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"
88 //config: hush is a small shell (25k). It handles the normal flow control
89 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
90 //config: case/esac. Redirections, here documents, $((arithmetic))
91 //config: and functions are supported.
93 //config: It will compile and work on no-mmu systems.
95 //config: It does not handle select, aliases, tilde expansion,
96 //config: &>file and >&file redirection of stdout+stderr.
98 //config:config HUSH_BASH_COMPAT
99 //config: bool "bash-compatible extensions"
101 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
103 //config:config HUSH_BRACE_EXPANSION
104 //config: bool "Brace expansion"
106 //config: depends on HUSH_BASH_COMPAT
108 //config: Enable {abc,def} extension.
110 //config:config HUSH_INTERACTIVE
111 //config: bool "Interactive mode"
113 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
115 //config: Enable interactive mode (prompt and command editing).
116 //config: Without this, hush simply reads and executes commands
117 //config: from stdin just like a shell script from a file.
118 //config: No prompt, no PS1/PS2 magic shell variables.
120 //config:config HUSH_SAVEHISTORY
121 //config: bool "Save command history to .hush_history"
123 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
125 //config:config HUSH_JOB
126 //config: bool "Job control"
128 //config: depends on HUSH_INTERACTIVE
130 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
131 //config: command (not entire shell), fg/bg builtins work. Without this option,
132 //config: "cmd &" still works by simply spawning a process and immediately
133 //config: prompting for next command (or executing next command in a script),
134 //config: but no separate process group is formed.
136 //config:config HUSH_TICK
137 //config: bool "Support process substitution"
139 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
141 //config: Enable `command` and $(command).
143 //config:config HUSH_IF
144 //config: bool "Support if/then/elif/else/fi"
146 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
148 //config:config HUSH_LOOPS
149 //config: bool "Support for, while and until loops"
151 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
153 //config:config HUSH_CASE
154 //config: bool "Support case ... esac statement"
156 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
158 //config: Enable case ... esac statement. +400 bytes.
160 //config:config HUSH_FUNCTIONS
161 //config: bool "Support funcname() { commands; } syntax"
163 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
165 //config: Enable support for shell functions. +800 bytes.
167 //config:config HUSH_LOCAL
168 //config: bool "local builtin"
170 //config: depends on HUSH_FUNCTIONS
172 //config: Enable support for local variables in functions.
174 //config:config HUSH_RANDOM_SUPPORT
175 //config: bool "Pseudorandom generator and $RANDOM variable"
177 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
179 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
180 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
182 //config:config HUSH_MODE_X
183 //config: bool "Support 'hush -x' option and 'set -x' command"
185 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
187 //config: This instructs hush to print commands before execution.
188 //config: Adds ~300 bytes.
190 //config:config HUSH_ECHO
191 //config: bool "echo builtin"
193 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
195 //config:config HUSH_PRINTF
196 //config: bool "printf builtin"
198 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
200 //config:config HUSH_TEST
201 //config: bool "test builtin"
203 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
205 //config:config HUSH_HELP
206 //config: bool "help builtin"
208 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
210 //config:config HUSH_EXPORT
211 //config: bool "export builtin"
213 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
215 //config:config HUSH_EXPORT_N
216 //config: bool "Support 'export -n' option"
218 //config: depends on HUSH_EXPORT
220 //config: export -n unexports variables. It is a bash extension.
222 //config:config HUSH_KILL
223 //config: bool "kill builtin (supports kill %jobspec)"
225 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227 //config:config HUSH_WAIT
228 //config: bool "wait builtin"
230 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
232 //config:config HUSH_TRAP
233 //config: bool "trap builtin"
235 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
237 //config:config HUSH_TYPE
238 //config: bool "type builtin"
240 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
242 //config:config HUSH_READ
243 //config: bool "read builtin"
245 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
247 //config:config HUSH_SET
248 //config: bool "set builtin"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config:config HUSH_UNSET
253 //config: bool "unset builtin"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_ULIMIT
258 //config: bool "ulimit builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_UMASK
263 //config: bool "umask builtin"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
267 //config:config HUSH_MEMLEAK
268 //config: bool "memleak builtin (debugging)"
270 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
273 // APPLET_ODDNAME:name main location suid_type help
274 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
275 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
277 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
278 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
279 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
280 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
282 /* -i (interactive) and -s (read stdin) are also accepted,
283 * but currently do nothing, therefore aren't shown in help.
284 * NOMMU-specific options are not meant to be used by users,
285 * therefore we don't show them either.
287 //usage:#define hush_trivial_usage
288 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
289 //usage:#define hush_full_usage "\n\n"
290 //usage: "Unix shell interpreter"
292 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
293 || defined(__APPLE__) \
295 # include <malloc.h> /* for malloc_trim */
298 /* #include <dmalloc.h> */
300 # include <fnmatch.h>
302 #include <sys/utsname.h> /* for setting $HOSTNAME */
304 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
306 #include "shell_common.h"
309 #if ENABLE_HUSH_RANDOM_SUPPORT
312 # define CLEAR_RANDOM_T(rnd) ((void)0)
314 #ifndef F_DUPFD_CLOEXEC
315 # define F_DUPFD_CLOEXEC F_DUPFD
318 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
322 /* So far, all bash compat is controlled by one config option */
323 /* Separate defines document which part of code implements what */
324 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
325 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
326 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
327 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
328 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
332 #define LEAK_HUNTING 0
333 #define BUILD_AS_NOMMU 0
334 /* Enable/disable sanity checks. Ok to enable in production,
335 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
336 * Keeping 1 for now even in released versions.
339 /* Slightly bigger (+200 bytes), but faster hush.
340 * So far it only enables a trick with counting SIGCHLDs and forks,
341 * which allows us to do fewer waitpid's.
342 * (we can detect a case where neither forks were done nor SIGCHLDs happened
343 * and therefore waitpid will return the same result as last time)
345 #define ENABLE_HUSH_FAST 0
346 /* TODO: implement simplified code for users which do not need ${var%...} ops
347 * So far ${var%...} ops are always enabled:
349 #define ENABLE_HUSH_DOLLAR_OPS 1
354 # undef USE_FOR_NOMMU
357 # define USE_FOR_NOMMU(...) __VA_ARGS__
358 # define USE_FOR_MMU(...)
361 #include "NUM_APPLETS.h"
363 /* STANDALONE does not make sense, and won't compile */
364 # undef CONFIG_FEATURE_SH_STANDALONE
365 # undef ENABLE_FEATURE_SH_STANDALONE
366 # undef IF_FEATURE_SH_STANDALONE
367 # undef IF_NOT_FEATURE_SH_STANDALONE
368 # define ENABLE_FEATURE_SH_STANDALONE 0
369 # define IF_FEATURE_SH_STANDALONE(...)
370 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
373 #if !ENABLE_HUSH_INTERACTIVE
374 # undef ENABLE_FEATURE_EDITING
375 # define ENABLE_FEATURE_EDITING 0
376 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
377 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
378 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
379 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
382 /* Do we support ANY keywords? */
383 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
384 # define HAS_KEYWORDS 1
385 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
386 # define IF_HAS_NO_KEYWORDS(...)
388 # define HAS_KEYWORDS 0
389 # define IF_HAS_KEYWORDS(...)
390 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
393 /* If you comment out one of these below, it will be #defined later
394 * to perform debug printfs to stderr: */
395 #define debug_printf(...) do {} while (0)
396 /* Finer-grained debug switches */
397 #define debug_printf_parse(...) do {} while (0)
398 #define debug_print_tree(a, b) do {} while (0)
399 #define debug_printf_exec(...) do {} while (0)
400 #define debug_printf_env(...) do {} while (0)
401 #define debug_printf_jobs(...) do {} while (0)
402 #define debug_printf_expand(...) do {} while (0)
403 #define debug_printf_varexp(...) do {} while (0)
404 #define debug_printf_glob(...) do {} while (0)
405 #define debug_printf_redir(...) do {} while (0)
406 #define debug_printf_list(...) do {} while (0)
407 #define debug_printf_subst(...) do {} while (0)
408 #define debug_printf_clean(...) do {} while (0)
410 #define ERR_PTR ((void*)(long)1)
412 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
414 #define _SPECIAL_VARS_STR "_*@$!?#"
415 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
416 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
417 #if BASH_PATTERN_SUBST
418 /* Support / and // replace ops */
419 /* Note that // is stored as \ in "encoded" string representation */
420 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
421 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
422 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
424 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
425 # define VAR_SUBST_OPS "%#:-=+?"
426 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
429 #define SPECIAL_VAR_SYMBOL 3
433 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
435 /* This supports saving pointers malloced in vfork child,
436 * to be freed in the parent.
439 typedef struct nommu_save_t {
441 struct variable *old_vars;
443 char **argv_from_re_execing;
456 #if ENABLE_HUSH_LOOPS
463 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
468 /* three pseudo-keywords support contrived "case" syntax: */
469 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
470 RES_MATCH , /* "word)" */
471 RES_CASE_BODY, /* "this command is inside CASE" */
478 typedef struct o_string {
480 int length; /* position where data is appended */
483 /* At least some part of the string was inside '' or "",
484 * possibly empty one: word"", wo''rd etc. */
485 smallint has_quoted_part;
486 smallint has_empty_slot;
487 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
490 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
492 /* Protect newly added chars against globbing
493 * by prepending \ to *, ?, [, \ */
494 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
497 MAYBE_ASSIGNMENT = 0,
498 DEFINITELY_ASSIGNMENT = 1,
500 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
503 /* Used for initialization: o_string foo = NULL_O_STRING; */
504 #define NULL_O_STRING { NULL }
506 #ifndef debug_printf_parse
507 static const char *const assignment_flag[] = {
509 "DEFINITELY_ASSIGNMENT",
515 typedef struct in_str {
517 #if ENABLE_HUSH_INTERACTIVE
518 smallint promptmode; /* 0: PS1, 1: PS2 */
525 /* The descrip member of this structure is only used to make
526 * debugging output pretty */
527 static const struct {
529 signed char default_fd;
532 { O_RDONLY, 0, "<" },
533 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
534 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
535 { O_CREAT|O_RDWR, 1, "<>" },
536 { O_RDONLY, 0, "<<" },
537 /* Should not be needed. Bogus default_fd helps in debugging */
538 /* { O_RDONLY, 77, "<<" }, */
541 struct redir_struct {
542 struct redir_struct *next;
543 char *rd_filename; /* filename */
544 int rd_fd; /* fd to redirect */
545 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
547 smallint rd_type; /* (enum redir_type) */
548 /* note: for heredocs, rd_filename contains heredoc delimiter,
549 * and subsequently heredoc itself; and rd_dup is a bitmask:
550 * bit 0: do we need to trim leading tabs?
551 * bit 1: is heredoc quoted (<<'delim' syntax) ?
554 typedef enum redir_type {
556 REDIRECT_OVERWRITE = 1,
559 REDIRECT_HEREDOC = 4,
560 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
563 REDIRFD_SYNTAX_ERR = -2,
564 REDIRFD_TO_FILE = -1,
565 /* otherwise, rd_fd is redirected to rd_dup */
567 HEREDOC_SKIPTABS = 1,
573 pid_t pid; /* 0 if exited */
574 int assignment_cnt; /* how many argv[i] are assignments? */
575 smallint cmd_type; /* CMD_xxx */
577 #define CMD_SUBSHELL 1
579 /* used for "[[ EXPR ]]" */
580 # define CMD_SINGLEWORD_NOGLOB 2
582 #if ENABLE_HUSH_FUNCTIONS
583 # define CMD_FUNCDEF 3
586 smalluint cmd_exitcode;
587 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
590 char *group_as_string;
592 #if ENABLE_HUSH_FUNCTIONS
593 struct function *child_func;
594 /* This field is used to prevent a bug here:
595 * while...do f1() {a;}; f1; f1() {b;}; f1; done
596 * When we execute "f1() {a;}" cmd, we create new function and clear
597 * cmd->group, cmd->group_as_string, cmd->argv[0].
598 * When we execute "f1() {b;}", we notice that f1 exists,
599 * and that its "parent cmd" struct is still "alive",
600 * we put those fields back into cmd->xxx
601 * (struct function has ->parent_cmd ptr to facilitate that).
602 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
603 * Without this trick, loop would execute a;b;b;b;...
604 * instead of correct sequence a;b;a;b;...
605 * When command is freed, it severs the link
606 * (sets ->child_func->parent_cmd to NULL).
609 char **argv; /* command name and arguments */
610 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
611 * and on execution these are substituted with their values.
612 * Substitution can make _several_ words out of one argv[n]!
613 * Example: argv[0]=='.^C*^C.' here: echo .$*.
614 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
616 struct redir_struct *redirects; /* I/O redirections */
618 /* Is there anything in this command at all? */
619 #define IS_NULL_CMD(cmd) \
620 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
624 int num_cmds; /* total number of commands in pipe */
625 int alive_cmds; /* number of commands running (not exited) */
626 int stopped_cmds; /* number of commands alive, but stopped */
628 unsigned jobid; /* job number */
629 pid_t pgrp; /* process group ID for the job */
630 char *cmdtext; /* name of job */
632 struct command *cmds; /* array of commands in pipe */
633 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
634 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
635 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
637 typedef enum pipe_style {
643 /* Is there anything in this pipe at all? */
644 #define IS_NULL_PIPE(pi) \
645 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
647 /* This holds pointers to the various results of parsing */
648 struct parse_context {
649 /* linked list of pipes */
650 struct pipe *list_head;
651 /* last pipe (being constructed right now) */
653 /* last command in pipe (being constructed right now) */
654 struct command *command;
655 /* last redirect in command->redirects list */
656 struct redir_struct *pending_redirect;
662 smallint ctx_inverted; /* "! cmd | cmd" */
664 smallint ctx_dsemicolon; /* ";;" seen */
666 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
668 /* group we are enclosed in:
669 * example: "if pipe1; pipe2; then pipe3; fi"
670 * when we see "if" or "then", we malloc and copy current context,
671 * and make ->stack point to it. then we parse pipeN.
672 * when closing "then" / fi" / whatever is found,
673 * we move list_head into ->stack->command->group,
674 * copy ->stack into current context, and delete ->stack.
675 * (parsing of { list } and ( list ) doesn't use this method)
677 struct parse_context *stack;
681 /* On program start, environ points to initial environment.
682 * putenv adds new pointers into it, unsetenv removes them.
683 * Neither of these (de)allocates the strings.
684 * setenv allocates new strings in malloc space and does putenv,
685 * and thus setenv is unusable (leaky) for shell's purposes */
686 #define setenv(...) setenv_is_leaky_dont_use()
688 struct variable *next;
689 char *varstr; /* points to "name=" portion */
690 #if ENABLE_HUSH_LOCAL
691 unsigned func_nest_level;
693 int max_len; /* if > 0, name is part of initial env; else name is malloced */
694 smallint flg_export; /* putenv should be done on this var */
695 smallint flg_read_only;
703 #if ENABLE_HUSH_FUNCTIONS
705 struct function *next;
707 struct command *parent_cmd;
710 char *body_as_string;
716 /* set -/+o OPT support. (TODO: make it optional)
717 * bash supports the following opts:
728 * interactive-comments on
746 static const char o_opt_strings[] ALIGN1 =
749 #if ENABLE_HUSH_MODE_X
756 #if ENABLE_HUSH_MODE_X
764 struct FILE_list *next;
770 /* "Globals" within this file */
771 /* Sorted roughly by size (smaller offsets == smaller code) */
773 /* interactive_fd != 0 means we are an interactive shell.
774 * If we are, then saved_tty_pgrp can also be != 0, meaning
775 * that controlling tty is available. With saved_tty_pgrp == 0,
776 * job control still works, but terminal signals
777 * (^C, ^Z, ^Y, ^\) won't work at all, and background
778 * process groups can only be created with "cmd &".
779 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
780 * to give tty to the foreground process group,
781 * and will take it back when the group is stopped (^Z)
784 #if ENABLE_HUSH_INTERACTIVE
785 /* 'interactive_fd' is a fd# open to ctty, if we have one
786 * _AND_ if we decided to act interactively */
790 # define G_interactive_fd (G.interactive_fd)
792 # define G_interactive_fd 0
794 #if ENABLE_FEATURE_EDITING
795 line_input_t *line_input_state;
800 #if ENABLE_HUSH_RANDOM_SUPPORT
806 pid_t saved_tty_pgrp;
807 struct pipe *job_list;
808 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
810 # define G_saved_tty_pgrp 0
812 char o_opt[NUM_OPT_O];
813 #if ENABLE_HUSH_MODE_X
814 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
818 smallint flag_SIGINT;
819 #if ENABLE_HUSH_LOOPS
820 smallint flag_break_continue;
822 #if ENABLE_HUSH_FUNCTIONS
823 /* 0: outside of a function (or sourced file)
824 * -1: inside of a function, ok to use return builtin
825 * 1: return is invoked, skip all till end of func
827 smallint flag_return_in_progress;
828 # define G_flag_return_in_progress (G.flag_return_in_progress)
830 # define G_flag_return_in_progress 0
832 smallint exiting; /* used to prevent EXIT trap recursion */
833 /* These four support $?, $#, and $1 */
834 smalluint last_exitcode;
835 smalluint last_bg_pid_exitcode;
837 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
838 smalluint global_args_malloced;
839 # define G_global_args_malloced (G.global_args_malloced)
841 # define G_global_args_malloced 0
843 /* how many non-NULL argv's we have. NB: $# + 1 */
847 char *argv0_for_re_execing;
849 #if ENABLE_HUSH_LOOPS
850 unsigned depth_break_continue;
851 unsigned depth_of_loop;
855 struct variable *top_var;
856 char **expanded_assignments;
857 #if ENABLE_HUSH_FUNCTIONS
858 struct function *top_func;
859 # if ENABLE_HUSH_LOCAL
860 struct variable **shadowed_vars_pp;
861 unsigned func_nest_level;
864 /* Signal and trap handling */
866 unsigned count_SIGCHLD;
867 unsigned handled_SIGCHLD;
868 smallint we_have_children;
870 struct FILE_list *FILE_list;
871 /* Which signals have non-DFL handler (even with no traps set)?
872 * Set at the start to:
873 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
874 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
875 * The rest is cleared right before execv syscalls.
876 * Other than these two times, never modified.
878 unsigned special_sig_mask;
880 unsigned fatal_sig_mask;
881 # define G_fatal_sig_mask (G.fatal_sig_mask)
883 # define G_fatal_sig_mask 0
886 char **traps; /* char *traps[NSIG] */
887 # define G_traps G.traps
889 # define G_traps ((char**)NULL)
891 sigset_t pending_set;
892 #if ENABLE_HUSH_MEMLEAK
893 unsigned long memleak_value;
899 #if ENABLE_FEATURE_EDITING
900 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
903 #define G (*ptr_to_globals)
904 /* Not #defining name to G.name - this quickly gets unwieldy
905 * (too many defines). Also, I actually prefer to see when a variable
906 * is global, thus "G." prefix is a useful hint */
907 #define INIT_G() do { \
908 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
909 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
910 sigfillset(&G.sa.sa_mask); \
911 G.sa.sa_flags = SA_RESTART; \
915 /* Function prototypes for builtins */
916 static int builtin_cd(char **argv) FAST_FUNC;
918 static int builtin_echo(char **argv) FAST_FUNC;
920 static int builtin_eval(char **argv) FAST_FUNC;
921 static int builtin_exec(char **argv) FAST_FUNC;
922 static int builtin_exit(char **argv) FAST_FUNC;
923 #if ENABLE_HUSH_EXPORT
924 static int builtin_export(char **argv) FAST_FUNC;
927 static int builtin_fg_bg(char **argv) FAST_FUNC;
928 static int builtin_jobs(char **argv) FAST_FUNC;
931 static int builtin_help(char **argv) FAST_FUNC;
933 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
934 static int builtin_history(char **argv) FAST_FUNC;
936 #if ENABLE_HUSH_LOCAL
937 static int builtin_local(char **argv) FAST_FUNC;
939 #if ENABLE_HUSH_MEMLEAK
940 static int builtin_memleak(char **argv) FAST_FUNC;
942 #if ENABLE_HUSH_PRINTF
943 static int builtin_printf(char **argv) FAST_FUNC;
945 static int builtin_pwd(char **argv) FAST_FUNC;
947 static int builtin_read(char **argv) FAST_FUNC;
950 static int builtin_set(char **argv) FAST_FUNC;
952 static int builtin_shift(char **argv) FAST_FUNC;
953 static int builtin_source(char **argv) FAST_FUNC;
954 #if ENABLE_HUSH_TEST || BASH_TEST2
955 static int builtin_test(char **argv) FAST_FUNC;
958 static int builtin_trap(char **argv) FAST_FUNC;
961 static int builtin_type(char **argv) FAST_FUNC;
963 static int builtin_true(char **argv) FAST_FUNC;
964 #if ENABLE_HUSH_UMASK
965 static int builtin_umask(char **argv) FAST_FUNC;
967 #if ENABLE_HUSH_UNSET
968 static int builtin_unset(char **argv) FAST_FUNC;
971 static int builtin_kill(char **argv) FAST_FUNC;
974 static int builtin_wait(char **argv) FAST_FUNC;
976 #if ENABLE_HUSH_LOOPS
977 static int builtin_break(char **argv) FAST_FUNC;
978 static int builtin_continue(char **argv) FAST_FUNC;
980 #if ENABLE_HUSH_FUNCTIONS
981 static int builtin_return(char **argv) FAST_FUNC;
984 /* Table of built-in functions. They can be forked or not, depending on
985 * context: within pipes, they fork. As simple commands, they do not.
986 * When used in non-forking context, they can change global variables
987 * in the parent shell process. If forked, of course they cannot.
988 * For example, 'unset foo | whatever' will parse and run, but foo will
989 * still be set at the end. */
990 struct built_in_command {
992 int (*b_function)(char **argv) FAST_FUNC;
995 # define BLTIN(cmd, func, help) { cmd, func, help }
997 # define BLTIN(cmd, func, help) { cmd, func }
1001 static const struct built_in_command bltins1[] = {
1002 BLTIN("." , builtin_source , "Run commands in file"),
1003 BLTIN(":" , builtin_true , NULL),
1005 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1007 #if ENABLE_HUSH_LOOPS
1008 BLTIN("break" , builtin_break , "Exit loop"),
1010 BLTIN("cd" , builtin_cd , "Change directory"),
1011 #if ENABLE_HUSH_LOOPS
1012 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1014 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1015 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1016 BLTIN("exit" , builtin_exit , NULL),
1017 #if ENABLE_HUSH_EXPORT
1018 BLTIN("export" , builtin_export , "Set environment variables"),
1021 BLTIN("fg" , builtin_fg_bg , "Bring job into foreground"),
1023 #if ENABLE_HUSH_HELP
1024 BLTIN("help" , builtin_help , NULL),
1026 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1027 BLTIN("history" , builtin_history , "Show history"),
1030 BLTIN("jobs" , builtin_jobs , "List jobs"),
1032 #if ENABLE_HUSH_KILL
1033 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1035 #if ENABLE_HUSH_LOCAL
1036 BLTIN("local" , builtin_local , "Set local variables"),
1038 #if ENABLE_HUSH_MEMLEAK
1039 BLTIN("memleak" , builtin_memleak , NULL),
1041 #if ENABLE_HUSH_READ
1042 BLTIN("read" , builtin_read , "Input into variable"),
1044 #if ENABLE_HUSH_FUNCTIONS
1045 BLTIN("return" , builtin_return , "Return from function"),
1048 BLTIN("set" , builtin_set , "Set positional parameters"),
1050 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1052 BLTIN("source" , builtin_source , NULL),
1054 #if ENABLE_HUSH_TRAP
1055 BLTIN("trap" , builtin_trap , "Trap signals"),
1057 BLTIN("true" , builtin_true , NULL),
1058 #if ENABLE_HUSH_TYPE
1059 BLTIN("type" , builtin_type , "Show command type"),
1061 #if ENABLE_HUSH_ULIMIT
1062 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1064 #if ENABLE_HUSH_UMASK
1065 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1067 #if ENABLE_HUSH_UNSET
1068 BLTIN("unset" , builtin_unset , "Unset variables"),
1070 #if ENABLE_HUSH_WAIT
1071 BLTIN("wait" , builtin_wait , "Wait for process"),
1074 /* These builtins won't be used if we are on NOMMU and need to re-exec
1075 * (it's cheaper to run an external program in this case):
1077 static const struct built_in_command bltins2[] = {
1078 #if ENABLE_HUSH_TEST
1079 BLTIN("[" , builtin_test , NULL),
1082 BLTIN("[[" , builtin_test , NULL),
1084 #if ENABLE_HUSH_ECHO
1085 BLTIN("echo" , builtin_echo , NULL),
1087 #if ENABLE_HUSH_PRINTF
1088 BLTIN("printf" , builtin_printf , NULL),
1090 BLTIN("pwd" , builtin_pwd , NULL),
1091 #if ENABLE_HUSH_TEST
1092 BLTIN("test" , builtin_test , NULL),
1100 /* prevent disasters with G.debug_indent < 0 */
1101 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1102 # define debug_enter() (G.debug_indent++)
1103 # define debug_leave() (G.debug_indent--)
1105 # define indent() ((void)0)
1106 # define debug_enter() ((void)0)
1107 # define debug_leave() ((void)0)
1110 #ifndef debug_printf
1111 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1114 #ifndef debug_printf_parse
1115 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1118 #ifndef debug_printf_exec
1119 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1122 #ifndef debug_printf_env
1123 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1126 #ifndef debug_printf_jobs
1127 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1128 # define DEBUG_JOBS 1
1130 # define DEBUG_JOBS 0
1133 #ifndef debug_printf_expand
1134 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1135 # define DEBUG_EXPAND 1
1137 # define DEBUG_EXPAND 0
1140 #ifndef debug_printf_varexp
1141 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1144 #ifndef debug_printf_glob
1145 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1146 # define DEBUG_GLOB 1
1148 # define DEBUG_GLOB 0
1151 #ifndef debug_printf_redir
1152 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1155 #ifndef debug_printf_list
1156 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1159 #ifndef debug_printf_subst
1160 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1163 #ifndef debug_printf_clean
1164 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1165 # define DEBUG_CLEAN 1
1167 # define DEBUG_CLEAN 0
1171 static void debug_print_strings(const char *prefix, char **vv)
1174 fdprintf(2, "%s:\n", prefix);
1176 fdprintf(2, " '%s'\n", *vv++);
1179 # define debug_print_strings(prefix, vv) ((void)0)
1183 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1186 static void *xxmalloc(int lineno, size_t size)
1188 void *ptr = xmalloc((size + 0xff) & ~0xff);
1189 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1192 static void *xxrealloc(int lineno, void *ptr, size_t size)
1194 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1195 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1198 static char *xxstrdup(int lineno, const char *str)
1200 char *ptr = xstrdup(str);
1201 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1204 static void xxfree(void *ptr)
1206 fdprintf(2, "free %p\n", ptr);
1209 # define xmalloc(s) xxmalloc(__LINE__, s)
1210 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1211 # define xstrdup(s) xxstrdup(__LINE__, s)
1212 # define free(p) xxfree(p)
1216 /* Syntax and runtime errors. They always abort scripts.
1217 * In interactive use they usually discard unparsed and/or unexecuted commands
1218 * and return to the prompt.
1219 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1222 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1223 # define syntax_error(lineno, msg) syntax_error(msg)
1224 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1225 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1226 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1227 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1230 static void die_if_script(unsigned lineno, const char *fmt, ...)
1235 bb_error_msg("hush.c:%u", lineno);
1238 bb_verror_msg(fmt, p, NULL);
1240 if (!G_interactive_fd)
1244 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1247 bb_error_msg("syntax error: %s", msg);
1249 bb_error_msg("syntax error");
1252 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1254 bb_error_msg("syntax error at '%s'", msg);
1257 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1259 bb_error_msg("syntax error: unterminated %s", s);
1262 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1264 char msg[2] = { ch, '\0' };
1265 syntax_error_unterm_str(lineno, msg);
1268 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1274 bb_error_msg("hush.c:%u", lineno);
1276 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1280 # undef die_if_script
1281 # undef syntax_error
1282 # undef syntax_error_at
1283 # undef syntax_error_unterm_ch
1284 # undef syntax_error_unterm_str
1285 # undef syntax_error_unexpected_ch
1287 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1288 # define syntax_error(msg) syntax_error(__LINE__, msg)
1289 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1290 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1291 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1292 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1296 #if ENABLE_HUSH_INTERACTIVE
1297 static void cmdedit_update_prompt(void);
1299 # define cmdedit_update_prompt() ((void)0)
1303 /* Utility functions
1305 /* Replace each \x with x in place, return ptr past NUL. */
1306 static char *unbackslash(char *src)
1308 char *dst = src = strchrnul(src, '\\');
1312 if ((*dst++ = *src++) == '\0')
1318 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1339 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1340 v[count1 + count2] = NULL;
1343 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1347 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1349 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1350 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1353 #define add_strings_to_strings(strings, add, need_to_dup) \
1354 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1357 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1358 static char **add_string_to_strings(char **strings, char *add)
1363 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1366 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1368 char **ptr = add_string_to_strings(strings, add);
1369 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1372 #define add_string_to_strings(strings, add) \
1373 xx_add_string_to_strings(__LINE__, strings, add)
1376 static void free_strings(char **strings)
1390 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1394 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1404 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC, int avoid_fd)
1408 newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, avoid_fd + 1);
1414 /* fd was not open? */
1424 /* Manipulating the list of open FILEs */
1425 static FILE *remember_FILE(FILE *fp)
1428 struct FILE_list *n = xmalloc(sizeof(*n));
1429 n->next = G.FILE_list;
1433 close_on_exec_on(n->fd);
1437 static void fclose_and_forget(FILE *fp)
1439 struct FILE_list **pp = &G.FILE_list;
1441 struct FILE_list *cur = *pp;
1442 if (cur->fp == fp) {
1451 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1453 struct FILE_list *fl = G.FILE_list;
1456 /* We use it only on script files, they are all CLOEXEC */
1457 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC, avoid_fd);
1458 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1465 static void restore_redirected_FILEs(void)
1467 struct FILE_list *fl = G.FILE_list;
1469 int should_be = fileno(fl->fp);
1470 if (fl->fd != should_be) {
1471 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1472 xmove_fd(fl->fd, should_be);
1478 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1479 static void close_all_FILE_list(void)
1481 struct FILE_list *fl = G.FILE_list;
1483 /* fclose would also free FILE object.
1484 * It is disastrous if we share memory with a vforked parent.
1485 * I'm not sure we never come here after vfork.
1486 * Therefore just close fd, nothing more.
1488 /*fclose(fl->fp); - unsafe */
1496 /* Helpers for setting new $n and restoring them back
1498 typedef struct save_arg_t {
1502 IF_HUSH_SET(smallint sv_g_malloced;)
1505 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1507 sv->sv_argv0 = argv[0];
1508 sv->sv_g_argv = G.global_argv;
1509 sv->sv_g_argc = G.global_argc;
1510 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1512 argv[0] = G.global_argv[0]; /* retain $0 */
1513 G.global_argv = argv;
1514 IF_HUSH_SET(G.global_args_malloced = 0;)
1516 G.global_argc = 1 + string_array_len(argv + 1);
1519 static void restore_G_args(save_arg_t *sv, char **argv)
1522 if (G.global_args_malloced) {
1523 /* someone ran "set -- arg1 arg2 ...", undo */
1524 char **pp = G.global_argv;
1525 while (*++pp) /* note: does not free $0 */
1527 free(G.global_argv);
1530 argv[0] = sv->sv_argv0;
1531 G.global_argv = sv->sv_g_argv;
1532 G.global_argc = sv->sv_g_argc;
1533 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1537 /* Basic theory of signal handling in shell
1538 * ========================================
1539 * This does not describe what hush does, rather, it is current understanding
1540 * what it _should_ do. If it doesn't, it's a bug.
1541 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1543 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1544 * is finished or backgrounded. It is the same in interactive and
1545 * non-interactive shells, and is the same regardless of whether
1546 * a user trap handler is installed or a shell special one is in effect.
1547 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1548 * backgrounds (i.e. stops) or kills all members of currently running
1551 * Wait builtin is interruptible by signals for which user trap is set
1552 * or by SIGINT in interactive shell.
1554 * Trap handlers will execute even within trap handlers. (right?)
1556 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1557 * except for handlers set to '' (empty string).
1559 * If job control is off, backgrounded commands ("cmd &")
1560 * have SIGINT, SIGQUIT set to SIG_IGN.
1562 * Commands which are run in command substitution ("`cmd`")
1563 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1565 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1566 * by the shell from its parent.
1568 * Signals which differ from SIG_DFL action
1569 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1572 * SIGTERM (interactive): ignore
1573 * SIGHUP (interactive):
1574 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1575 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1576 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1577 * that all pipe members are stopped. Try this in bash:
1578 * while :; do :; done - ^Z does not background it
1579 * (while :; do :; done) - ^Z backgrounds it
1580 * SIGINT (interactive): wait for last pipe, ignore the rest
1581 * of the command line, show prompt. NB: ^C does not send SIGINT
1582 * to interactive shell while shell is waiting for a pipe,
1583 * since shell is bg'ed (is not in foreground process group).
1584 * Example 1: this waits 5 sec, but does not execute ls:
1585 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1586 * Example 2: this does not wait and does not execute ls:
1587 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1588 * Example 3: this does not wait 5 sec, but executes ls:
1589 * "sleep 5; ls -l" + press ^C
1590 * Example 4: this does not wait and does not execute ls:
1591 * "sleep 5 & wait; ls -l" + press ^C
1593 * (What happens to signals which are IGN on shell start?)
1594 * (What happens with signal mask on shell start?)
1596 * Old implementation
1597 * ==================
1598 * We use in-kernel pending signal mask to determine which signals were sent.
1599 * We block all signals which we don't want to take action immediately,
1600 * i.e. we block all signals which need to have special handling as described
1601 * above, and all signals which have traps set.
1602 * After each pipe execution, we extract any pending signals via sigtimedwait()
1605 * unsigned special_sig_mask: a mask of such "special" signals
1606 * sigset_t blocked_set: current blocked signal set
1609 * clear bit in blocked_set unless it is also in special_sig_mask
1610 * "trap 'cmd' SIGxxx":
1611 * set bit in blocked_set (even if 'cmd' is '')
1612 * after [v]fork, if we plan to be a shell:
1613 * unblock signals with special interactive handling
1614 * (child shell is not interactive),
1615 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1616 * after [v]fork, if we plan to exec:
1617 * POSIX says fork clears pending signal mask in child - no need to clear it.
1618 * Restore blocked signal set to one inherited by shell just prior to exec.
1620 * Note: as a result, we do not use signal handlers much. The only uses
1621 * are to count SIGCHLDs
1622 * and to restore tty pgrp on signal-induced exit.
1625 * Standard says "When a subshell is entered, traps that are not being ignored
1626 * are set to the default actions". bash interprets it so that traps which
1627 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1629 * Problem: the above approach makes it unwieldy to catch signals while
1630 * we are in read builtin, or while we read commands from stdin:
1631 * masked signals are not visible!
1633 * New implementation
1634 * ==================
1635 * We record each signal we are interested in by installing signal handler
1636 * for them - a bit like emulating kernel pending signal mask in userspace.
1637 * We are interested in: signals which need to have special handling
1638 * as described above, and all signals which have traps set.
1639 * Signals are recorded in pending_set.
1640 * After each pipe execution, we extract any pending signals
1643 * unsigned special_sig_mask: a mask of shell-special signals.
1644 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1645 * char *traps[sig] if trap for sig is set (even if it's '').
1646 * sigset_t pending_set: set of sigs we received.
1649 * if sig is in special_sig_mask, set handler back to:
1650 * record_pending_signo, or to IGN if it's a tty stop signal
1651 * if sig is in fatal_sig_mask, set handler back to sigexit.
1652 * else: set handler back to SIG_DFL
1653 * "trap 'cmd' SIGxxx":
1654 * set handler to record_pending_signo.
1656 * set handler to SIG_IGN.
1657 * after [v]fork, if we plan to be a shell:
1658 * set signals with special interactive handling to SIG_DFL
1659 * (because child shell is not interactive),
1660 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1661 * after [v]fork, if we plan to exec:
1662 * POSIX says fork clears pending signal mask in child - no need to clear it.
1664 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1665 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1668 * Standard says "When a subshell is entered, traps that are not being ignored
1669 * are set to the default actions". bash interprets it so that traps which
1670 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1673 SPECIAL_INTERACTIVE_SIGS = 0
1678 SPECIAL_JOBSTOP_SIGS = 0
1687 static void record_pending_signo(int sig)
1689 sigaddset(&G.pending_set, sig);
1690 #if ENABLE_HUSH_FAST
1691 if (sig == SIGCHLD) {
1693 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1698 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1700 struct sigaction old_sa;
1702 /* We could use signal() to install handlers... almost:
1703 * except that we need to mask ALL signals while handlers run.
1704 * I saw signal nesting in strace, race window isn't small.
1705 * SA_RESTART is also needed, but in Linux, signal()
1706 * sets SA_RESTART too.
1708 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1709 /* sigfillset(&G.sa.sa_mask); - already done */
1710 /* G.sa.sa_flags = SA_RESTART; - already done */
1711 G.sa.sa_handler = handler;
1712 sigaction(sig, &G.sa, &old_sa);
1713 return old_sa.sa_handler;
1716 static void hush_exit(int exitcode) NORETURN;
1718 static void restore_ttypgrp_and__exit(void) NORETURN;
1719 static void restore_ttypgrp_and__exit(void)
1721 /* xfunc has failed! die die die */
1722 /* no EXIT traps, this is an escape hatch! */
1724 hush_exit(xfunc_error_retval);
1729 /* Needed only on some libc:
1730 * It was observed that on exit(), fgetc'ed buffered data
1731 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1732 * With the net effect that even after fork(), not vfork(),
1733 * exit() in NOEXECed applet in "sh SCRIPT":
1734 * noexec_applet_here
1735 * echo END_OF_SCRIPT
1736 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1737 * This makes "echo END_OF_SCRIPT" executed twice.
1738 * Similar problems can be seen with die_if_script() -> xfunc_die()
1739 * and in `cmd` handling.
1740 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1742 static void fflush_and__exit(void) NORETURN;
1743 static void fflush_and__exit(void)
1746 _exit(xfunc_error_retval);
1749 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1750 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1751 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1752 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1754 /* Restores tty foreground process group, and exits.
1755 * May be called as signal handler for fatal signal
1756 * (will resend signal to itself, producing correct exit state)
1757 * or called directly with -EXITCODE.
1758 * We also call it if xfunc is exiting.
1760 static void sigexit(int sig) NORETURN;
1761 static void sigexit(int sig)
1763 /* Careful: we can end up here after [v]fork. Do not restore
1764 * tty pgrp then, only top-level shell process does that */
1765 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1766 /* Disable all signals: job control, SIGPIPE, etc.
1767 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1769 sigprocmask_allsigs(SIG_BLOCK);
1770 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1773 /* Not a signal, just exit */
1777 kill_myself_with_sig(sig); /* does not return */
1781 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1782 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1786 static sighandler_t pick_sighandler(unsigned sig)
1788 sighandler_t handler = SIG_DFL;
1789 if (sig < sizeof(unsigned)*8) {
1790 unsigned sigmask = (1 << sig);
1794 if (G_fatal_sig_mask & sigmask)
1798 /* sig has special handling? */
1799 if (G.special_sig_mask & sigmask) {
1800 handler = record_pending_signo;
1801 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1802 * in order to ignore them: they will be raised
1803 * in an endless loop when we try to do some
1804 * terminal ioctls! We do have to _ignore_ these.
1806 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1813 /* Restores tty foreground process group, and exits. */
1814 static void hush_exit(int exitcode)
1816 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1817 save_history(G.line_input_state);
1821 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1823 /* argv[0] is unused */
1824 argv[1] = G_traps[0];
1826 G.exiting = 1; /* prevent EXIT trap recursion */
1827 /* Note: G_traps[0] is not cleared!
1828 * "trap" will still show it, if executed
1833 #if ENABLE_FEATURE_CLEAN_UP
1835 struct variable *cur_var;
1836 if (G.cwd != bb_msg_unknown)
1838 cur_var = G.top_var;
1840 struct variable *tmp = cur_var;
1841 if (!cur_var->max_len)
1842 free(cur_var->varstr);
1843 cur_var = cur_var->next;
1851 sigexit(- (exitcode & 0xff));
1858 //TODO: return a mask of ALL handled sigs?
1859 static int check_and_run_traps(void)
1866 if (sigisemptyset(&G.pending_set))
1871 if (sigismember(&G.pending_set, sig)) {
1872 sigdelset(&G.pending_set, sig);
1875 } while (sig < NSIG);
1878 if (G_traps && G_traps[sig]) {
1879 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1880 if (G_traps[sig][0]) {
1881 /* We have user-defined handler */
1882 smalluint save_rcode;
1884 /* argv[0] is unused */
1885 argv[1] = G_traps[sig];
1887 save_rcode = G.last_exitcode;
1889 //FIXME: shouldn't it be set to 128 + sig instead?
1890 G.last_exitcode = save_rcode;
1892 } /* else: "" trap, ignoring signal */
1895 /* not a trap: special action */
1898 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1905 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1906 /* bash is observed to signal whole process groups,
1907 * not individual processes */
1908 for (job = G.job_list; job; job = job->next) {
1911 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1912 if (kill(- job->pgrp, SIGHUP) == 0)
1913 kill(- job->pgrp, SIGCONT);
1918 #if ENABLE_HUSH_FAST
1920 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1922 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1924 * We don't do 'last_sig = sig' here -> NOT returning this sig.
1925 * This simplifies wait builtin a bit.
1929 default: /* ignored: */
1930 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1931 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1933 * We don't do 'last_sig = sig' here -> NOT returning this sig.
1934 * Example: wait is not interrupted by TERM
1935 * in interactive shell, because TERM is ignored.
1944 static const char *get_cwd(int force)
1946 if (force || G.cwd == NULL) {
1947 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1948 * we must not try to free(bb_msg_unknown) */
1949 if (G.cwd == bb_msg_unknown)
1951 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1953 G.cwd = bb_msg_unknown;
1960 * Shell and environment variable support
1962 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1964 struct variable **pp;
1965 struct variable *cur;
1968 while ((cur = *pp) != NULL) {
1969 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1976 static const char* FAST_FUNC get_local_var_value(const char *name)
1978 struct variable **vpp;
1979 unsigned len = strlen(name);
1981 if (G.expanded_assignments) {
1982 char **cpp = G.expanded_assignments;
1985 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1986 return cp + len + 1;
1991 vpp = get_ptr_to_local_var(name, len);
1993 return (*vpp)->varstr + len + 1;
1995 if (strcmp(name, "PPID") == 0)
1996 return utoa(G.root_ppid);
1997 // bash compat: UID? EUID?
1998 #if ENABLE_HUSH_RANDOM_SUPPORT
1999 if (strcmp(name, "RANDOM") == 0)
2000 return utoa(next_random(&G.random_gen));
2005 /* str holds "NAME=VAL" and is expected to be malloced.
2006 * We take ownership of it.
2008 * 0: do not change export flag
2009 * (if creating new variable, flag will be 0)
2010 * 1: set export flag and putenv the variable
2011 * -1: clear export flag and unsetenv the variable
2012 * flg_read_only is set only when we handle -R var=val
2014 #if !BB_MMU && ENABLE_HUSH_LOCAL
2015 /* all params are used */
2016 #elif BB_MMU && ENABLE_HUSH_LOCAL
2017 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2018 set_local_var(str, flg_export, local_lvl)
2019 #elif BB_MMU && !ENABLE_HUSH_LOCAL
2020 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2021 set_local_var(str, flg_export)
2022 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
2023 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2024 set_local_var(str, flg_export, flg_read_only)
2026 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
2028 struct variable **var_pp;
2029 struct variable *cur;
2030 char *free_me = NULL;
2034 eq_sign = strchr(str, '=');
2035 if (!eq_sign) { /* not expected to ever happen? */
2040 name_len = eq_sign - str + 1; /* including '=' */
2041 var_pp = &G.top_var;
2042 while ((cur = *var_pp) != NULL) {
2043 if (strncmp(cur->varstr, str, name_len) != 0) {
2044 var_pp = &cur->next;
2048 /* We found an existing var with this name */
2049 if (cur->flg_read_only) {
2053 bb_error_msg("%s: readonly variable", str);
2057 if (flg_export == -1) { // "&& cur->flg_export" ?
2058 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2063 #if ENABLE_HUSH_LOCAL
2064 if (cur->func_nest_level < local_lvl) {
2065 /* New variable is declared as local,
2066 * and existing one is global, or local
2067 * from enclosing function.
2068 * Remove and save old one: */
2069 *var_pp = cur->next;
2070 cur->next = *G.shadowed_vars_pp;
2071 *G.shadowed_vars_pp = cur;
2072 /* bash 3.2.33(1) and exported vars:
2074 * # f() { local z=a; env | grep ^z; }
2080 if (cur->flg_export)
2085 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2090 if (cur->max_len != 0) {
2091 if (cur->max_len >= strlen(str)) {
2092 /* This one is from startup env, reuse space */
2093 strcpy(cur->varstr, str);
2098 goto set_str_and_exp;
2100 /* max_len == 0 signifies "malloced" var, which we can
2101 * (and have to) free. But we can't free(cur->varstr) here:
2102 * if cur->flg_export is 1, it is in the environment.
2103 * We should either unsetenv+free, or wait until putenv,
2104 * then putenv(new)+free(old).
2106 free_me = cur->varstr;
2107 goto set_str_and_exp;
2110 /* Not found - create new variable struct */
2111 cur = xzalloc(sizeof(*cur));
2112 #if ENABLE_HUSH_LOCAL
2113 cur->func_nest_level = local_lvl;
2115 cur->next = *var_pp;
2121 cur->flg_read_only = flg_read_only;
2124 if (flg_export == 1)
2125 cur->flg_export = 1;
2126 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2127 cmdedit_update_prompt();
2128 if (cur->flg_export) {
2129 if (flg_export == -1) {
2130 cur->flg_export = 0;
2131 /* unsetenv was already done */
2134 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2135 i = putenv(cur->varstr);
2136 /* only now we can free old exported malloced string */
2145 /* Used at startup and after each cd */
2146 static void set_pwd_var(int exp)
2148 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2149 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2152 static int unset_local_var_len(const char *name, int name_len)
2154 struct variable *cur;
2155 struct variable **var_pp;
2158 return EXIT_SUCCESS;
2159 var_pp = &G.top_var;
2160 while ((cur = *var_pp) != NULL) {
2161 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2162 if (cur->flg_read_only) {
2163 bb_error_msg("%s: readonly variable", name);
2164 return EXIT_FAILURE;
2166 *var_pp = cur->next;
2167 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2168 bb_unsetenv(cur->varstr);
2169 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2170 cmdedit_update_prompt();
2174 return EXIT_SUCCESS;
2176 var_pp = &cur->next;
2178 return EXIT_SUCCESS;
2181 #if ENABLE_HUSH_UNSET
2182 static int unset_local_var(const char *name)
2184 return unset_local_var_len(name, strlen(name));
2188 static void unset_vars(char **strings)
2196 const char *eq = strchrnul(*v, '=');
2197 unset_local_var_len(*v, (int)(eq - *v));
2203 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ
2204 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2206 char *var = xasprintf("%s=%s", name, val);
2207 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2213 * Helpers for "var1=val1 var2=val2 cmd" feature
2215 static void add_vars(struct variable *var)
2217 struct variable *next;
2221 var->next = G.top_var;
2223 if (var->flg_export) {
2224 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2225 putenv(var->varstr);
2227 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2233 static struct variable *set_vars_and_save_old(char **strings)
2236 struct variable *old = NULL;
2242 struct variable *var_p;
2243 struct variable **var_pp;
2246 eq = strchr(*s, '=');
2248 var_pp = get_ptr_to_local_var(*s, eq - *s);
2250 /* Remove variable from global linked list */
2252 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2253 *var_pp = var_p->next;
2254 /* Add it to returned list */
2258 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2269 static void reinit_unicode_for_hush(void)
2271 /* Unicode support should be activated even if LANG is set
2272 * _during_ shell execution, not only if it was set when
2273 * shell was started. Therefore, re-check LANG every time:
2275 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2276 || ENABLE_UNICODE_USING_LOCALE
2278 const char *s = get_local_var_value("LC_ALL");
2279 if (!s) s = get_local_var_value("LC_CTYPE");
2280 if (!s) s = get_local_var_value("LANG");
2286 * in_str support (strings, and "strings" read from files).
2289 #if ENABLE_HUSH_INTERACTIVE
2290 /* To test correct lineedit/interactive behavior, type from command line:
2296 * It exercises a lot of corner cases.
2298 static void cmdedit_update_prompt(void)
2300 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2301 G.PS1 = get_local_var_value("PS1");
2304 G.PS2 = get_local_var_value("PS2");
2311 static const char *setup_prompt_string(int promptmode)
2313 const char *prompt_str;
2314 debug_printf("setup_prompt_string %d ", promptmode);
2315 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2316 /* Set up the prompt */
2317 if (promptmode == 0) { /* PS1 */
2319 /* bash uses $PWD value, even if it is set by user.
2320 * It uses current dir only if PWD is unset.
2321 * We always use current dir. */
2322 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2327 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2328 debug_printf("prompt_str '%s'\n", prompt_str);
2331 static int get_user_input(struct in_str *i)
2334 const char *prompt_str;
2336 prompt_str = setup_prompt_string(i->promptmode);
2337 # if ENABLE_FEATURE_EDITING
2339 reinit_unicode_for_hush();
2340 if (G.flag_SIGINT) {
2341 /* There was ^C'ed, make it look prettier: */
2345 /* buglet: SIGINT will not make new prompt to appear _at once_,
2346 * only after <Enter>. (^C works immediately) */
2347 r = read_line_input(G.line_input_state, prompt_str,
2348 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2351 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2353 write(STDOUT_FILENO, "^C", 2);
2356 check_and_run_traps();
2357 if (r != 0 && !G.flag_SIGINT)
2359 /* ^C or SIGINT: repeat */
2360 G.last_exitcode = 128 + SIGINT;
2363 /* EOF/error detected */
2365 i->peek_buf[0] = r = EOF;
2368 i->p = G.user_input_buf;
2369 return (unsigned char)*i->p++;
2373 if (i->last_char == '\0' || i->last_char == '\n') {
2374 /* Why check_and_run_traps here? Try this interactively:
2375 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2376 * $ <[enter], repeatedly...>
2377 * Without check_and_run_traps, handler never runs.
2379 check_and_run_traps();
2380 fputs(prompt_str, stdout);
2383 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2385 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2386 * no ^C masking happens during fgetc, no special code for ^C:
2387 * it generates SIGINT as usual.
2389 check_and_run_traps();
2391 G.last_exitcode = 128 + SIGINT;
2398 /* This is the magic location that prints prompts
2399 * and gets data back from the user */
2400 static int fgetc_interactive(struct in_str *i)
2403 /* If it's interactive stdin, get new line. */
2404 if (G_interactive_fd && i->file == stdin) {
2405 /* Returns first char (or EOF), the rest is in i->p[] */
2406 ch = get_user_input(i);
2407 i->promptmode = 1; /* PS2 */
2409 /* Not stdin: script file, sourced file, etc */
2410 do ch = fgetc(i->file); while (ch == '\0');
2415 static inline int fgetc_interactive(struct in_str *i)
2418 do ch = fgetc(i->file); while (ch == '\0');
2421 #endif /* INTERACTIVE */
2423 static int i_getch(struct in_str *i)
2428 /* string-based in_str */
2429 ch = (unsigned char)*i->p;
2438 /* FILE-based in_str */
2440 #if ENABLE_FEATURE_EDITING
2441 /* This can be stdin, check line editing char[] buffer */
2442 if (i->p && *i->p != '\0') {
2443 ch = (unsigned char)*i->p++;
2447 /* peek_buf[] is an int array, not char. Can contain EOF. */
2448 ch = i->peek_buf[0];
2450 int ch2 = i->peek_buf[1];
2451 i->peek_buf[0] = ch2;
2452 if (ch2 == 0) /* very likely, avoid redundant write */
2458 ch = fgetc_interactive(i);
2460 debug_printf("file_get: got '%c' %d\n", ch, ch);
2465 static int i_peek(struct in_str *i)
2470 /* string-based in_str */
2471 /* Doesn't report EOF on NUL. None of the callers care. */
2472 return (unsigned char)*i->p;
2475 /* FILE-based in_str */
2477 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2478 /* This can be stdin, check line editing char[] buffer */
2479 if (i->p && *i->p != '\0')
2480 return (unsigned char)*i->p;
2482 /* peek_buf[] is an int array, not char. Can contain EOF. */
2483 ch = i->peek_buf[0];
2487 /* Need to get a new char */
2488 ch = fgetc_interactive(i);
2489 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2491 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2492 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2498 i->peek_buf[0] = ch;
2499 /*i->peek_buf[1] = 0; - already is */
2503 /* Only ever called if i_peek() was called, and did not return EOF.
2504 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2505 * not end-of-line. Therefore we never need to read a new editing line here.
2507 static int i_peek2(struct in_str *i)
2511 /* There are two cases when i->p[] buffer exists.
2512 * (1) it's a string in_str.
2513 * (2) It's a file, and we have a saved line editing buffer.
2514 * In both cases, we know that i->p[0] exists and not NUL, and
2515 * the peek2 result is in i->p[1].
2518 return (unsigned char)i->p[1];
2520 /* Now we know it is a file-based in_str. */
2522 /* peek_buf[] is an int array, not char. Can contain EOF. */
2523 /* Is there 2nd char? */
2524 ch = i->peek_buf[1];
2526 /* We did not read it yet, get it now */
2527 do ch = fgetc(i->file); while (ch == '\0');
2528 i->peek_buf[1] = ch;
2531 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2535 static void setup_file_in_str(struct in_str *i, FILE *f)
2537 memset(i, 0, sizeof(*i));
2538 /* i->promptmode = 0; - PS1 (memset did it) */
2543 static void setup_string_in_str(struct in_str *i, const char *s)
2545 memset(i, 0, sizeof(*i));
2546 /* i->promptmode = 0; - PS1 (memset did it) */
2547 /*i->file = NULL */;
2555 #define B_CHUNK (32 * sizeof(char*))
2557 static void o_reset_to_empty_unquoted(o_string *o)
2560 o->has_quoted_part = 0;
2565 static void o_free(o_string *o)
2568 memset(o, 0, sizeof(*o));
2571 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2576 static void o_grow_by(o_string *o, int len)
2578 if (o->length + len > o->maxlen) {
2579 o->maxlen += (2 * len) | (B_CHUNK-1);
2580 o->data = xrealloc(o->data, 1 + o->maxlen);
2584 static void o_addchr(o_string *o, int ch)
2586 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2587 if (o->length < o->maxlen) {
2588 /* likely. avoid o_grow_by() call */
2590 o->data[o->length] = ch;
2592 o->data[o->length] = '\0';
2600 /* Valid only if we know o_string is not empty */
2601 static void o_delchr(o_string *o)
2604 o->data[o->length] = '\0';
2608 static void o_addblock(o_string *o, const char *str, int len)
2611 memcpy(&o->data[o->length], str, len);
2613 o->data[o->length] = '\0';
2616 static void o_addstr(o_string *o, const char *str)
2618 o_addblock(o, str, strlen(str));
2622 static void nommu_addchr(o_string *o, int ch)
2628 # define nommu_addchr(o, str) ((void)0)
2631 static void o_addstr_with_NUL(o_string *o, const char *str)
2633 o_addblock(o, str, strlen(str) + 1);
2637 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2638 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2639 * Apparently, on unquoted $v bash still does globbing
2640 * ("v='*.txt'; echo $v" prints all .txt files),
2641 * but NOT brace expansion! Thus, there should be TWO independent
2642 * quoting mechanisms on $v expansion side: one protects
2643 * $v from brace expansion, and other additionally protects "$v" against globbing.
2644 * We have only second one.
2647 #if ENABLE_HUSH_BRACE_EXPANSION
2648 # define MAYBE_BRACES "{}"
2650 # define MAYBE_BRACES ""
2653 /* My analysis of quoting semantics tells me that state information
2654 * is associated with a destination, not a source.
2656 static void o_addqchr(o_string *o, int ch)
2659 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2664 o->data[o->length] = '\\';
2667 o->data[o->length] = ch;
2669 o->data[o->length] = '\0';
2672 static void o_addQchr(o_string *o, int ch)
2675 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2676 && strchr("*?[\\" MAYBE_BRACES, ch)
2679 o->data[o->length] = '\\';
2683 o->data[o->length] = ch;
2685 o->data[o->length] = '\0';
2688 static void o_addqblock(o_string *o, const char *str, int len)
2693 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2694 if (ordinary_cnt > len) /* paranoia */
2696 o_addblock(o, str, ordinary_cnt);
2697 if (ordinary_cnt == len)
2698 return; /* NUL is already added by o_addblock */
2699 str += ordinary_cnt;
2700 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2704 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2706 o->data[o->length] = '\\';
2710 o->data[o->length] = ch;
2713 o->data[o->length] = '\0';
2716 static void o_addQblock(o_string *o, const char *str, int len)
2718 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2719 o_addblock(o, str, len);
2722 o_addqblock(o, str, len);
2725 static void o_addQstr(o_string *o, const char *str)
2727 o_addQblock(o, str, strlen(str));
2730 /* A special kind of o_string for $VAR and `cmd` expansion.
2731 * It contains char* list[] at the beginning, which is grown in 16 element
2732 * increments. Actual string data starts at the next multiple of 16 * (char*).
2733 * list[i] contains an INDEX (int!) into this string data.
2734 * It means that if list[] needs to grow, data needs to be moved higher up
2735 * but list[i]'s need not be modified.
2736 * NB: remembering how many list[i]'s you have there is crucial.
2737 * o_finalize_list() operation post-processes this structure - calculates
2738 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2740 #if DEBUG_EXPAND || DEBUG_GLOB
2741 static void debug_print_list(const char *prefix, o_string *o, int n)
2743 char **list = (char**)o->data;
2744 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2748 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2749 prefix, list, n, string_start, o->length, o->maxlen,
2750 !!(o->o_expflags & EXP_FLAG_GLOB),
2752 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2755 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2756 o->data + (int)(uintptr_t)list[i] + string_start,
2757 o->data + (int)(uintptr_t)list[i] + string_start);
2761 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2763 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2767 # define debug_print_list(prefix, o, n) ((void)0)
2770 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2771 * in list[n] so that it points past last stored byte so far.
2772 * It returns n+1. */
2773 static int o_save_ptr_helper(o_string *o, int n)
2775 char **list = (char**)o->data;
2779 if (!o->has_empty_slot) {
2780 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2781 string_len = o->length - string_start;
2782 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2783 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2784 /* list[n] points to string_start, make space for 16 more pointers */
2785 o->maxlen += 0x10 * sizeof(list[0]);
2786 o->data = xrealloc(o->data, o->maxlen + 1);
2787 list = (char**)o->data;
2788 memmove(list + n + 0x10, list + n, string_len);
2789 o->length += 0x10 * sizeof(list[0]);
2791 debug_printf_list("list[%d]=%d string_start=%d\n",
2792 n, string_len, string_start);
2795 /* We have empty slot at list[n], reuse without growth */
2796 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2797 string_len = o->length - string_start;
2798 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2799 n, string_len, string_start);
2800 o->has_empty_slot = 0;
2802 o->has_quoted_part = 0;
2803 list[n] = (char*)(uintptr_t)string_len;
2807 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2808 static int o_get_last_ptr(o_string *o, int n)
2810 char **list = (char**)o->data;
2811 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2813 return ((int)(uintptr_t)list[n-1]) + string_start;
2816 #if ENABLE_HUSH_BRACE_EXPANSION
2817 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2818 * first, it processes even {a} (no commas), second,
2819 * I didn't manage to make it return strings when they don't match
2820 * existing files. Need to re-implement it.
2824 static int glob_needed(const char *s)
2833 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2839 /* Return pointer to next closing brace or to comma */
2840 static const char *next_brace_sub(const char *cp)
2844 while (*cp != '\0') {
2851 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2857 return *cp != '\0' ? cp : NULL;
2859 /* Recursive brace globber. Note: may garble pattern[]. */
2860 static int glob_brace(char *pattern, o_string *o, int n)
2862 char *new_pattern_buf;
2869 debug_printf_glob("glob_brace('%s')\n", pattern);
2875 if (*begin == '{') {
2876 /* Find the first sub-pattern and at the same time
2877 * find the rest after the closing brace */
2878 next = next_brace_sub(begin);
2880 /* An illegal expression */
2884 /* "{abc}" with no commas - illegal
2885 * brace expr, disregard and skip it */
2891 if (*begin == '\\' && begin[1] != '\0')
2895 debug_printf_glob("begin:%s\n", begin);
2896 debug_printf_glob("next:%s\n", next);
2898 /* Now find the end of the whole brace expression */
2900 while (*rest != '}') {
2901 rest = next_brace_sub(rest);
2903 /* An illegal expression */
2906 debug_printf_glob("rest:%s\n", rest);
2908 rest_len = strlen(++rest) + 1;
2910 /* We are sure the brace expression is well-formed */
2912 /* Allocate working buffer large enough for our work */
2913 new_pattern_buf = xmalloc(strlen(pattern));
2915 /* We have a brace expression. BEGIN points to the opening {,
2916 * NEXT points past the terminator of the first element, and REST
2917 * points past the final }. We will accumulate result names from
2918 * recursive runs for each brace alternative in the buffer using
2923 /* Construct the new glob expression */
2926 mempcpy(new_pattern_buf,
2927 /* We know the prefix for all sub-patterns */
2928 pattern, begin - pattern),
2932 /* Note: glob_brace() may garble new_pattern_buf[].
2933 * That's why we re-copy prefix every time (1st memcpy above).
2935 n = glob_brace(new_pattern_buf, o, n);
2937 /* We saw the last entry */
2941 next = next_brace_sub(next);
2943 free(new_pattern_buf);
2951 memset(&globdata, 0, sizeof(globdata));
2952 gr = glob(pattern, 0, NULL, &globdata);
2953 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2955 if (gr == GLOB_NOMATCH) {
2956 globfree(&globdata);
2957 /* NB: garbles parameter */
2958 unbackslash(pattern);
2959 o_addstr_with_NUL(o, pattern);
2960 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2961 return o_save_ptr_helper(o, n);
2963 if (gr == GLOB_NOSPACE)
2964 bb_error_msg_and_die(bb_msg_memory_exhausted);
2965 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2966 * but we didn't specify it. Paranoia again. */
2967 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2969 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2970 char **argv = globdata.gl_pathv;
2972 o_addstr_with_NUL(o, *argv);
2973 n = o_save_ptr_helper(o, n);
2979 globfree(&globdata);
2983 /* Performs globbing on last list[],
2984 * saving each result as a new list[].
2986 static int perform_glob(o_string *o, int n)
2988 char *pattern, *copy;
2990 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2992 return o_save_ptr_helper(o, n);
2993 pattern = o->data + o_get_last_ptr(o, n);
2994 debug_printf_glob("glob pattern '%s'\n", pattern);
2995 if (!glob_needed(pattern)) {
2996 /* unbackslash last string in o in place, fix length */
2997 o->length = unbackslash(pattern) - o->data;
2998 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2999 return o_save_ptr_helper(o, n);
3002 copy = xstrdup(pattern);
3003 /* "forget" pattern in o */
3004 o->length = pattern - o->data;
3005 n = glob_brace(copy, o, n);
3008 debug_print_list("perform_glob returning", o, n);
3012 #else /* !HUSH_BRACE_EXPANSION */
3015 static int glob_needed(const char *s)
3024 if (*s == '*' || *s == '[' || *s == '?')
3030 /* Performs globbing on last list[],
3031 * saving each result as a new list[].
3033 static int perform_glob(o_string *o, int n)
3039 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3041 return o_save_ptr_helper(o, n);
3042 pattern = o->data + o_get_last_ptr(o, n);
3043 debug_printf_glob("glob pattern '%s'\n", pattern);
3044 if (!glob_needed(pattern)) {
3046 /* unbackslash last string in o in place, fix length */
3047 o->length = unbackslash(pattern) - o->data;
3048 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3049 return o_save_ptr_helper(o, n);
3052 memset(&globdata, 0, sizeof(globdata));
3053 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3054 * If we glob "*.\*" and don't find anything, we need
3055 * to fall back to using literal "*.*", but GLOB_NOCHECK
3056 * will return "*.\*"!
3058 gr = glob(pattern, 0, NULL, &globdata);
3059 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3061 if (gr == GLOB_NOMATCH) {
3062 globfree(&globdata);
3065 if (gr == GLOB_NOSPACE)
3066 bb_error_msg_and_die(bb_msg_memory_exhausted);
3067 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3068 * but we didn't specify it. Paranoia again. */
3069 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3071 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3072 char **argv = globdata.gl_pathv;
3073 /* "forget" pattern in o */
3074 o->length = pattern - o->data;
3076 o_addstr_with_NUL(o, *argv);
3077 n = o_save_ptr_helper(o, n);
3083 globfree(&globdata);
3085 debug_print_list("perform_glob returning", o, n);
3089 #endif /* !HUSH_BRACE_EXPANSION */
3091 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3092 * Otherwise, just finish current list[] and start new */
3093 static int o_save_ptr(o_string *o, int n)
3095 if (o->o_expflags & EXP_FLAG_GLOB) {
3096 /* If o->has_empty_slot, list[n] was already globbed
3097 * (if it was requested back then when it was filled)
3098 * so don't do that again! */
3099 if (!o->has_empty_slot)
3100 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3102 return o_save_ptr_helper(o, n);
3105 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3106 static char **o_finalize_list(o_string *o, int n)
3111 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3113 debug_print_list("finalized", o, n);
3114 debug_printf_expand("finalized n:%d\n", n);
3115 list = (char**)o->data;
3116 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3120 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3125 static void free_pipe_list(struct pipe *pi);
3127 /* Returns pi->next - next pipe in the list */
3128 static struct pipe *free_pipe(struct pipe *pi)
3133 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3134 for (i = 0; i < pi->num_cmds; i++) {
3135 struct command *command;
3136 struct redir_struct *r, *rnext;
3138 command = &pi->cmds[i];
3139 debug_printf_clean(" command %d:\n", i);
3140 if (command->argv) {
3144 for (a = 0, p = command->argv; *p; a++, p++) {
3145 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3148 free_strings(command->argv);
3149 //command->argv = NULL;
3151 /* not "else if": on syntax error, we may have both! */
3152 if (command->group) {
3153 debug_printf_clean(" begin group (cmd_type:%d)\n",
3155 free_pipe_list(command->group);
3156 debug_printf_clean(" end group\n");
3157 //command->group = NULL;
3159 /* else is crucial here.
3160 * If group != NULL, child_func is meaningless */
3161 #if ENABLE_HUSH_FUNCTIONS
3162 else if (command->child_func) {
3163 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3164 command->child_func->parent_cmd = NULL;
3168 free(command->group_as_string);
3169 //command->group_as_string = NULL;
3171 for (r = command->redirects; r; r = rnext) {
3172 debug_printf_clean(" redirect %d%s",
3173 r->rd_fd, redir_table[r->rd_type].descrip);
3174 /* guard against the case >$FOO, where foo is unset or blank */
3175 if (r->rd_filename) {
3176 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3177 free(r->rd_filename);
3178 //r->rd_filename = NULL;
3180 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3184 //command->redirects = NULL;
3186 free(pi->cmds); /* children are an array, they get freed all at once */
3190 //pi->cmdtext = NULL;
3198 static void free_pipe_list(struct pipe *pi)
3202 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3204 debug_printf_clean("pipe followup code %d\n", pi->followup);
3210 /*** Parsing routines ***/
3212 #ifndef debug_print_tree
3213 static void debug_print_tree(struct pipe *pi, int lvl)
3215 static const char *const PIPE[] = {
3221 static const char *RES[] = {
3222 [RES_NONE ] = "NONE" ,
3225 [RES_THEN ] = "THEN" ,
3226 [RES_ELIF ] = "ELIF" ,
3227 [RES_ELSE ] = "ELSE" ,
3230 # if ENABLE_HUSH_LOOPS
3231 [RES_FOR ] = "FOR" ,
3232 [RES_WHILE] = "WHILE",
3233 [RES_UNTIL] = "UNTIL",
3235 [RES_DONE ] = "DONE" ,
3237 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3240 # if ENABLE_HUSH_CASE
3241 [RES_CASE ] = "CASE" ,
3242 [RES_CASE_IN ] = "CASE_IN" ,
3243 [RES_MATCH] = "MATCH",
3244 [RES_CASE_BODY] = "CASE_BODY",
3245 [RES_ESAC ] = "ESAC" ,
3247 [RES_XXXX ] = "XXXX" ,
3248 [RES_SNTX ] = "SNTX" ,
3250 static const char *const CMDTYPE[] = {
3254 # if ENABLE_HUSH_FUNCTIONS
3263 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3264 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3266 while (prn < pi->num_cmds) {
3267 struct command *command = &pi->cmds[prn];
3268 char **argv = command->argv;
3270 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3272 command->assignment_cnt);
3273 if (command->group) {
3274 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3275 CMDTYPE[command->cmd_type],
3278 , " group_as_string:", command->group_as_string
3283 debug_print_tree(command->group, lvl+1);
3287 if (argv) while (*argv) {
3288 fdprintf(2, " '%s'", *argv);
3298 #endif /* debug_print_tree */
3300 static struct pipe *new_pipe(void)
3303 pi = xzalloc(sizeof(struct pipe));
3304 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3308 /* Command (member of a pipe) is complete, or we start a new pipe
3309 * if ctx->command is NULL.
3310 * No errors possible here.
3312 static int done_command(struct parse_context *ctx)
3314 /* The command is really already in the pipe structure, so
3315 * advance the pipe counter and make a new, null command. */
3316 struct pipe *pi = ctx->pipe;
3317 struct command *command = ctx->command;
3319 #if 0 /* Instead we emit error message at run time */
3320 if (ctx->pending_redirect) {
3321 /* For example, "cmd >" (no filename to redirect to) */
3322 die_if_script("syntax error: %s", "invalid redirect");
3323 ctx->pending_redirect = NULL;
3328 if (IS_NULL_CMD(command)) {
3329 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3333 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3334 //debug_print_tree(ctx->list_head, 20);
3336 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3339 /* Only real trickiness here is that the uncommitted
3340 * command structure is not counted in pi->num_cmds. */
3341 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3342 ctx->command = command = &pi->cmds[pi->num_cmds];
3344 memset(command, 0, sizeof(*command));
3345 return pi->num_cmds; /* used only for 0/nonzero check */
3348 static void done_pipe(struct parse_context *ctx, pipe_style type)
3352 debug_printf_parse("done_pipe entered, followup %d\n", type);
3353 /* Close previous command */
3354 not_null = done_command(ctx);
3355 ctx->pipe->followup = type;
3357 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3358 ctx->ctx_inverted = 0;
3359 ctx->pipe->res_word = ctx->ctx_res_w;
3362 /* Without this check, even just <enter> on command line generates
3363 * tree of three NOPs (!). Which is harmless but annoying.
3364 * IOW: it is safe to do it unconditionally. */
3367 || ctx->ctx_res_w == RES_FI
3369 #if ENABLE_HUSH_LOOPS
3370 || ctx->ctx_res_w == RES_DONE
3371 || ctx->ctx_res_w == RES_FOR
3372 || ctx->ctx_res_w == RES_IN
3374 #if ENABLE_HUSH_CASE
3375 || ctx->ctx_res_w == RES_ESAC
3379 debug_printf_parse("done_pipe: adding new pipe: "
3380 "not_null:%d ctx->ctx_res_w:%d\n",
3381 not_null, ctx->ctx_res_w);
3383 ctx->pipe->next = new_p;
3385 /* RES_THEN, RES_DO etc are "sticky" -
3386 * they remain set for pipes inside if/while.
3387 * This is used to control execution.
3388 * RES_FOR and RES_IN are NOT sticky (needed to support
3389 * cases where variable or value happens to match a keyword):
3391 #if ENABLE_HUSH_LOOPS
3392 if (ctx->ctx_res_w == RES_FOR
3393 || ctx->ctx_res_w == RES_IN)
3394 ctx->ctx_res_w = RES_NONE;
3396 #if ENABLE_HUSH_CASE
3397 if (ctx->ctx_res_w == RES_MATCH)
3398 ctx->ctx_res_w = RES_CASE_BODY;
3399 if (ctx->ctx_res_w == RES_CASE)
3400 ctx->ctx_res_w = RES_CASE_IN;
3402 ctx->command = NULL; /* trick done_command below */
3403 /* Create the memory for command, roughly:
3404 * ctx->pipe->cmds = new struct command;
3405 * ctx->command = &ctx->pipe->cmds[0];
3408 //debug_print_tree(ctx->list_head, 10);
3410 debug_printf_parse("done_pipe return\n");
3413 static void initialize_context(struct parse_context *ctx)
3415 memset(ctx, 0, sizeof(*ctx));
3416 ctx->pipe = ctx->list_head = new_pipe();
3417 /* Create the memory for command, roughly:
3418 * ctx->pipe->cmds = new struct command;
3419 * ctx->command = &ctx->pipe->cmds[0];
3424 /* If a reserved word is found and processed, parse context is modified
3425 * and 1 is returned.
3428 struct reserved_combo {
3431 unsigned char assignment_flag;
3435 FLAG_END = (1 << RES_NONE ),
3437 FLAG_IF = (1 << RES_IF ),
3438 FLAG_THEN = (1 << RES_THEN ),
3439 FLAG_ELIF = (1 << RES_ELIF ),
3440 FLAG_ELSE = (1 << RES_ELSE ),
3441 FLAG_FI = (1 << RES_FI ),
3443 # if ENABLE_HUSH_LOOPS
3444 FLAG_FOR = (1 << RES_FOR ),
3445 FLAG_WHILE = (1 << RES_WHILE),
3446 FLAG_UNTIL = (1 << RES_UNTIL),
3447 FLAG_DO = (1 << RES_DO ),
3448 FLAG_DONE = (1 << RES_DONE ),
3449 FLAG_IN = (1 << RES_IN ),
3451 # if ENABLE_HUSH_CASE
3452 FLAG_MATCH = (1 << RES_MATCH),
3453 FLAG_ESAC = (1 << RES_ESAC ),
3455 FLAG_START = (1 << RES_XXXX ),
3458 static const struct reserved_combo* match_reserved_word(o_string *word)
3460 /* Mostly a list of accepted follow-up reserved words.
3461 * FLAG_END means we are done with the sequence, and are ready
3462 * to turn the compound list into a command.
3463 * FLAG_START means the word must start a new compound list.
3465 static const struct reserved_combo reserved_list[] = {
3467 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3468 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3469 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3470 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3471 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3472 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3474 # if ENABLE_HUSH_LOOPS
3475 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3476 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3477 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3478 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3479 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3480 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3482 # if ENABLE_HUSH_CASE
3483 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3484 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3487 const struct reserved_combo *r;
3489 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3490 if (strcmp(word->data, r->literal) == 0)
3495 /* Return 0: not a keyword, 1: keyword
3497 static int reserved_word(o_string *word, struct parse_context *ctx)
3499 # if ENABLE_HUSH_CASE
3500 static const struct reserved_combo reserved_match = {
3501 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3504 const struct reserved_combo *r;
3506 if (word->has_quoted_part)
3508 r = match_reserved_word(word);
3512 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3513 # if ENABLE_HUSH_CASE
3514 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3515 /* "case word IN ..." - IN part starts first MATCH part */
3516 r = &reserved_match;
3519 if (r->flag == 0) { /* '!' */
3520 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3521 syntax_error("! ! command");
3522 ctx->ctx_res_w = RES_SNTX;
3524 ctx->ctx_inverted = 1;
3527 if (r->flag & FLAG_START) {
3528 struct parse_context *old;
3530 old = xmalloc(sizeof(*old));
3531 debug_printf_parse("push stack %p\n", old);
3532 *old = *ctx; /* physical copy */
3533 initialize_context(ctx);
3535 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3536 syntax_error_at(word->data);
3537 ctx->ctx_res_w = RES_SNTX;
3540 /* "{...} fi" is ok. "{...} if" is not
3542 * if { echo foo; } then { echo bar; } fi */
3543 if (ctx->command->group)
3544 done_pipe(ctx, PIPE_SEQ);
3547 ctx->ctx_res_w = r->res;
3548 ctx->old_flag = r->flag;
3549 word->o_assignment = r->assignment_flag;
3550 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3552 if (ctx->old_flag & FLAG_END) {
3553 struct parse_context *old;
3555 done_pipe(ctx, PIPE_SEQ);
3556 debug_printf_parse("pop stack %p\n", ctx->stack);
3558 old->command->group = ctx->list_head;
3559 old->command->cmd_type = CMD_NORMAL;
3561 /* At this point, the compound command's string is in
3562 * ctx->as_string... except for the leading keyword!
3563 * Consider this example: "echo a | if true; then echo a; fi"
3564 * ctx->as_string will contain "true; then echo a; fi",
3565 * with "if " remaining in old->as_string!
3569 int len = old->as_string.length;
3570 /* Concatenate halves */
3571 o_addstr(&old->as_string, ctx->as_string.data);
3572 o_free_unsafe(&ctx->as_string);
3573 /* Find where leading keyword starts in first half */
3574 str = old->as_string.data + len;
3575 if (str > old->as_string.data)
3576 str--; /* skip whitespace after keyword */
3577 while (str > old->as_string.data && isalpha(str[-1]))
3579 /* Ugh, we're done with this horrid hack */
3580 old->command->group_as_string = xstrdup(str);
3581 debug_printf_parse("pop, remembering as:'%s'\n",
3582 old->command->group_as_string);
3585 *ctx = *old; /* physical copy */
3590 #endif /* HAS_KEYWORDS */
3592 /* Word is complete, look at it and update parsing context.
3593 * Normal return is 0. Syntax errors return 1.
3594 * Note: on return, word is reset, but not o_free'd!
3596 static int done_word(o_string *word, struct parse_context *ctx)
3598 struct command *command = ctx->command;
3600 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3601 if (word->length == 0 && !word->has_quoted_part) {
3602 debug_printf_parse("done_word return 0: true null, ignored\n");
3606 if (ctx->pending_redirect) {
3607 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3608 * only if run as "bash", not "sh" */
3609 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3611 * ...the word that follows the redirection operator
3612 * shall be subjected to tilde expansion, parameter expansion,
3613 * command substitution, arithmetic expansion, and quote
3614 * removal. Pathname expansion shall not be performed
3615 * on the word by a non-interactive shell; an interactive
3616 * shell may perform it, but shall do so only when
3617 * the expansion would result in one word."
3619 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3620 /* Cater for >\file case:
3621 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3622 * Same with heredocs:
3623 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3625 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3626 unbackslash(ctx->pending_redirect->rd_filename);
3627 /* Is it <<"HEREDOC"? */
3628 if (word->has_quoted_part) {
3629 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3632 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3633 ctx->pending_redirect = NULL;
3636 # if ENABLE_HUSH_CASE
3637 if (ctx->ctx_dsemicolon
3638 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3640 /* already done when ctx_dsemicolon was set to 1: */
3641 /* ctx->ctx_res_w = RES_MATCH; */
3642 ctx->ctx_dsemicolon = 0;
3645 if (!command->argv /* if it's the first word... */
3646 # if ENABLE_HUSH_LOOPS
3647 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3648 && ctx->ctx_res_w != RES_IN
3650 # if ENABLE_HUSH_CASE
3651 && ctx->ctx_res_w != RES_CASE
3654 int reserved = reserved_word(word, ctx);
3655 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3657 o_reset_to_empty_unquoted(word);
3658 debug_printf_parse("done_word return %d\n",
3659 (ctx->ctx_res_w == RES_SNTX));
3660 return (ctx->ctx_res_w == RES_SNTX);
3663 if (strcmp(word->data, "[[") == 0) {
3664 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3670 if (command->group) {
3671 /* "{ echo foo; } echo bar" - bad */
3672 syntax_error_at(word->data);
3673 debug_printf_parse("done_word return 1: syntax error, "
3674 "groups and arglists don't mix\n");
3678 /* If this word wasn't an assignment, next ones definitely
3679 * can't be assignments. Even if they look like ones. */
3680 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3681 && word->o_assignment != WORD_IS_KEYWORD
3683 word->o_assignment = NOT_ASSIGNMENT;
3685 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3686 command->assignment_cnt++;
3687 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3689 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3690 word->o_assignment = MAYBE_ASSIGNMENT;
3692 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3694 if (word->has_quoted_part
3695 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3696 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3697 /* (otherwise it's known to be not empty and is already safe) */
3699 /* exclude "$@" - it can expand to no word despite "" */
3700 char *p = word->data;
3701 while (p[0] == SPECIAL_VAR_SYMBOL
3702 && (p[1] & 0x7f) == '@'
3703 && p[2] == SPECIAL_VAR_SYMBOL
3708 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3709 debug_print_strings("word appended to argv", command->argv);
3712 #if ENABLE_HUSH_LOOPS
3713 if (ctx->ctx_res_w == RES_FOR) {
3714 if (word->has_quoted_part
3715 || !is_well_formed_var_name(command->argv[0], '\0')
3717 /* bash says just "not a valid identifier" */
3718 syntax_error("not a valid identifier in for");
3721 /* Force FOR to have just one word (variable name) */
3722 /* NB: basically, this makes hush see "for v in ..."
3723 * syntax as if it is "for v; in ...". FOR and IN become
3724 * two pipe structs in parse tree. */
3725 done_pipe(ctx, PIPE_SEQ);
3728 #if ENABLE_HUSH_CASE
3729 /* Force CASE to have just one word */
3730 if (ctx->ctx_res_w == RES_CASE) {
3731 done_pipe(ctx, PIPE_SEQ);
3735 o_reset_to_empty_unquoted(word);
3737 debug_printf_parse("done_word return 0\n");
3742 /* Peek ahead in the input to find out if we have a "&n" construct,
3743 * as in "2>&1", that represents duplicating a file descriptor.
3745 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3746 * REDIRFD_SYNTAX_ERR if syntax error,
3747 * REDIRFD_TO_FILE if no & was seen,
3748 * or the number found.
3751 #define parse_redir_right_fd(as_string, input) \
3752 parse_redir_right_fd(input)
3754 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3760 return REDIRFD_TO_FILE;
3762 ch = i_getch(input); /* get the & */
3763 nommu_addchr(as_string, ch);
3766 ch = i_getch(input);
3767 nommu_addchr(as_string, ch);
3768 return REDIRFD_CLOSE;
3772 while (ch != EOF && isdigit(ch)) {
3773 d = d*10 + (ch-'0');
3775 ch = i_getch(input);
3776 nommu_addchr(as_string, ch);
3781 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3783 bb_error_msg("ambiguous redirect");
3784 return REDIRFD_SYNTAX_ERR;
3787 /* Return code is 0 normal, 1 if a syntax error is detected
3789 static int parse_redirect(struct parse_context *ctx,
3792 struct in_str *input)
3794 struct command *command = ctx->command;
3795 struct redir_struct *redir;
3796 struct redir_struct **redirp;
3799 dup_num = REDIRFD_TO_FILE;
3800 if (style != REDIRECT_HEREDOC) {
3801 /* Check for a '>&1' type redirect */
3802 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3803 if (dup_num == REDIRFD_SYNTAX_ERR)
3806 int ch = i_peek(input);
3807 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3808 if (dup_num) { /* <<-... */
3809 ch = i_getch(input);
3810 nommu_addchr(&ctx->as_string, ch);
3815 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3816 int ch = i_peek(input);
3818 /* >|FILE redirect ("clobbering" >).
3819 * Since we do not support "set -o noclobber" yet,
3820 * >| and > are the same for now. Just eat |.
3822 ch = i_getch(input);
3823 nommu_addchr(&ctx->as_string, ch);
3827 /* Create a new redir_struct and append it to the linked list */
3828 redirp = &command->redirects;
3829 while ((redir = *redirp) != NULL) {
3830 redirp = &(redir->next);
3832 *redirp = redir = xzalloc(sizeof(*redir));
3833 /* redir->next = NULL; */
3834 /* redir->rd_filename = NULL; */
3835 redir->rd_type = style;
3836 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3838 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3839 redir_table[style].descrip);
3841 redir->rd_dup = dup_num;
3842 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3843 /* Erik had a check here that the file descriptor in question
3844 * is legit; I postpone that to "run time"
3845 * A "-" representation of "close me" shows up as a -3 here */
3846 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3847 redir->rd_fd, redir->rd_dup);
3849 #if 0 /* Instead we emit error message at run time */
3850 if (ctx->pending_redirect) {
3851 /* For example, "cmd > <file" */
3852 die_if_script("syntax error: %s", "invalid redirect");
3855 /* Set ctx->pending_redirect, so we know what to do at the
3856 * end of the next parsed word. */
3857 ctx->pending_redirect = redir;
3862 /* If a redirect is immediately preceded by a number, that number is
3863 * supposed to tell which file descriptor to redirect. This routine
3864 * looks for such preceding numbers. In an ideal world this routine
3865 * needs to handle all the following classes of redirects...
3866 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3867 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3868 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3869 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3871 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3873 * ... If n is quoted, the number shall not be recognized as part of
3874 * the redirection expression. For example:
3876 * writes the character 2 into file a"
3877 * We are getting it right by setting ->has_quoted_part on any \<char>
3879 * A -1 return means no valid number was found,
3880 * the caller should use the appropriate default for this redirection.
3882 static int redirect_opt_num(o_string *o)
3886 if (o->data == NULL)
3888 num = bb_strtou(o->data, NULL, 10);
3889 if (errno || num < 0)
3891 o_reset_to_empty_unquoted(o);
3896 #define fetch_till_str(as_string, input, word, skip_tabs) \
3897 fetch_till_str(input, word, skip_tabs)
3899 static char *fetch_till_str(o_string *as_string,
3900 struct in_str *input,
3904 o_string heredoc = NULL_O_STRING;
3906 int prev = 0; /* not \ */
3912 ch = i_getch(input);
3914 nommu_addchr(as_string, ch);
3915 if ((ch == '\n' || ch == EOF)
3916 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3918 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3919 heredoc.data[past_EOL] = '\0';
3920 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3921 return heredoc.data;
3923 while (ch == '\n') {
3924 o_addchr(&heredoc, ch);
3927 past_EOL = heredoc.length;
3929 ch = i_getch(input);
3931 nommu_addchr(as_string, ch);
3932 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3936 o_free_unsafe(&heredoc);
3939 o_addchr(&heredoc, ch);
3940 nommu_addchr(as_string, ch);
3941 if (prev == '\\' && ch == '\\')
3942 /* Correctly handle foo\\<eol> (not a line cont.) */
3943 prev = 0; /* not \ */
3949 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3950 * and load them all. There should be exactly heredoc_cnt of them.
3952 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3954 struct pipe *pi = ctx->list_head;
3956 while (pi && heredoc_cnt) {
3958 struct command *cmd = pi->cmds;
3960 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3962 cmd->argv ? cmd->argv[0] : "NONE");
3963 for (i = 0; i < pi->num_cmds; i++) {
3964 struct redir_struct *redir = cmd->redirects;
3966 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3967 i, cmd->argv ? cmd->argv[0] : "NONE");
3969 if (redir->rd_type == REDIRECT_HEREDOC) {
3972 redir->rd_type = REDIRECT_HEREDOC2;
3973 /* redir->rd_dup is (ab)used to indicate <<- */
3974 p = fetch_till_str(&ctx->as_string, input,
3975 redir->rd_filename, redir->rd_dup);
3977 syntax_error("unexpected EOF in here document");
3980 free(redir->rd_filename);
3981 redir->rd_filename = p;
3984 redir = redir->next;
3991 /* Should be 0. If it isn't, it's a parse error */
3993 bb_error_msg_and_die("heredoc BUG 2");
3999 static int run_list(struct pipe *pi);
4001 #define parse_stream(pstring, input, end_trigger) \
4002 parse_stream(input, end_trigger)
4004 static struct pipe *parse_stream(char **pstring,
4005 struct in_str *input,
4009 #if !ENABLE_HUSH_FUNCTIONS
4010 #define parse_group(dest, ctx, input, ch) \
4011 parse_group(ctx, input, ch)
4013 static int parse_group(o_string *dest, struct parse_context *ctx,
4014 struct in_str *input, int ch)
4016 /* dest contains characters seen prior to ( or {.
4017 * Typically it's empty, but for function defs,
4018 * it contains function name (without '()'). */
4019 struct pipe *pipe_list;
4021 struct command *command = ctx->command;
4023 debug_printf_parse("parse_group entered\n");
4024 #if ENABLE_HUSH_FUNCTIONS
4025 if (ch == '(' && !dest->has_quoted_part) {
4027 if (done_word(dest, ctx))
4030 goto skip; /* (... */
4031 if (command->argv[1]) { /* word word ... (... */
4032 syntax_error_unexpected_ch('(');
4035 /* it is "word(..." or "word (..." */
4037 ch = i_getch(input);
4038 while (ch == ' ' || ch == '\t');
4040 syntax_error_unexpected_ch(ch);
4043 nommu_addchr(&ctx->as_string, ch);
4045 ch = i_getch(input);
4046 while (ch == ' ' || ch == '\t' || ch == '\n');
4048 syntax_error_unexpected_ch(ch);
4051 nommu_addchr(&ctx->as_string, ch);
4052 command->cmd_type = CMD_FUNCDEF;
4057 #if 0 /* Prevented by caller */
4058 if (command->argv /* word [word]{... */
4059 || dest->length /* word{... */
4060 || dest->has_quoted_part /* ""{... */
4063 debug_printf_parse("parse_group return 1: "
4064 "syntax error, groups and arglists don't mix\n");
4069 #if ENABLE_HUSH_FUNCTIONS
4075 command->cmd_type = CMD_SUBSHELL;
4077 /* bash does not allow "{echo...", requires whitespace */
4079 if (ch != ' ' && ch != '\t' && ch != '\n'
4080 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4082 syntax_error_unexpected_ch(ch);
4086 ch = i_getch(input);
4087 nommu_addchr(&ctx->as_string, ch);
4093 # define as_string NULL
4095 char *as_string = NULL;
4097 pipe_list = parse_stream(&as_string, input, endch);
4100 o_addstr(&ctx->as_string, as_string);
4102 /* empty ()/{} or parse error? */
4103 if (!pipe_list || pipe_list == ERR_PTR) {
4104 /* parse_stream already emitted error msg */
4107 debug_printf_parse("parse_group return 1: "
4108 "parse_stream returned %p\n", pipe_list);
4111 command->group = pipe_list;
4113 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4114 command->group_as_string = as_string;
4115 debug_printf_parse("end of group, remembering as:'%s'\n",
4116 command->group_as_string);
4120 debug_printf_parse("parse_group return 0\n");
4122 /* command remains "open", available for possible redirects */
4125 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4130 ch = i_getch(input);
4133 ch2 = i_peek(input);
4136 /* backslash+newline, skip it */
4141 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4149 ch2 = i_peek2(input);
4152 /* backslash+newline, skip it */
4158 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4159 /* Subroutines for copying $(...) and `...` things */
4160 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4162 static int add_till_single_quote(o_string *dest, struct in_str *input)
4165 int ch = i_getch(input);
4167 syntax_error_unterm_ch('\'');
4175 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4176 static int add_till_double_quote(o_string *dest, struct in_str *input)
4179 int ch = i_getch(input);
4181 syntax_error_unterm_ch('"');
4186 if (ch == '\\') { /* \x. Copy both chars. */
4188 ch = i_getch(input);
4192 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4197 //if (ch == '$') ...
4200 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4202 * "Within the backquoted style of command substitution, backslash
4203 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4204 * The search for the matching backquote shall be satisfied by the first
4205 * backquote found without a preceding backslash; during this search,
4206 * if a non-escaped backquote is encountered within a shell comment,
4207 * a here-document, an embedded command substitution of the $(command)
4208 * form, or a quoted string, undefined results occur. A single-quoted
4209 * or double-quoted string that begins, but does not end, within the
4210 * "`...`" sequence produces undefined results."
4212 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4214 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4217 int ch = i_getch(input);
4221 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4222 ch = i_getch(input);
4226 && (!in_dquote || ch != '"')
4228 o_addchr(dest, '\\');
4232 syntax_error_unterm_ch('`');
4238 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4239 * quoting and nested ()s.
4240 * "With the $(command) style of command substitution, all characters
4241 * following the open parenthesis to the matching closing parenthesis
4242 * constitute the command. Any valid shell script can be used for command,
4243 * except a script consisting solely of redirections which produces
4244 * unspecified results."
4246 * echo $(echo '(TEST)' BEST) (TEST) BEST
4247 * echo $(echo 'TEST)' BEST) TEST) BEST
4248 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4250 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4251 * can contain arbitrary constructs, just like $(cmd).
4252 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4253 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4255 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4256 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4259 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4260 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4261 char end_char2 = end_ch >> 8;
4263 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4266 ch = i_getch(input);
4268 syntax_error_unterm_ch(end_ch);
4272 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4278 /* we look for closing )) of $((EXPR)) */
4279 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4280 i_getch(input); /* eat second ')' */
4285 if (ch == '(' || ch == '{') {
4286 ch = (ch == '(' ? ')' : '}');
4287 if (!add_till_closing_bracket(dest, input, ch))
4293 if (!add_till_single_quote(dest, input))
4299 if (!add_till_double_quote(dest, input))
4305 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4311 /* \x. Copy verbatim. Important for \(, \) */
4312 ch = i_getch(input);
4314 syntax_error_unterm_ch(')');
4319 /* "backslash+newline", ignore both */
4320 o_delchr(dest); /* undo insertion of '\' */
4330 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4332 /* Return code: 0 for OK, 1 for syntax error */
4334 #define parse_dollar(as_string, dest, input, quote_mask) \
4335 parse_dollar(dest, input, quote_mask)
4336 #define as_string NULL
4338 static int parse_dollar(o_string *as_string,
4340 struct in_str *input, unsigned char quote_mask)
4342 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4344 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4346 ch = i_getch(input);
4347 nommu_addchr(as_string, ch);
4349 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4351 debug_printf_parse(": '%c'\n", ch);
4352 o_addchr(dest, ch | quote_mask);
4354 ch = i_peek_and_eat_bkslash_nl(input);
4355 if (!isalnum(ch) && ch != '_') {
4356 /* End of variable name reached */
4359 ch = i_getch(input);
4360 nommu_addchr(as_string, ch);
4362 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4363 } else if (isdigit(ch)) {
4365 ch = i_getch(input);
4366 nommu_addchr(as_string, ch);
4367 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4368 debug_printf_parse(": '%c'\n", ch);
4369 o_addchr(dest, ch | quote_mask);
4370 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4371 } else switch (ch) {
4373 case '!': /* last bg pid */
4374 case '?': /* last exit code */
4375 case '#': /* number of args */
4376 case '*': /* args */
4377 case '@': /* args */
4378 goto make_one_char_var;
4380 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4382 ch = i_getch(input); /* eat '{' */
4383 nommu_addchr(as_string, ch);
4385 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4386 /* It should be ${?}, or ${#var},
4387 * or even ${?+subst} - operator acting on a special variable,
4388 * or the beginning of variable name.
4391 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4394 syntax_error_unterm_str("${name}");
4395 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4398 nommu_addchr(as_string, ch);
4401 /* It's possible to just call add_till_closing_bracket() at this point.
4402 * However, this regresses some of our testsuite cases
4403 * which check invalid constructs like ${%}.
4404 * Oh well... let's check that the var name part is fine... */
4410 debug_printf_parse(": '%c'\n", ch);
4412 ch = i_getch(input);
4413 nommu_addchr(as_string, ch);
4417 if (!isalnum(ch) && ch != '_') {
4419 unsigned char last_ch;
4420 /* handle parameter expansions
4421 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4423 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4424 goto bad_dollar_syntax;
4426 /* Eat everything until closing '}' (or ':') */
4430 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4432 /* It's ${var:N[:M]} thing */
4433 end_ch = '}' * 0x100 + ':';
4435 if (BASH_PATTERN_SUBST
4438 /* It's ${var/[/]pattern[/repl]} thing */
4439 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4441 nommu_addchr(as_string, '/');
4444 end_ch = '}' * 0x100 + '/';
4450 #if ENABLE_HUSH_DOLLAR_OPS
4451 last_ch = add_till_closing_bracket(dest, input, end_ch);
4452 if (last_ch == 0) /* error? */
4455 #error Simple code to only allow ${var} is not implemented
4458 o_addstr(as_string, dest->data + pos);
4459 o_addchr(as_string, last_ch);
4462 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4463 && (end_ch & 0xff00)
4465 /* close the first block: */
4466 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4467 /* while parsing N from ${var:N[:M]}
4468 * or pattern from ${var/[/]pattern[/repl]} */
4469 if ((end_ch & 0xff) == last_ch) {
4470 /* got ':' or '/'- parse the rest */
4475 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4476 /* it's ${var:N} - emulate :999999999 */
4477 o_addstr(dest, "999999999");
4478 } /* else: it's ${var/[/]pattern} */
4483 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4486 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4490 ch = i_getch(input);
4491 nommu_addchr(as_string, ch);
4492 # if ENABLE_FEATURE_SH_MATH
4493 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4494 ch = i_getch(input);
4495 nommu_addchr(as_string, ch);
4496 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4497 o_addchr(dest, /*quote_mask |*/ '+');
4500 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4501 return 0; /* error */
4503 o_addstr(as_string, dest->data + pos);
4504 o_addchr(as_string, ')');
4505 o_addchr(as_string, ')');
4507 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4511 # if ENABLE_HUSH_TICK
4512 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4513 o_addchr(dest, quote_mask | '`');
4516 if (!add_till_closing_bracket(dest, input, ')'))
4517 return 0; /* error */
4519 o_addstr(as_string, dest->data + pos);
4520 o_addchr(as_string, ')');
4522 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4528 ch = i_getch(input);
4529 nommu_addchr(as_string, ch);
4530 ch = i_peek_and_eat_bkslash_nl(input);
4531 if (isalnum(ch)) { /* it's $_name or $_123 */
4536 /* TODO: $_ and $-: */
4537 /* $_ Shell or shell script name; or last argument of last command
4538 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4539 * but in command's env, set to full pathname used to invoke it */
4540 /* $- Option flags set by set builtin or shell options (-i etc) */
4542 o_addQchr(dest, '$');
4544 debug_printf_parse("parse_dollar return 1 (ok)\n");
4550 # if BASH_PATTERN_SUBST
4551 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4552 encode_string(dest, input, dquote_end, process_bkslash)
4554 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4555 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4556 encode_string(dest, input, dquote_end)
4558 #define as_string NULL
4562 # if BASH_PATTERN_SUBST
4563 /* all parameters are needed, no macro tricks */
4565 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4566 encode_string(as_string, dest, input, dquote_end)
4569 static int encode_string(o_string *as_string,
4571 struct in_str *input,
4573 int process_bkslash)
4575 #if !BASH_PATTERN_SUBST
4576 const int process_bkslash = 1;
4582 ch = i_getch(input);
4584 nommu_addchr(as_string, ch);
4585 if (ch == dquote_end) { /* may be only '"' or EOF */
4586 debug_printf_parse("encode_string return 1 (ok)\n");
4589 /* note: can't move it above ch == dquote_end check! */
4591 syntax_error_unterm_ch('"');
4592 return 0; /* error */
4596 next = i_peek(input);
4598 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4599 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4600 if (process_bkslash && ch == '\\') {
4602 syntax_error("\\<eof>");
4606 * "The backslash retains its special meaning [in "..."]
4607 * only when followed by one of the following characters:
4608 * $, `, ", \, or <newline>. A double quote may be quoted
4609 * within double quotes by preceding it with a backslash."
4610 * NB: in (unquoted) heredoc, above does not apply to ",
4611 * therefore we check for it by "next == dquote_end" cond.
4613 if (next == dquote_end || strchr("$`\\\n", next)) {
4614 ch = i_getch(input); /* eat next */
4616 goto again; /* skip \<newline> */
4617 } /* else: ch remains == '\\', and we double it below: */
4618 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4619 nommu_addchr(as_string, ch);
4623 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4624 debug_printf_parse("encode_string return 0: "
4625 "parse_dollar returned 0 (error)\n");
4630 #if ENABLE_HUSH_TICK
4632 //unsigned pos = dest->length;
4633 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4634 o_addchr(dest, 0x80 | '`');
4635 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4636 return 0; /* error */
4637 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4638 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4642 o_addQchr(dest, ch);
4648 * Scan input until EOF or end_trigger char.
4649 * Return a list of pipes to execute, or NULL on EOF
4650 * or if end_trigger character is met.
4651 * On syntax error, exit if shell is not interactive,
4652 * reset parsing machinery and start parsing anew,
4653 * or return ERR_PTR.
4655 static struct pipe *parse_stream(char **pstring,
4656 struct in_str *input,
4659 struct parse_context ctx;
4660 o_string dest = NULL_O_STRING;
4663 /* Single-quote triggers a bypass of the main loop until its mate is
4664 * found. When recursing, quote state is passed in via dest->o_expflags.
4666 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4667 end_trigger ? end_trigger : 'X');
4670 /* If very first arg is "" or '', dest.data may end up NULL.
4671 * Preventing this: */
4672 o_addchr(&dest, '\0');
4675 /* We used to separate words on $IFS here. This was wrong.
4676 * $IFS is used only for word splitting when $var is expanded,
4677 * here we should use blank chars as separators, not $IFS
4680 if (MAYBE_ASSIGNMENT != 0)
4681 dest.o_assignment = MAYBE_ASSIGNMENT;
4682 initialize_context(&ctx);
4685 const char *is_blank;
4686 const char *is_special;
4690 redir_type redir_style;
4692 ch = i_getch(input);
4693 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4694 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4699 syntax_error_unterm_str("here document");
4702 if (end_trigger == ')') {
4703 syntax_error_unterm_ch('(');
4706 if (end_trigger == '}') {
4707 syntax_error_unterm_ch('{');
4711 if (done_word(&dest, &ctx)) {
4715 done_pipe(&ctx, PIPE_SEQ);
4717 /* If we got nothing... */
4718 /* (this makes bare "&" cmd a no-op.
4719 * bash says: "syntax error near unexpected token '&'") */
4720 if (pi->num_cmds == 0
4721 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4727 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4729 *pstring = ctx.as_string.data;
4731 o_free_unsafe(&ctx.as_string);
4734 debug_printf_parse("parse_stream return %p\n", pi);
4737 nommu_addchr(&ctx.as_string, ch);
4741 next = i_peek(input);
4743 is_special = "{}<>;&|()#'" /* special outside of "str" */
4744 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4745 /* Are { and } special here? */
4746 if (ctx.command->argv /* word [word]{... - non-special */
4747 || dest.length /* word{... - non-special */
4748 || dest.has_quoted_part /* ""{... - non-special */
4749 || (next != ';' /* }; - special */
4750 && next != ')' /* }) - special */
4751 && next != '(' /* {( - special */
4752 && next != '&' /* }& and }&& ... - special */
4753 && next != '|' /* }|| ... - special */
4754 && !strchr(defifs, next) /* {word - non-special */
4757 /* They are not special, skip "{}" */
4760 is_special = strchr(is_special, ch);
4761 is_blank = strchr(defifs, ch);
4763 if (!is_special && !is_blank) { /* ordinary char */
4765 o_addQchr(&dest, ch);
4766 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4767 || dest.o_assignment == WORD_IS_KEYWORD)
4769 && is_well_formed_var_name(dest.data, '=')
4771 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4772 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4778 if (done_word(&dest, &ctx)) {
4782 /* Is this a case when newline is simply ignored?
4784 * "cmd | <newline> cmd ..."
4785 * "case ... in <newline> word) ..."
4787 if (IS_NULL_CMD(ctx.command)
4788 && dest.length == 0 && !dest.has_quoted_part
4790 /* This newline can be ignored. But...
4791 * Without check #1, interactive shell
4792 * ignores even bare <newline>,
4793 * and shows the continuation prompt:
4794 * ps1_prompt$ <enter>
4795 * ps2> _ <=== wrong, should be ps1
4796 * Without check #2, "cmd & <newline>"
4797 * is similarly mistreated.
4798 * (BTW, this makes "cmd & cmd"
4799 * and "cmd && cmd" non-orthogonal.
4800 * Really, ask yourself, why
4801 * "cmd && <newline>" doesn't start
4802 * cmd but waits for more input?
4805 struct pipe *pi = ctx.list_head;
4806 if (pi->num_cmds != 0 /* check #1 */
4807 && pi->followup != PIPE_BG /* check #2 */
4812 /* Treat newline as a command separator. */
4813 done_pipe(&ctx, PIPE_SEQ);
4814 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4816 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4821 dest.o_assignment = MAYBE_ASSIGNMENT;
4822 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4824 /* note: if (is_blank) continue;
4825 * will still trigger for us */
4829 /* "cmd}" or "cmd }..." without semicolon or &:
4830 * } is an ordinary char in this case, even inside { cmd; }
4831 * Pathological example: { ""}; } should exec "}" cmd
4834 if (dest.length != 0 /* word} */
4835 || dest.has_quoted_part /* ""} */
4839 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4840 /* Generally, there should be semicolon: "cmd; }"
4841 * However, bash allows to omit it if "cmd" is
4842 * a group. Examples:
4845 * { echo 0 >&2 | { echo 1; } }
4846 * { while false; do :; done }
4847 * { case a in b) ;; esac }
4849 if (ctx.command->group)
4853 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4854 /* Can't be an end of {cmd}, skip the check */
4855 goto skip_end_trigger;
4856 /* else: } does terminate a group */
4859 if (end_trigger && end_trigger == ch
4860 && (ch != ';' || heredoc_cnt == 0)
4861 #if ENABLE_HUSH_CASE
4863 || ctx.ctx_res_w != RES_MATCH
4864 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4869 /* This is technically valid:
4870 * { cat <<HERE; }; echo Ok
4874 * but we don't support this.
4875 * We require heredoc to be in enclosing {}/(),
4878 syntax_error_unterm_str("here document");
4881 if (done_word(&dest, &ctx)) {
4884 done_pipe(&ctx, PIPE_SEQ);
4885 dest.o_assignment = MAYBE_ASSIGNMENT;
4886 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4887 /* Do we sit outside of any if's, loops or case's? */
4889 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4893 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4895 *pstring = ctx.as_string.data;
4897 o_free_unsafe(&ctx.as_string);
4900 debug_printf_parse("parse_stream return %p: "
4901 "end_trigger char found\n",
4903 return ctx.list_head;
4910 /* Catch <, > before deciding whether this word is
4911 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4914 redir_fd = redirect_opt_num(&dest);
4915 if (done_word(&dest, &ctx)) {
4918 redir_style = REDIRECT_OVERWRITE;
4920 redir_style = REDIRECT_APPEND;
4921 ch = i_getch(input);
4922 nommu_addchr(&ctx.as_string, ch);
4925 else if (next == '(') {
4926 syntax_error(">(process) not supported");
4930 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4932 continue; /* back to top of while (1) */
4934 redir_fd = redirect_opt_num(&dest);
4935 if (done_word(&dest, &ctx)) {
4938 redir_style = REDIRECT_INPUT;
4940 redir_style = REDIRECT_HEREDOC;
4942 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4943 ch = i_getch(input);
4944 nommu_addchr(&ctx.as_string, ch);
4945 } else if (next == '>') {
4946 redir_style = REDIRECT_IO;
4947 ch = i_getch(input);
4948 nommu_addchr(&ctx.as_string, ch);
4951 else if (next == '(') {
4952 syntax_error("<(process) not supported");
4956 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4958 continue; /* back to top of while (1) */
4960 if (dest.length == 0 && !dest.has_quoted_part) {
4961 /* skip "#comment" */
4964 if (ch == EOF || ch == '\n')
4967 /* note: we do not add it to &ctx.as_string */
4969 nommu_addchr(&ctx.as_string, '\n');
4970 continue; /* back to top of while (1) */
4975 /* It's "\<newline>" */
4977 /* Remove trailing '\' from ctx.as_string */
4978 ctx.as_string.data[--ctx.as_string.length] = '\0';
4980 ch = i_getch(input); /* eat it */
4981 continue; /* back to top of while (1) */
4986 if (dest.o_assignment == MAYBE_ASSIGNMENT
4987 /* check that we are not in word in "a=1 2>word b=1": */
4988 && !ctx.pending_redirect
4990 /* ch is a special char and thus this word
4991 * cannot be an assignment */
4992 dest.o_assignment = NOT_ASSIGNMENT;
4993 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4996 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4999 case '#': /* non-comment #: "echo a#b" etc */
5000 o_addQchr(&dest, ch);
5004 syntax_error("\\<eof>");
5007 ch = i_getch(input);
5008 /* note: ch != '\n' (that case does not reach this place) */
5009 o_addchr(&dest, '\\');
5010 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5011 o_addchr(&dest, ch);
5012 nommu_addchr(&ctx.as_string, ch);
5013 /* Example: echo Hello \2>file
5014 * we need to know that word 2 is quoted */
5015 dest.has_quoted_part = 1;
5018 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5019 debug_printf_parse("parse_stream parse error: "
5020 "parse_dollar returned 0 (error)\n");
5025 dest.has_quoted_part = 1;
5026 if (next == '\'' && !ctx.pending_redirect) {
5027 insert_empty_quoted_str_marker:
5028 nommu_addchr(&ctx.as_string, next);
5029 i_getch(input); /* eat second ' */
5030 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5031 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5034 ch = i_getch(input);
5036 syntax_error_unterm_ch('\'');
5039 nommu_addchr(&ctx.as_string, ch);
5042 o_addqchr(&dest, ch);
5047 dest.has_quoted_part = 1;
5048 if (next == '"' && !ctx.pending_redirect)
5049 goto insert_empty_quoted_str_marker;
5050 if (dest.o_assignment == NOT_ASSIGNMENT)
5051 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5052 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5054 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5056 #if ENABLE_HUSH_TICK
5058 USE_FOR_NOMMU(unsigned pos;)
5060 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5061 o_addchr(&dest, '`');
5062 USE_FOR_NOMMU(pos = dest.length;)
5063 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5066 o_addstr(&ctx.as_string, dest.data + pos);
5067 o_addchr(&ctx.as_string, '`');
5069 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5070 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5075 #if ENABLE_HUSH_CASE
5078 if (done_word(&dest, &ctx)) {
5081 done_pipe(&ctx, PIPE_SEQ);
5082 #if ENABLE_HUSH_CASE
5083 /* Eat multiple semicolons, detect
5084 * whether it means something special */
5089 ch = i_getch(input);
5090 nommu_addchr(&ctx.as_string, ch);
5091 if (ctx.ctx_res_w == RES_CASE_BODY) {
5092 ctx.ctx_dsemicolon = 1;
5093 ctx.ctx_res_w = RES_MATCH;
5099 /* We just finished a cmd. New one may start
5100 * with an assignment */
5101 dest.o_assignment = MAYBE_ASSIGNMENT;
5102 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5105 if (done_word(&dest, &ctx)) {
5109 ch = i_getch(input);
5110 nommu_addchr(&ctx.as_string, ch);
5111 done_pipe(&ctx, PIPE_AND);
5113 done_pipe(&ctx, PIPE_BG);
5117 if (done_word(&dest, &ctx)) {
5120 #if ENABLE_HUSH_CASE
5121 if (ctx.ctx_res_w == RES_MATCH)
5122 break; /* we are in case's "word | word)" */
5124 if (next == '|') { /* || */
5125 ch = i_getch(input);
5126 nommu_addchr(&ctx.as_string, ch);
5127 done_pipe(&ctx, PIPE_OR);
5129 /* we could pick up a file descriptor choice here
5130 * with redirect_opt_num(), but bash doesn't do it.
5131 * "echo foo 2| cat" yields "foo 2". */
5136 #if ENABLE_HUSH_CASE
5137 /* "case... in [(]word)..." - skip '(' */
5138 if (ctx.ctx_res_w == RES_MATCH
5139 && ctx.command->argv == NULL /* not (word|(... */
5140 && dest.length == 0 /* not word(... */
5141 && dest.has_quoted_part == 0 /* not ""(... */
5147 if (parse_group(&dest, &ctx, input, ch) != 0) {
5152 #if ENABLE_HUSH_CASE
5153 if (ctx.ctx_res_w == RES_MATCH)
5157 /* proper use of this character is caught by end_trigger:
5158 * if we see {, we call parse_group(..., end_trigger='}')
5159 * and it will match } earlier (not here). */
5160 syntax_error_unexpected_ch(ch);
5161 G.last_exitcode = 2;
5165 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5170 G.last_exitcode = 1;
5173 struct parse_context *pctx;
5174 IF_HAS_KEYWORDS(struct parse_context *p2;)
5176 /* Clean up allocated tree.
5177 * Sample for finding leaks on syntax error recovery path.
5178 * Run it from interactive shell, watch pmap `pidof hush`.
5179 * while if false; then false; fi; do break; fi
5180 * Samples to catch leaks at execution:
5181 * while if (true | { true;}); then echo ok; fi; do break; done
5182 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5186 /* Update pipe/command counts,
5187 * otherwise freeing may miss some */
5188 done_pipe(pctx, PIPE_SEQ);
5189 debug_printf_clean("freeing list %p from ctx %p\n",
5190 pctx->list_head, pctx);
5191 debug_print_tree(pctx->list_head, 0);
5192 free_pipe_list(pctx->list_head);
5193 debug_printf_clean("freed list %p\n", pctx->list_head);
5195 o_free_unsafe(&pctx->as_string);
5197 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5201 IF_HAS_KEYWORDS(pctx = p2;)
5202 } while (HAS_KEYWORDS && pctx);
5215 /*** Execution routines ***/
5217 /* Expansion can recurse, need forward decls: */
5218 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5219 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5220 #define expand_string_to_string(str, do_unbackslash) \
5221 expand_string_to_string(str)
5223 static char *expand_string_to_string(const char *str, int do_unbackslash);
5224 #if ENABLE_HUSH_TICK
5225 static int process_command_subs(o_string *dest, const char *s);
5228 /* expand_strvec_to_strvec() takes a list of strings, expands
5229 * all variable references within and returns a pointer to
5230 * a list of expanded strings, possibly with larger number
5231 * of strings. (Think VAR="a b"; echo $VAR).
5232 * This new list is allocated as a single malloc block.
5233 * NULL-terminated list of char* pointers is at the beginning of it,
5234 * followed by strings themselves.
5235 * Caller can deallocate entire list by single free(list). */
5237 /* A horde of its helpers come first: */
5239 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5241 while (--len >= 0) {
5244 #if ENABLE_HUSH_BRACE_EXPANSION
5245 if (c == '{' || c == '}') {
5246 /* { -> \{, } -> \} */
5248 /* And now we want to add { or } and continue:
5251 * luckily, just falling through achieves this.
5257 /* \z -> \\\z; \<eol> -> \\<eol> */
5262 o_addchr(o, *str++);
5268 /* Store given string, finalizing the word and starting new one whenever
5269 * we encounter IFS char(s). This is used for expanding variable values.
5270 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5271 * Return in *ended_with_ifs:
5272 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5274 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5276 int last_is_ifs = 0;
5281 if (!*str) /* EOL - do not finalize word */
5283 word_len = strcspn(str, G.ifs);
5285 /* We have WORD_LEN leading non-IFS chars */
5286 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5287 o_addblock(output, str, word_len);
5289 /* Protect backslashes against globbing up :)
5290 * Example: "v='\*'; echo b$v" prints "b\*"
5291 * (and does not try to glob on "*")
5293 o_addblock_duplicate_backslash(output, str, word_len);
5294 /*/ Why can't we do it easier? */
5295 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5296 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5300 if (!*str) /* EOL - do not finalize word */
5304 /* We know str here points to at least one IFS char */
5306 str += strspn(str, G.ifs); /* skip IFS chars */
5307 if (!*str) /* EOL - do not finalize word */
5310 /* Start new word... but not always! */
5311 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5312 if (output->has_quoted_part
5313 /* Case "v=' a'; echo $v":
5314 * here nothing precedes the space in $v expansion,
5315 * therefore we should not finish the word
5316 * (IOW: if there *is* word to finalize, only then do it):
5318 || (n > 0 && output->data[output->length - 1])
5320 o_addchr(output, '\0');
5321 debug_print_list("expand_on_ifs", output, n);
5322 n = o_save_ptr(output, n);
5327 *ended_with_ifs = last_is_ifs;
5328 debug_print_list("expand_on_ifs[1]", output, n);
5332 /* Helper to expand $((...)) and heredoc body. These act as if
5333 * they are in double quotes, with the exception that they are not :).
5334 * Just the rules are similar: "expand only $var and `cmd`"
5336 * Returns malloced string.
5337 * As an optimization, we return NULL if expansion is not needed.
5339 #if !BASH_PATTERN_SUBST
5340 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5341 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5342 encode_then_expand_string(str)
5344 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5346 #if !BASH_PATTERN_SUBST
5347 const int do_unbackslash = 1;
5350 struct in_str input;
5351 o_string dest = NULL_O_STRING;
5353 if (!strchr(str, '$')
5354 && !strchr(str, '\\')
5355 #if ENABLE_HUSH_TICK
5356 && !strchr(str, '`')
5362 /* We need to expand. Example:
5363 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5365 setup_string_in_str(&input, str);
5366 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5367 //TODO: error check (encode_string returns 0 on error)?
5368 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5369 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5370 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5371 o_free_unsafe(&dest);
5375 #if ENABLE_FEATURE_SH_MATH
5376 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5378 arith_state_t math_state;
5382 math_state.lookupvar = get_local_var_value;
5383 math_state.setvar = set_local_var_from_halves;
5384 //math_state.endofname = endofname;
5385 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5386 res = arith(&math_state, exp_str ? exp_str : arg);
5389 *errmsg_p = math_state.errmsg;
5390 if (math_state.errmsg)
5391 die_if_script(math_state.errmsg);
5396 #if BASH_PATTERN_SUBST
5397 /* ${var/[/]pattern[/repl]} helpers */
5398 static char *strstr_pattern(char *val, const char *pattern, int *size)
5401 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5402 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5409 /* Optimization: if "*pat" did not match the start of "string",
5410 * we know that "tring", "ring" etc will not match too:
5412 if (pattern[0] == '*')
5417 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5419 char *result = NULL;
5420 unsigned res_len = 0;
5421 unsigned repl_len = strlen(repl);
5425 char *s = strstr_pattern(val, pattern, &size);
5429 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5430 memcpy(result + res_len, val, s - val);
5432 strcpy(result + res_len, repl);
5433 res_len += repl_len;
5434 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5440 if (val[0] && result) {
5441 result = xrealloc(result, res_len + strlen(val) + 1);
5442 strcpy(result + res_len, val);
5443 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5445 debug_printf_varexp("result:'%s'\n", result);
5448 #endif /* BASH_PATTERN_SUBST */
5451 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5453 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5455 const char *val = NULL;
5456 char *to_be_freed = NULL;
5461 char exp_save = exp_save; /* for compiler */
5462 char *exp_saveptr; /* points to expansion operator */
5463 char *exp_word = exp_word; /* for compiler */
5466 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5468 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5470 first_char = arg[0] = arg0 & 0x7f;
5473 if (first_char == '#' /* ${#... */
5474 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5476 /* It must be length operator: ${#var} */
5480 /* Maybe handle parameter expansion */
5481 if (exp_saveptr /* if 2nd char is one of expansion operators */
5482 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5484 /* ${?:0}, ${#[:]%0} etc */
5485 exp_saveptr = var + 1;
5487 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5488 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5490 exp_op = exp_save = *exp_saveptr;
5492 exp_word = exp_saveptr + 1;
5493 if (exp_op == ':') {
5494 exp_op = *exp_word++;
5495 //TODO: try ${var:} and ${var:bogus} in non-bash config
5497 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5499 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5504 *exp_saveptr = '\0';
5505 } /* else: it's not an expansion op, but bare ${var} */
5508 /* Look up the variable in question */
5509 if (isdigit(var[0])) {
5510 /* parse_dollar should have vetted var for us */
5511 int n = xatoi_positive(var);
5512 if (n < G.global_argc)
5513 val = G.global_argv[n];
5514 /* else val remains NULL: $N with too big N */
5518 val = utoa(G.root_pid);
5520 case '!': /* bg pid */
5521 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5523 case '?': /* exitcode */
5524 val = utoa(G.last_exitcode);
5526 case '#': /* argc */
5527 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5530 val = get_local_var_value(var);
5534 /* Handle any expansions */
5535 if (exp_op == 'L') {
5536 reinit_unicode_for_hush();
5537 debug_printf_expand("expand: length(%s)=", val);
5538 val = utoa(val ? unicode_strlen(val) : 0);
5539 debug_printf_expand("%s\n", val);
5540 } else if (exp_op) {
5541 if (exp_op == '%' || exp_op == '#') {
5542 /* Standard-mandated substring removal ops:
5543 * ${parameter%word} - remove smallest suffix pattern
5544 * ${parameter%%word} - remove largest suffix pattern
5545 * ${parameter#word} - remove smallest prefix pattern
5546 * ${parameter##word} - remove largest prefix pattern
5548 * Word is expanded to produce a glob pattern.
5549 * Then var's value is matched to it and matching part removed.
5551 if (val && val[0]) {
5555 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5556 if (exp_op == *exp_word) /* ## or %% */
5558 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5560 exp_word = exp_exp_word;
5561 /* HACK ALERT. We depend here on the fact that
5562 * G.global_argv and results of utoa and get_local_var_value
5563 * are actually in writable memory:
5564 * scan_and_match momentarily stores NULs there. */
5566 loc = scan_and_match(t, exp_word, scan_flags);
5567 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5568 // exp_op, t, exp_word, loc);
5570 if (loc) { /* match was found */
5571 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5572 val = loc; /* take right part */
5574 val = to_be_freed = xstrndup(val, loc - val); /* left */
5578 #if BASH_PATTERN_SUBST
5579 else if (exp_op == '/' || exp_op == '\\') {
5580 /* It's ${var/[/]pattern[/repl]} thing.
5581 * Note that in encoded form it has TWO parts:
5582 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5583 * and if // is used, it is encoded as \:
5584 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5586 /* Empty variable always gives nothing: */
5587 // "v=''; echo ${v/*/w}" prints "", not "w"
5588 if (val && val[0]) {
5589 /* pattern uses non-standard expansion.
5590 * repl should be unbackslashed and globbed
5591 * by the usual expansion rules:
5593 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5594 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5595 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5596 * v='a bz'; echo ${v/a*z/\z} prints "z"
5597 * (note that a*z _pattern_ is never globbed!)
5599 char *pattern, *repl, *t;
5600 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5602 pattern = xstrdup(exp_word);
5603 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5604 *p++ = SPECIAL_VAR_SYMBOL;
5606 p = strchr(p, SPECIAL_VAR_SYMBOL);
5608 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5609 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5610 /* HACK ALERT. We depend here on the fact that
5611 * G.global_argv and results of utoa and get_local_var_value
5612 * are actually in writable memory:
5613 * replace_pattern momentarily stores NULs there. */
5615 to_be_freed = replace_pattern(t,
5617 (repl ? repl : exp_word),
5619 if (to_be_freed) /* at least one replace happened */
5625 #endif /* BASH_PATTERN_SUBST */
5626 else if (exp_op == ':') {
5627 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5628 /* It's ${var:N[:M]} bashism.
5629 * Note that in encoded form it has TWO parts:
5630 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5635 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5638 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5639 *p++ = SPECIAL_VAR_SYMBOL;
5641 p = strchr(p, SPECIAL_VAR_SYMBOL);
5643 len = expand_and_evaluate_arith(exp_word, &errmsg);
5646 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5647 if (len >= 0) { /* bash compat: len < 0 is illegal */
5649 /* negative beg counts from the end */
5650 beg = (arith_t)strlen(val) + beg;
5651 if (beg < 0) /* ${v: -999999} is "" */
5654 debug_printf_varexp("from val:'%s'\n", val);
5655 if (len == 0 || !val || beg >= strlen(val)) {
5659 /* Paranoia. What if user entered 9999999999999
5660 * which fits in arith_t but not int? */
5663 val = to_be_freed = xstrndup(val + beg, len);
5665 debug_printf_varexp("val:'%s'\n", val);
5667 #endif /* HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH */
5669 die_if_script("malformed ${%s:...}", var);
5672 } else { /* one of "-=+?" */
5673 /* Standard-mandated substitution ops:
5674 * ${var?word} - indicate error if unset
5675 * If var is unset, word (or a message indicating it is unset
5676 * if word is null) is written to standard error
5677 * and the shell exits with a non-zero exit status.
5678 * Otherwise, the value of var is substituted.
5679 * ${var-word} - use default value
5680 * If var is unset, word is substituted.
5681 * ${var=word} - assign and use default value
5682 * If var is unset, word is assigned to var.
5683 * In all cases, final value of var is substituted.
5684 * ${var+word} - use alternative value
5685 * If var is unset, null is substituted.
5686 * Otherwise, word is substituted.
5688 * Word is subjected to tilde expansion, parameter expansion,
5689 * command substitution, and arithmetic expansion.
5690 * If word is not needed, it is not expanded.
5692 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5693 * but also treat null var as if it is unset.
5695 int use_word = (!val || ((exp_save == ':') && !val[0]));
5697 use_word = !use_word;
5698 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5699 (exp_save == ':') ? "true" : "false", use_word);
5701 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5703 exp_word = to_be_freed;
5704 if (exp_op == '?') {
5705 /* mimic bash message */
5706 die_if_script("%s: %s",
5708 exp_word[0] ? exp_word : "parameter null or not set"
5710 //TODO: how interactive bash aborts expansion mid-command?
5715 if (exp_op == '=') {
5716 /* ${var=[word]} or ${var:=[word]} */
5717 if (isdigit(var[0]) || var[0] == '#') {
5718 /* mimic bash message */
5719 die_if_script("$%s: cannot assign in this way", var);
5722 char *new_var = xasprintf("%s=%s", var, val);
5723 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5727 } /* one of "-=+?" */
5729 *exp_saveptr = exp_save;
5735 *to_be_freed_pp = to_be_freed;
5739 /* Expand all variable references in given string, adding words to list[]
5740 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5741 * to be filled). This routine is extremely tricky: has to deal with
5742 * variables/parameters with whitespace, $* and $@, and constructs like
5743 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5744 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5746 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5747 * expansion of right-hand side of assignment == 1-element expand.
5749 char cant_be_null = 0; /* only bit 0x80 matters */
5750 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5753 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5754 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5755 debug_print_list("expand_vars_to_list", output, n);
5756 n = o_save_ptr(output, n);
5757 debug_print_list("expand_vars_to_list[0]", output, n);
5759 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5761 char *to_be_freed = NULL;
5762 const char *val = NULL;
5763 #if ENABLE_HUSH_TICK
5764 o_string subst_result = NULL_O_STRING;
5766 #if ENABLE_FEATURE_SH_MATH
5767 char arith_buf[sizeof(arith_t)*3 + 2];
5771 o_addchr(output, '\0');
5772 n = o_save_ptr(output, n);
5776 o_addblock(output, arg, p - arg);
5777 debug_print_list("expand_vars_to_list[1]", output, n);
5779 p = strchr(p, SPECIAL_VAR_SYMBOL);
5781 /* Fetch special var name (if it is indeed one of them)
5782 * and quote bit, force the bit on if singleword expansion -
5783 * important for not getting v=$@ expand to many words. */
5784 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5786 /* Is this variable quoted and thus expansion can't be null?
5787 * "$@" is special. Even if quoted, it can still
5788 * expand to nothing (not even an empty string),
5789 * thus it is excluded. */
5790 if ((first_ch & 0x7f) != '@')
5791 cant_be_null |= first_ch;
5793 switch (first_ch & 0x7f) {
5794 /* Highest bit in first_ch indicates that var is double-quoted */
5798 if (!G.global_argv[1])
5801 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5802 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5803 while (G.global_argv[i]) {
5804 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5805 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5806 if (G.global_argv[i++][0] && G.global_argv[i]) {
5807 /* this argv[] is not empty and not last:
5808 * put terminating NUL, start new word */
5809 o_addchr(output, '\0');
5810 debug_print_list("expand_vars_to_list[2]", output, n);
5811 n = o_save_ptr(output, n);
5812 debug_print_list("expand_vars_to_list[3]", output, n);
5816 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5817 * and in this case should treat it like '$*' - see 'else...' below */
5818 if (first_ch == ('@'|0x80) /* quoted $@ */
5819 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5822 o_addQstr(output, G.global_argv[i]);
5823 if (++i >= G.global_argc)
5825 o_addchr(output, '\0');
5826 debug_print_list("expand_vars_to_list[4]", output, n);
5827 n = o_save_ptr(output, n);
5829 } else { /* quoted $* (or v="$@" case): add as one word */
5831 o_addQstr(output, G.global_argv[i]);
5832 if (!G.global_argv[++i])
5835 o_addchr(output, G.ifs[0]);
5837 output->has_quoted_part = 1;
5841 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5842 /* "Empty variable", used to make "" etc to not disappear */
5843 output->has_quoted_part = 1;
5845 cant_be_null = 0x80;
5847 #if ENABLE_HUSH_TICK
5848 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5849 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5851 /* Can't just stuff it into output o_string,
5852 * expanded result may need to be globbed
5854 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5855 G.last_exitcode = process_command_subs(&subst_result, arg);
5856 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5857 val = subst_result.data;
5860 #if ENABLE_FEATURE_SH_MATH
5861 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5864 arg++; /* skip '+' */
5865 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5866 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5867 res = expand_and_evaluate_arith(arg, NULL);
5868 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5869 sprintf(arith_buf, ARITH_FMT, res);
5875 val = expand_one_var(&to_be_freed, arg, &p);
5876 IF_HUSH_TICK(store_val:)
5877 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5878 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5879 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5880 if (val && val[0]) {
5881 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5884 } else { /* quoted $VAR, val will be appended below */
5885 output->has_quoted_part = 1;
5886 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5887 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5890 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5892 if (val && val[0]) {
5893 o_addQstr(output, val);
5897 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5898 * Do the check to avoid writing to a const string. */
5899 if (*p != SPECIAL_VAR_SYMBOL)
5900 *p = SPECIAL_VAR_SYMBOL;
5902 #if ENABLE_HUSH_TICK
5903 o_free(&subst_result);
5906 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5910 o_addchr(output, '\0');
5911 n = o_save_ptr(output, n);
5913 debug_print_list("expand_vars_to_list[a]", output, n);
5914 /* this part is literal, and it was already pre-quoted
5915 * if needed (much earlier), do not use o_addQstr here! */
5916 o_addstr_with_NUL(output, arg);
5917 debug_print_list("expand_vars_to_list[b]", output, n);
5918 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5919 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5922 /* allow to reuse list[n] later without re-growth */
5923 output->has_empty_slot = 1;
5925 o_addchr(output, '\0');
5931 static char **expand_variables(char **argv, unsigned expflags)
5935 o_string output = NULL_O_STRING;
5937 output.o_expflags = expflags;
5941 n = expand_vars_to_list(&output, n, *argv);
5944 debug_print_list("expand_variables", &output, n);
5946 /* output.data (malloced in one block) gets returned in "list" */
5947 list = o_finalize_list(&output, n);
5948 debug_print_strings("expand_variables[1]", list);
5952 static char **expand_strvec_to_strvec(char **argv)
5954 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5958 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5960 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5964 /* Used for expansion of right hand of assignments,
5965 * $((...)), heredocs, variable espansion parts.
5967 * NB: should NOT do globbing!
5968 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5970 static char *expand_string_to_string(const char *str, int do_unbackslash)
5972 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5973 const int do_unbackslash = 1;
5975 char *argv[2], **list;
5977 debug_printf_expand("string_to_string<='%s'\n", str);
5978 /* This is generally an optimization, but it also
5979 * handles "", which otherwise trips over !list[0] check below.
5980 * (is this ever happens that we actually get str="" here?)
5982 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5983 //TODO: Can use on strings with \ too, just unbackslash() them?
5984 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5985 return xstrdup(str);
5988 argv[0] = (char*)str;
5990 list = expand_variables(argv, do_unbackslash
5991 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5992 : EXP_FLAG_SINGLEWORD
5995 if (!list[0] || list[1])
5996 bb_error_msg_and_die("BUG in varexp2");
5997 /* actually, just move string 2*sizeof(char*) bytes back */
5998 overlapping_strcpy((char*)list, list[0]);
6000 unbackslash((char*)list);
6001 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6005 /* Used for "eval" builtin and case string */
6006 static char* expand_strvec_to_string(char **argv)
6010 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6011 /* Convert all NULs to spaces */
6016 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6017 bb_error_msg_and_die("BUG in varexp3");
6018 /* bash uses ' ' regardless of $IFS contents */
6023 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6024 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6028 static char **expand_assignments(char **argv, int count)
6033 G.expanded_assignments = p = NULL;
6034 /* Expand assignments into one string each */
6035 for (i = 0; i < count; i++) {
6036 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6038 G.expanded_assignments = NULL;
6043 static void switch_off_special_sigs(unsigned mask)
6046 while ((mask >>= 1) != 0) {
6050 #if ENABLE_HUSH_TRAP
6052 if (G_traps[sig] && !G_traps[sig][0])
6053 /* trap is '', has to remain SIG_IGN */
6056 G_traps[sig] = NULL;
6059 /* We are here only if no trap or trap was not '' */
6060 install_sighandler(sig, SIG_DFL);
6066 void re_execute_shell(char ***to_free, const char *s,
6067 char *g_argv0, char **g_argv,
6068 char **builtin_argv) NORETURN;
6070 static void reset_traps_to_defaults(void)
6072 /* This function is always called in a child shell
6073 * after fork (not vfork, NOMMU doesn't use this function).
6075 IF_HUSH_TRAP(unsigned sig;)
6078 /* Child shells are not interactive.
6079 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6080 * Testcase: (while :; do :; done) + ^Z should background.
6081 * Same goes for SIGTERM, SIGHUP, SIGINT.
6083 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6084 if (!G_traps && !mask)
6085 return; /* already no traps and no special sigs */
6087 /* Switch off special sigs */
6088 switch_off_special_sigs(mask);
6089 # if ENABLE_HUSH_JOB
6090 G_fatal_sig_mask = 0;
6092 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6093 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6094 * remain set in G.special_sig_mask */
6096 # if ENABLE_HUSH_TRAP
6100 /* Reset all sigs to default except ones with empty traps */
6101 for (sig = 0; sig < NSIG; sig++) {
6103 continue; /* no trap: nothing to do */
6104 if (!G_traps[sig][0])
6105 continue; /* empty trap: has to remain SIG_IGN */
6106 /* sig has non-empty trap, reset it: */
6108 G_traps[sig] = NULL;
6109 /* There is no signal for trap 0 (EXIT) */
6112 install_sighandler(sig, pick_sighandler(sig));
6119 static void re_execute_shell(char ***to_free, const char *s,
6120 char *g_argv0, char **g_argv,
6121 char **builtin_argv) NORETURN;
6122 static void re_execute_shell(char ***to_free, const char *s,
6123 char *g_argv0, char **g_argv,
6124 char **builtin_argv)
6126 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6127 /* delims + 2 * (number of bytes in printed hex numbers) */
6128 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6129 char *heredoc_argv[4];
6130 struct variable *cur;
6131 # if ENABLE_HUSH_FUNCTIONS
6132 struct function *funcp;
6136 unsigned long long empty_trap_mask;
6138 if (!g_argv0) { /* heredoc */
6139 argv = heredoc_argv;
6140 argv[0] = (char *) G.argv0_for_re_execing;
6141 argv[1] = (char *) "-<";
6142 argv[2] = (char *) s;
6144 pp = &argv[3]; /* used as pointer to empty environment */
6150 if (pp) while (*pp++)
6153 empty_trap_mask = 0;
6156 for (sig = 1; sig < NSIG; sig++) {
6157 if (G_traps[sig] && !G_traps[sig][0])
6158 empty_trap_mask |= 1LL << sig;
6162 sprintf(param_buf, NOMMU_HACK_FMT
6163 , (unsigned) G.root_pid
6164 , (unsigned) G.root_ppid
6165 , (unsigned) G.last_bg_pid
6166 , (unsigned) G.last_exitcode
6169 IF_HUSH_LOOPS(, G.depth_of_loop)
6171 # undef NOMMU_HACK_FMT
6172 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6173 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6176 for (cur = G.top_var; cur; cur = cur->next) {
6177 if (!cur->flg_export || cur->flg_read_only)
6180 # if ENABLE_HUSH_FUNCTIONS
6181 for (funcp = G.top_func; funcp; funcp = funcp->next)
6187 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6188 *pp++ = (char *) G.argv0_for_re_execing;
6190 for (cur = G.top_var; cur; cur = cur->next) {
6191 if (strcmp(cur->varstr, hush_version_str) == 0)
6193 if (cur->flg_read_only) {
6194 *pp++ = (char *) "-R";
6195 *pp++ = cur->varstr;
6196 } else if (!cur->flg_export) {
6197 *pp++ = (char *) "-V";
6198 *pp++ = cur->varstr;
6201 # if ENABLE_HUSH_FUNCTIONS
6202 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6203 *pp++ = (char *) "-F";
6204 *pp++ = funcp->name;
6205 *pp++ = funcp->body_as_string;
6208 /* We can pass activated traps here. Say, -Tnn:trap_string
6210 * However, POSIX says that subshells reset signals with traps
6212 * I tested bash-3.2 and it not only does that with true subshells
6213 * of the form ( list ), but with any forked children shells.
6214 * I set trap "echo W" WINCH; and then tried:
6216 * { echo 1; sleep 20; echo 2; } &
6217 * while true; do echo 1; sleep 20; echo 2; break; done &
6218 * true | { echo 1; sleep 20; echo 2; } | cat
6220 * In all these cases sending SIGWINCH to the child shell
6221 * did not run the trap. If I add trap "echo V" WINCH;
6222 * _inside_ group (just before echo 1), it works.
6224 * I conclude it means we don't need to pass active traps here.
6226 *pp++ = (char *) "-c";
6229 while (*++builtin_argv)
6230 *pp++ = *builtin_argv;
6231 *pp++ = (char *) "";
6236 /* *pp = NULL; - is already there */
6240 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6241 /* Don't propagate SIG_IGN to the child */
6242 if (SPECIAL_JOBSTOP_SIGS != 0)
6243 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6244 execve(bb_busybox_exec_path, argv, pp);
6245 /* Fallback. Useful for init=/bin/hush usage etc */
6246 if (argv[0][0] == '/')
6247 execve(argv[0], argv, pp);
6248 xfunc_error_retval = 127;
6249 bb_error_msg_and_die("can't re-execute the shell");
6251 #endif /* !BB_MMU */
6254 static int run_and_free_list(struct pipe *pi);
6256 /* Executing from string: eval, sh -c '...'
6257 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6258 * end_trigger controls how often we stop parsing
6259 * NUL: parse all, execute, return
6260 * ';': parse till ';' or newline, execute, repeat till EOF
6262 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6264 /* Why we need empty flag?
6265 * An obscure corner case "false; ``; echo $?":
6266 * empty command in `` should still set $? to 0.
6267 * But we can't just set $? to 0 at the start,
6268 * this breaks "false; echo `echo $?`" case.
6272 struct pipe *pipe_list;
6274 #if ENABLE_HUSH_INTERACTIVE
6275 if (end_trigger == ';')
6276 inp->promptmode = 0; /* PS1 */
6278 pipe_list = parse_stream(NULL, inp, end_trigger);
6279 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6280 /* If we are in "big" script
6281 * (not in `cmd` or something similar)...
6283 if (pipe_list == ERR_PTR && end_trigger == ';') {
6284 /* Discard cached input (rest of line) */
6285 int ch = inp->last_char;
6286 while (ch != EOF && ch != '\n') {
6287 //bb_error_msg("Discarded:'%c'", ch);
6292 /* This stream isn't empty */
6296 if (!pipe_list && empty)
6297 G.last_exitcode = 0;
6300 debug_print_tree(pipe_list, 0);
6301 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6302 run_and_free_list(pipe_list);
6304 if (G_flag_return_in_progress == 1)
6309 static void parse_and_run_string(const char *s)
6311 struct in_str input;
6312 setup_string_in_str(&input, s);
6313 parse_and_run_stream(&input, '\0');
6316 static void parse_and_run_file(FILE *f)
6318 struct in_str input;
6319 setup_file_in_str(&input, f);
6320 parse_and_run_stream(&input, ';');
6323 #if ENABLE_HUSH_TICK
6324 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6329 char **to_free = NULL;
6333 pid = BB_MMU ? xfork() : xvfork();
6334 if (pid == 0) { /* child */
6335 disable_restore_tty_pgrp_on_exit();
6336 /* Process substitution is not considered to be usual
6337 * 'command execution'.
6338 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6345 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6346 close(channel[0]); /* NB: close _first_, then move fd! */
6347 xmove_fd(channel[1], 1);
6348 /* Prevent it from trying to handle ctrl-z etc */
6349 IF_HUSH_JOB(G.run_list_level = 1;)
6350 # if ENABLE_HUSH_TRAP
6351 /* Awful hack for `trap` or $(trap).
6353 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6354 * contains an example where "trap" is executed in a subshell:
6356 * save_traps=$(trap)
6358 * eval "$save_traps"
6360 * Standard does not say that "trap" in subshell shall print
6361 * parent shell's traps. It only says that its output
6362 * must have suitable form, but then, in the above example
6363 * (which is not supposed to be normative), it implies that.
6365 * bash (and probably other shell) does implement it
6366 * (traps are reset to defaults, but "trap" still shows them),
6367 * but as a result, "trap" logic is hopelessly messed up:
6370 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6371 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6372 * # true | trap <--- trap is in subshell - no output (ditto)
6373 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6374 * trap -- 'echo Ho' SIGWINCH
6375 * # echo `(trap)` <--- in subshell in subshell - output
6376 * trap -- 'echo Ho' SIGWINCH
6377 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6378 * trap -- 'echo Ho' SIGWINCH
6380 * The rules when to forget and when to not forget traps
6381 * get really complex and nonsensical.
6383 * Our solution: ONLY bare $(trap) or `trap` is special.
6385 s = skip_whitespace(s);
6386 if (is_prefixed_with(s, "trap")
6387 && skip_whitespace(s + 4)[0] == '\0'
6389 static const char *const argv[] = { NULL, NULL };
6390 builtin_trap((char**)argv);
6391 fflush_all(); /* important */
6396 reset_traps_to_defaults();
6397 parse_and_run_string(s);
6398 _exit(G.last_exitcode);
6400 /* We re-execute after vfork on NOMMU. This makes this script safe:
6401 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6402 * huge=`cat BIG` # was blocking here forever
6405 re_execute_shell(&to_free,
6415 # if ENABLE_HUSH_FAST
6417 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6418 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6419 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6421 enable_restore_tty_pgrp_on_exit();
6426 return remember_FILE(xfdopen_for_read(channel[0]));
6429 /* Return code is exit status of the process that is run. */
6430 static int process_command_subs(o_string *dest, const char *s)
6433 struct in_str pipe_str;
6435 int status, ch, eol_cnt;
6437 fp = generate_stream_from_string(s, &pid);
6439 /* Now send results of command back into original context */
6440 setup_file_in_str(&pipe_str, fp);
6442 while ((ch = i_getch(&pipe_str)) != EOF) {
6448 o_addchr(dest, '\n');
6451 o_addQchr(dest, ch);
6454 debug_printf("done reading from `cmd` pipe, closing it\n");
6455 fclose_and_forget(fp);
6456 /* We need to extract exitcode. Test case
6457 * "true; echo `sleep 1; false` $?"
6459 safe_waitpid(pid, &status, 0);
6460 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6461 return WEXITSTATUS(status);
6463 #endif /* ENABLE_HUSH_TICK */
6466 static void setup_heredoc(struct redir_struct *redir)
6468 struct fd_pair pair;
6471 /* the _body_ of heredoc (misleading field name) */
6472 const char *heredoc = redir->rd_filename;
6479 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6480 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6484 len = strlen(heredoc);
6486 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6488 xmove_fd(pair.rd, redir->rd_fd);
6490 /* Try writing without forking. Newer kernels have
6491 * dynamically growing pipes. Must use non-blocking write! */
6494 written = write(pair.wr, heredoc, len);
6505 ndelay_off(pair.wr);
6507 /* Okay, pipe buffer was not big enough */
6508 /* Note: we must not create a stray child (bastard? :)
6509 * for the unsuspecting parent process. Child creates a grandchild
6510 * and exits before parent execs the process which consumes heredoc
6511 * (that exec happens after we return from this function) */
6518 disable_restore_tty_pgrp_on_exit();
6519 pid = BB_MMU ? xfork() : xvfork();
6523 close(redir->rd_fd); /* read side of the pipe */
6525 full_write(pair.wr, heredoc, len); /* may loop or block */
6528 /* Delegate blocking writes to another process */
6529 xmove_fd(pair.wr, STDOUT_FILENO);
6530 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6534 #if ENABLE_HUSH_FAST
6536 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6538 enable_restore_tty_pgrp_on_exit();
6544 wait(NULL); /* wait till child has died */
6550 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6551 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6554 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6558 if (sq) while (sq[i].orig_fd >= 0) {
6559 /* If we collide with an already moved fd... */
6560 if (fd == sq[i].moved_to) {
6561 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6562 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6563 if (sq[i].moved_to < 0) /* what? */
6567 if (fd == sq[i].orig_fd) {
6568 /* Example: echo Hello >/dev/null 1>&2 */
6569 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6575 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6577 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6578 sq[i].moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6579 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, sq[i].moved_to);
6580 if (sq[i].moved_to < 0 && errno != EBADF)
6582 sq[i+1].orig_fd = -1; /* end marker */
6586 /* fd: redirect wants this fd to be used (e.g. 3>file).
6587 * Move all conflicting internally used fds,
6588 * and remember them so that we can restore them later.
6590 static int save_fds_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6592 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6595 #if ENABLE_HUSH_INTERACTIVE
6596 if (fd != 0 && fd == G.interactive_fd) {
6597 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC, avoid_fd);
6598 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6599 return 1; /* "we closed fd" */
6602 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6603 * (1) Redirect in a forked child. No need to save FILEs' fds,
6604 * we aren't going to use them anymore, ok to trash.
6605 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6606 * but how are we doing to restore them?
6607 * "fileno(fd) = new_fd" can't be done.
6612 /* If this one of script's fds? */
6613 if (save_FILEs_on_redirect(fd, avoid_fd))
6614 return 1; /* yes. "we closed fd" */
6616 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6617 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6618 return 0; /* "we did not close fd" */
6621 static void restore_redirects(struct squirrel *sq)
6626 while (sq[i].orig_fd >= 0) {
6627 if (sq[i].moved_to >= 0) {
6628 /* We simply die on error */
6629 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6630 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6632 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6633 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6634 close(sq[i].orig_fd);
6641 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6643 restore_redirected_FILEs();
6646 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6647 * and stderr if they are redirected. */
6648 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6651 struct redir_struct *redir;
6653 for (redir = prog->redirects; redir; redir = redir->next) {
6654 if (redir->rd_type == REDIRECT_HEREDOC2) {
6655 /* "rd_fd<<HERE" case */
6656 save_fds_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6657 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6659 debug_printf_parse("set heredoc '%s'\n",
6660 redir->rd_filename);
6661 setup_heredoc(redir);
6665 if (redir->rd_dup == REDIRFD_TO_FILE) {
6666 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6668 if (redir->rd_filename == NULL) {
6671 * "cmd >" (no filename)
6672 * "cmd > <file" (2nd redirect starts too early)
6674 die_if_script("syntax error: %s", "invalid redirect");
6677 mode = redir_table[redir->rd_type].mode;
6678 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6679 openfd = open_or_warn(p, mode);
6682 /* Error message from open_or_warn can be lost
6683 * if stderr has been redirected, but bash
6684 * and ash both lose it as well
6685 * (though zsh doesn't!)
6690 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6691 openfd = redir->rd_dup;
6694 if (openfd != redir->rd_fd) {
6695 int closed = save_fds_on_redirect(redir->rd_fd, /*avoid:*/ openfd, sqp);
6696 if (openfd == REDIRFD_CLOSE) {
6697 /* "rd_fd >&-" means "close me" */
6699 /* ^^^ optimization: saving may already
6700 * have closed it. If not... */
6701 close(redir->rd_fd);
6704 xdup2(openfd, redir->rd_fd);
6705 if (redir->rd_dup == REDIRFD_TO_FILE)
6706 /* "rd_fd > FILE" */
6708 /* else: "rd_fd > rd_dup" */
6715 static char *find_in_path(const char *arg)
6718 const char *PATH = get_local_var_value("PATH");
6724 const char *end = strchrnul(PATH, ':');
6725 int sz = end - PATH; /* must be int! */
6729 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6731 /* We have xxx::yyyy in $PATH,
6732 * it means "use current dir" */
6735 if (access(ret, F_OK) == 0)
6748 static const struct built_in_command *find_builtin_helper(const char *name,
6749 const struct built_in_command *x,
6750 const struct built_in_command *end)
6753 if (strcmp(name, x->b_cmd) != 0) {
6757 debug_printf_exec("found builtin '%s'\n", name);
6762 static const struct built_in_command *find_builtin1(const char *name)
6764 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6766 static const struct built_in_command *find_builtin(const char *name)
6768 const struct built_in_command *x = find_builtin1(name);
6771 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6774 #if ENABLE_HUSH_FUNCTIONS
6775 static struct function **find_function_slot(const char *name)
6777 struct function **funcpp = &G.top_func;
6779 if (strcmp(name, (*funcpp)->name) == 0) {
6782 funcpp = &(*funcpp)->next;
6787 static const struct function *find_function(const char *name)
6789 const struct function *funcp = *find_function_slot(name);
6791 debug_printf_exec("found function '%s'\n", name);
6795 /* Note: takes ownership on name ptr */
6796 static struct function *new_function(char *name)
6798 struct function **funcpp = find_function_slot(name);
6799 struct function *funcp = *funcpp;
6801 if (funcp != NULL) {
6802 struct command *cmd = funcp->parent_cmd;
6803 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6805 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6807 /* Note: if !funcp->body, do not free body_as_string!
6808 * This is a special case of "-F name body" function:
6809 * body_as_string was not malloced! */
6811 free_pipe_list(funcp->body);
6813 free(funcp->body_as_string);
6817 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6818 cmd->argv[0] = funcp->name;
6819 cmd->group = funcp->body;
6821 cmd->group_as_string = funcp->body_as_string;
6825 debug_printf_exec("remembering new function '%s'\n", name);
6826 funcp = *funcpp = xzalloc(sizeof(*funcp));
6827 /*funcp->next = NULL;*/
6834 # if ENABLE_HUSH_UNSET
6835 static void unset_func(const char *name)
6837 struct function **funcpp = find_function_slot(name);
6838 struct function *funcp = *funcpp;
6840 if (funcp != NULL) {
6841 debug_printf_exec("freeing function '%s'\n", funcp->name);
6842 *funcpp = funcp->next;
6843 /* funcp is unlinked now, deleting it.
6844 * Note: if !funcp->body, the function was created by
6845 * "-F name body", do not free ->body_as_string
6846 * and ->name as they were not malloced. */
6848 free_pipe_list(funcp->body);
6851 free(funcp->body_as_string);
6860 #define exec_function(to_free, funcp, argv) \
6861 exec_function(funcp, argv)
6863 static void exec_function(char ***to_free,
6864 const struct function *funcp,
6865 char **argv) NORETURN;
6866 static void exec_function(char ***to_free,
6867 const struct function *funcp,
6873 argv[0] = G.global_argv[0];
6874 G.global_argv = argv;
6875 G.global_argc = n = 1 + string_array_len(argv + 1);
6876 /* On MMU, funcp->body is always non-NULL */
6877 n = run_list(funcp->body);
6881 re_execute_shell(to_free,
6882 funcp->body_as_string,
6889 static int run_function(const struct function *funcp, char **argv)
6895 save_and_replace_G_args(&sv, argv);
6897 /* "we are in function, ok to use return" */
6898 sv_flg = G_flag_return_in_progress;
6899 G_flag_return_in_progress = -1;
6900 # if ENABLE_HUSH_LOCAL
6901 G.func_nest_level++;
6904 /* On MMU, funcp->body is always non-NULL */
6907 /* Function defined by -F */
6908 parse_and_run_string(funcp->body_as_string);
6909 rc = G.last_exitcode;
6913 rc = run_list(funcp->body);
6916 # if ENABLE_HUSH_LOCAL
6918 struct variable *var;
6919 struct variable **var_pp;
6921 var_pp = &G.top_var;
6922 while ((var = *var_pp) != NULL) {
6923 if (var->func_nest_level < G.func_nest_level) {
6924 var_pp = &var->next;
6928 if (var->flg_export)
6929 bb_unsetenv(var->varstr);
6930 /* Remove from global list */
6931 *var_pp = var->next;
6937 G.func_nest_level--;
6940 G_flag_return_in_progress = sv_flg;
6942 restore_G_args(&sv, argv);
6946 #endif /* ENABLE_HUSH_FUNCTIONS */
6950 #define exec_builtin(to_free, x, argv) \
6951 exec_builtin(x, argv)
6953 #define exec_builtin(to_free, x, argv) \
6954 exec_builtin(to_free, argv)
6956 static void exec_builtin(char ***to_free,
6957 const struct built_in_command *x,
6958 char **argv) NORETURN;
6959 static void exec_builtin(char ***to_free,
6960 const struct built_in_command *x,
6966 rcode = x->b_function(argv);
6971 /* On NOMMU, we must never block!
6972 * Example: { sleep 99 | read line; } & echo Ok
6974 re_execute_shell(to_free,
6983 static void execvp_or_die(char **argv) NORETURN;
6984 static void execvp_or_die(char **argv)
6987 debug_printf_exec("execing '%s'\n", argv[0]);
6988 /* Don't propagate SIG_IGN to the child */
6989 if (SPECIAL_JOBSTOP_SIGS != 0)
6990 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6991 execvp(argv[0], argv);
6993 if (errno == EACCES) e = 126;
6994 if (errno == ENOENT) e = 127;
6995 bb_perror_msg("can't execute '%s'", argv[0]);
6999 #if ENABLE_HUSH_MODE_X
7000 static void dump_cmd_in_x_mode(char **argv)
7002 if (G_x_mode && argv) {
7003 /* We want to output the line in one write op */
7011 len += strlen(argv[n++]) + 1;
7017 p += sprintf(p, " %s", argv[n++]);
7025 # define dump_cmd_in_x_mode(argv) ((void)0)
7029 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7030 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7031 #define pseudo_exec(nommu_save, command, argv_expanded) \
7032 pseudo_exec(command, argv_expanded)
7035 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7037 * Don't exit() here. If you don't exec, use _exit instead.
7038 * The at_exit handlers apparently confuse the calling process,
7039 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7041 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7042 char **argv, int assignment_cnt,
7043 char **argv_expanded) NORETURN;
7044 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7045 char **argv, int assignment_cnt,
7046 char **argv_expanded)
7050 new_env = expand_assignments(argv, assignment_cnt);
7051 dump_cmd_in_x_mode(new_env);
7053 if (!argv[assignment_cnt]) {
7054 /* Case when we are here: ... | var=val | ...
7055 * (note that we do not exit early, i.e., do not optimize out
7056 * expand_assignments(): think about ... | var=`sleep 1` | ...
7058 free_strings(new_env);
7059 _exit(EXIT_SUCCESS);
7063 set_vars_and_save_old(new_env);
7064 free(new_env); /* optional */
7065 /* we can also destroy set_vars_and_save_old's return value,
7068 nommu_save->new_env = new_env;
7069 nommu_save->old_vars = set_vars_and_save_old(new_env);
7072 if (argv_expanded) {
7073 argv = argv_expanded;
7075 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7077 nommu_save->argv = argv;
7080 dump_cmd_in_x_mode(argv);
7082 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7083 if (strchr(argv[0], '/') != NULL)
7087 /* Check if the command matches any of the builtins.
7088 * Depending on context, this might be redundant. But it's
7089 * easier to waste a few CPU cycles than it is to figure out
7090 * if this is one of those cases.
7093 /* On NOMMU, it is more expensive to re-execute shell
7094 * just in order to run echo or test builtin.
7095 * It's better to skip it here and run corresponding
7096 * non-builtin later. */
7097 const struct built_in_command *x;
7098 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7100 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7103 #if ENABLE_HUSH_FUNCTIONS
7104 /* Check if the command matches any functions */
7106 const struct function *funcp = find_function(argv[0]);
7108 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7113 #if ENABLE_FEATURE_SH_STANDALONE
7114 /* Check if the command matches any busybox applets */
7116 int a = find_applet_by_name(argv[0]);
7118 # if BB_MMU /* see above why on NOMMU it is not allowed */
7119 if (APPLET_IS_NOEXEC(a)) {
7120 /* Do not leak open fds from opened script files etc */
7121 close_all_FILE_list();
7122 debug_printf_exec("running applet '%s'\n", argv[0]);
7123 run_applet_no_and_exit(a, argv[0], argv);
7126 /* Re-exec ourselves */
7127 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7128 /* Don't propagate SIG_IGN to the child */
7129 if (SPECIAL_JOBSTOP_SIGS != 0)
7130 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7131 execv(bb_busybox_exec_path, argv);
7132 /* If they called chroot or otherwise made the binary no longer
7133 * executable, fall through */
7138 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7141 execvp_or_die(argv);
7144 /* Called after [v]fork() in run_pipe
7146 static void pseudo_exec(nommu_save_t *nommu_save,
7147 struct command *command,
7148 char **argv_expanded) NORETURN;
7149 static void pseudo_exec(nommu_save_t *nommu_save,
7150 struct command *command,
7151 char **argv_expanded)
7153 if (command->argv) {
7154 pseudo_exec_argv(nommu_save, command->argv,
7155 command->assignment_cnt, argv_expanded);
7158 if (command->group) {
7159 /* Cases when we are here:
7162 * ... | ( list ) | ...
7163 * ... | { list } | ...
7167 debug_printf_exec("pseudo_exec: run_list\n");
7168 reset_traps_to_defaults();
7169 rcode = run_list(command->group);
7170 /* OK to leak memory by not calling free_pipe_list,
7171 * since this process is about to exit */
7174 re_execute_shell(&nommu_save->argv_from_re_execing,
7175 command->group_as_string,
7182 /* Case when we are here: ... | >file */
7183 debug_printf_exec("pseudo_exec'ed null command\n");
7184 _exit(EXIT_SUCCESS);
7188 static const char *get_cmdtext(struct pipe *pi)
7194 /* This is subtle. ->cmdtext is created only on first backgrounding.
7195 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7196 * On subsequent bg argv is trashed, but we won't use it */
7200 argv = pi->cmds[0].argv;
7202 pi->cmdtext = xzalloc(1);
7207 len += strlen(*argv) + 1;
7211 argv = pi->cmds[0].argv;
7213 p = stpcpy(p, *argv);
7220 static void insert_bg_job(struct pipe *pi)
7222 struct pipe *job, **jobp;
7225 /* Linear search for the ID of the job to use */
7227 for (job = G.job_list; job; job = job->next)
7228 if (job->jobid >= pi->jobid)
7229 pi->jobid = job->jobid + 1;
7231 /* Add job to the list of running jobs */
7233 while ((job = *jobp) != NULL)
7235 job = *jobp = xmalloc(sizeof(*job));
7237 *job = *pi; /* physical copy */
7239 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7240 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7241 for (i = 0; i < pi->num_cmds; i++) {
7242 job->cmds[i].pid = pi->cmds[i].pid;
7243 /* all other fields are not used and stay zero */
7245 job->cmdtext = xstrdup(get_cmdtext(pi));
7247 if (G_interactive_fd)
7248 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7249 G.last_jobid = job->jobid;
7252 static void remove_bg_job(struct pipe *pi)
7254 struct pipe *prev_pipe;
7256 if (pi == G.job_list) {
7257 G.job_list = pi->next;
7259 prev_pipe = G.job_list;
7260 while (prev_pipe->next != pi)
7261 prev_pipe = prev_pipe->next;
7262 prev_pipe->next = pi->next;
7265 G.last_jobid = G.job_list->jobid;
7270 /* Remove a backgrounded job */
7271 static void delete_finished_bg_job(struct pipe *pi)
7278 static int job_exited_or_stopped(struct pipe *pi)
7282 if (pi->alive_cmds != pi->stopped_cmds)
7285 /* All processes in fg pipe have exited or stopped */
7289 rcode = pi->cmds[i].cmd_exitcode;
7290 /* usually last process gives overall exitstatus,
7291 * but with "set -o pipefail", last *failed* process does */
7292 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7295 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7299 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7306 dead = WIFEXITED(status) || WIFSIGNALED(status);
7309 if (WIFSTOPPED(status))
7310 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7311 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7312 if (WIFSIGNALED(status))
7313 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7314 childpid, WTERMSIG(status), WEXITSTATUS(status));
7315 if (WIFEXITED(status))
7316 debug_printf_jobs("pid %d exited, exitcode %d\n",
7317 childpid, WEXITSTATUS(status));
7319 /* Were we asked to wait for a fg pipe? */
7321 i = fg_pipe->num_cmds;
7326 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7327 if (fg_pipe->cmds[i].pid != childpid)
7331 fg_pipe->cmds[i].pid = 0;
7332 fg_pipe->alive_cmds--;
7333 ex = WEXITSTATUS(status);
7334 /* bash prints killer signal's name for *last*
7335 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7336 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7338 if (WIFSIGNALED(status)) {
7339 int sig = WTERMSIG(status);
7340 if (i == fg_pipe->num_cmds-1)
7341 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7342 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7343 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7344 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7345 * Maybe we need to use sig | 128? */
7348 fg_pipe->cmds[i].cmd_exitcode = ex;
7350 fg_pipe->stopped_cmds++;
7352 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7353 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7354 rcode = job_exited_or_stopped(fg_pipe);
7356 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7357 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7358 * and "killall -STOP cat" */
7359 if (G_interactive_fd) {
7361 if (fg_pipe->alive_cmds != 0)
7362 insert_bg_job(fg_pipe);
7366 if (fg_pipe->alive_cmds == 0)
7369 /* There are still running processes in the fg_pipe */
7372 /* It wasn't in fg_pipe, look for process in bg pipes */
7376 /* We were asked to wait for bg or orphaned children */
7377 /* No need to remember exitcode in this case */
7378 for (pi = G.job_list; pi; pi = pi->next) {
7379 for (i = 0; i < pi->num_cmds; i++) {
7380 if (pi->cmds[i].pid == childpid)
7381 goto found_pi_and_prognum;
7384 /* Happens when shell is used as init process (init=/bin/sh) */
7385 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7386 return -1; /* this wasn't a process from fg_pipe */
7388 found_pi_and_prognum:
7391 int rcode = WEXITSTATUS(status);
7392 if (WIFSIGNALED(status))
7393 rcode = 128 + WTERMSIG(status);
7394 pi->cmds[i].cmd_exitcode = rcode;
7395 if (G.last_bg_pid == pi->cmds[i].pid)
7396 G.last_bg_pid_exitcode = rcode;
7397 pi->cmds[i].pid = 0;
7399 if (!pi->alive_cmds) {
7400 if (G_interactive_fd)
7401 printf(JOB_STATUS_FORMAT, pi->jobid,
7402 "Done", pi->cmdtext);
7403 delete_finished_bg_job(pi);
7404 //bash deletes finished jobs from job table only in interactive mode, after "jobs" cmd,
7405 //or if pid of a new process matches one of the old ones
7406 //(see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7407 //Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7414 return -1; /* this wasn't a process from fg_pipe */
7417 /* Check to see if any processes have exited -- if they have,
7418 * figure out why and see if a job has completed.
7420 * If non-NULL fg_pipe: wait for its completion or stop.
7421 * Return its exitcode or zero if stopped.
7423 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7424 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7425 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7426 * or 0 if no children changed status.
7428 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7429 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7430 * or 0 if no children changed status.
7432 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7438 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7440 attributes = WUNTRACED;
7441 if (fg_pipe == NULL)
7442 attributes |= WNOHANG;
7445 #if ENABLE_HUSH_FAST
7446 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7447 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7448 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7449 /* There was neither fork nor SIGCHLD since last waitpid */
7450 /* Avoid doing waitpid syscall if possible */
7451 if (!G.we_have_children) {
7455 if (fg_pipe == NULL) { /* is WNOHANG set? */
7456 /* We have children, but they did not exit
7457 * or stop yet (we saw no SIGCHLD) */
7460 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7464 /* Do we do this right?
7465 * bash-3.00# sleep 20 | false
7467 * [3]+ Stopped sleep 20 | false
7468 * bash-3.00# echo $?
7469 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7470 * [hush 1.14.0: yes we do it right]
7474 #if ENABLE_HUSH_FAST
7476 i = G.count_SIGCHLD;
7478 childpid = waitpid(-1, &status, attributes);
7479 if (childpid <= 0) {
7480 if (childpid && errno != ECHILD)
7481 bb_perror_msg("waitpid");
7482 #if ENABLE_HUSH_FAST
7483 else { /* Until next SIGCHLD, waitpid's are useless */
7484 G.we_have_children = (childpid == 0);
7485 G.handled_SIGCHLD = i;
7486 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7489 /* ECHILD (no children), or 0 (no change in children status) */
7493 rcode = process_wait_result(fg_pipe, childpid, status);
7495 /* fg_pipe exited or stopped */
7498 if (childpid == waitfor_pid) {
7499 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7500 rcode = WEXITSTATUS(status);
7501 if (WIFSIGNALED(status))
7502 rcode = 128 + WTERMSIG(status);
7503 if (WIFSTOPPED(status))
7504 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7505 rcode = 128 + WSTOPSIG(status);
7507 break; /* "wait PID" called us, give it exitcode+1 */
7509 /* This wasn't one of our processes, or */
7510 /* fg_pipe still has running processes, do waitpid again */
7511 } /* while (waitpid succeeds)... */
7517 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7520 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7521 if (G_saved_tty_pgrp) {
7522 /* Job finished, move the shell to the foreground */
7523 p = getpgrp(); /* our process group id */
7524 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7525 tcsetpgrp(G_interactive_fd, p);
7531 /* Start all the jobs, but don't wait for anything to finish.
7534 * Return code is normally -1, when the caller has to wait for children
7535 * to finish to determine the exit status of the pipe. If the pipe
7536 * is a simple builtin command, however, the action is done by the
7537 * time run_pipe returns, and the exit code is provided as the
7540 * Returns -1 only if started some children. IOW: we have to
7541 * mask out retvals of builtins etc with 0xff!
7543 * The only case when we do not need to [v]fork is when the pipe
7544 * is single, non-backgrounded, non-subshell command. Examples:
7545 * cmd ; ... { list } ; ...
7546 * cmd && ... { list } && ...
7547 * cmd || ... { list } || ...
7548 * If it is, then we can run cmd as a builtin, NOFORK,
7549 * or (if SH_STANDALONE) an applet, and we can run the { list }
7550 * with run_list. If it isn't one of these, we fork and exec cmd.
7552 * Cases when we must fork:
7553 * non-single: cmd | cmd
7554 * backgrounded: cmd & { list } &
7555 * subshell: ( list ) [&]
7557 #if !ENABLE_HUSH_MODE_X
7558 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7559 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7561 static int redirect_and_varexp_helper(char ***new_env_p,
7562 struct variable **old_vars_p,
7563 struct command *command,
7564 struct squirrel **sqp,
7565 char **argv_expanded)
7567 /* setup_redirects acts on file descriptors, not FILEs.
7568 * This is perfect for work that comes after exec().
7569 * Is it really safe for inline use? Experimentally,
7570 * things seem to work. */
7571 int rcode = setup_redirects(command, sqp);
7573 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7574 *new_env_p = new_env;
7575 dump_cmd_in_x_mode(new_env);
7576 dump_cmd_in_x_mode(argv_expanded);
7578 *old_vars_p = set_vars_and_save_old(new_env);
7582 static NOINLINE int run_pipe(struct pipe *pi)
7584 static const char *const null_ptr = NULL;
7588 struct command *command;
7589 char **argv_expanded;
7591 struct squirrel *squirrel = NULL;
7594 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7597 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7598 * Result should be 3 lines: q w e, qwe, q w e
7600 G.ifs = get_local_var_value("IFS");
7604 IF_HUSH_JOB(pi->pgrp = -1;)
7605 pi->stopped_cmds = 0;
7606 command = &pi->cmds[0];
7607 argv_expanded = NULL;
7609 if (pi->num_cmds != 1
7610 || pi->followup == PIPE_BG
7611 || command->cmd_type == CMD_SUBSHELL
7618 debug_printf_exec(": group:%p argv:'%s'\n",
7619 command->group, command->argv ? command->argv[0] : "NONE");
7621 if (command->group) {
7622 #if ENABLE_HUSH_FUNCTIONS
7623 if (command->cmd_type == CMD_FUNCDEF) {
7624 /* "executing" func () { list } */
7625 struct function *funcp;
7627 funcp = new_function(command->argv[0]);
7628 /* funcp->name is already set to argv[0] */
7629 funcp->body = command->group;
7631 funcp->body_as_string = command->group_as_string;
7632 command->group_as_string = NULL;
7634 command->group = NULL;
7635 command->argv[0] = NULL;
7636 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7637 funcp->parent_cmd = command;
7638 command->child_func = funcp;
7640 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7642 return EXIT_SUCCESS;
7646 debug_printf("non-subshell group\n");
7647 rcode = 1; /* exitcode if redir failed */
7648 if (setup_redirects(command, &squirrel) == 0) {
7649 debug_printf_exec(": run_list\n");
7650 rcode = run_list(command->group) & 0xff;
7652 restore_redirects(squirrel);
7653 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7655 debug_printf_exec("run_pipe: return %d\n", rcode);
7659 argv = command->argv ? command->argv : (char **) &null_ptr;
7661 const struct built_in_command *x;
7662 #if ENABLE_HUSH_FUNCTIONS
7663 const struct function *funcp;
7667 char **new_env = NULL;
7668 struct variable *old_vars = NULL;
7670 if (argv[command->assignment_cnt] == NULL) {
7671 /* Assignments, but no command */
7672 /* Ensure redirects take effect (that is, create files).
7673 * Try "a=t >file" */
7674 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7675 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
7676 /* Set shell variables */
7680 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7681 /* Do we need to flag set_local_var() errors?
7682 * "assignment to readonly var" and "putenv error"
7687 /* Redirect error sets $? to 1. Otherwise,
7688 * if evaluating assignment value set $?, retain it.
7689 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7691 rcode = G.last_exitcode;
7692 /* Exit, _skipping_ variable restoring code: */
7693 goto clean_up_and_ret0;
7695 #else /* Older, bigger, but more correct code */
7697 rcode = setup_redirects(command, &squirrel);
7698 restore_redirects(squirrel);
7699 /* Set shell variables */
7701 bb_putchar_stderr('+');
7703 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7705 fprintf(stderr, " %s", p);
7706 debug_printf_exec("set shell var:'%s'->'%s'\n",
7708 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7709 /* Do we need to flag set_local_var() errors?
7710 * "assignment to readonly var" and "putenv error"
7715 bb_putchar_stderr('\n');
7716 /* Redirect error sets $? to 1. Otherwise,
7717 * if evaluating assignment value set $?, retain it.
7718 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7720 rcode = G.last_exitcode;
7721 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7723 debug_printf_exec("run_pipe: return %d\n", rcode);
7728 /* Expand the rest into (possibly) many strings each */
7730 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7731 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7735 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7738 /* if someone gives us an empty string: `cmd with empty output` */
7739 if (!argv_expanded[0]) {
7740 free(argv_expanded);
7742 return G.last_exitcode;
7745 x = find_builtin(argv_expanded[0]);
7746 #if ENABLE_HUSH_FUNCTIONS
7749 funcp = find_function(argv_expanded[0]);
7753 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7754 debug_printf("exec with redirects only\n");
7755 rcode = setup_redirects(command, NULL);
7756 /* rcode=1 can be if redir file can't be opened */
7757 goto clean_up_and_ret1;
7760 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
7763 debug_printf_exec(": builtin '%s' '%s'...\n",
7764 x->b_cmd, argv_expanded[1]);
7766 rcode = x->b_function(argv_expanded) & 0xff;
7769 #if ENABLE_HUSH_FUNCTIONS
7771 # if ENABLE_HUSH_LOCAL
7772 struct variable **sv;
7773 sv = G.shadowed_vars_pp;
7774 G.shadowed_vars_pp = &old_vars;
7776 debug_printf_exec(": function '%s' '%s'...\n",
7777 funcp->name, argv_expanded[1]);
7778 rcode = run_function(funcp, argv_expanded) & 0xff;
7779 # if ENABLE_HUSH_LOCAL
7780 G.shadowed_vars_pp = sv;
7786 unset_vars(new_env);
7788 /* clean_up_and_ret0: */
7789 restore_redirects(squirrel);
7791 free(argv_expanded);
7792 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7794 debug_printf_exec("run_pipe return %d\n", rcode);
7798 if (ENABLE_FEATURE_SH_NOFORK) {
7799 int n = find_applet_by_name(argv_expanded[0]);
7800 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7801 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
7803 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7804 argv_expanded[0], argv_expanded[1]);
7805 rcode = run_nofork_applet(n, argv_expanded);
7807 goto clean_up_and_ret;
7810 /* It is neither builtin nor applet. We must fork. */
7814 /* NB: argv_expanded may already be created, and that
7815 * might include `cmd` runs! Do not rerun it! We *must*
7816 * use argv_expanded if it's non-NULL */
7818 /* Going to fork a child per each pipe member */
7823 while (cmd_no < pi->num_cmds) {
7824 struct fd_pair pipefds;
7826 volatile nommu_save_t nommu_save;
7827 nommu_save.new_env = NULL;
7828 nommu_save.old_vars = NULL;
7829 nommu_save.argv = NULL;
7830 nommu_save.argv_from_re_execing = NULL;
7832 command = &pi->cmds[cmd_no];
7834 if (command->argv) {
7835 debug_printf_exec(": pipe member '%s' '%s'...\n",
7836 command->argv[0], command->argv[1]);
7838 debug_printf_exec(": pipe member with no argv\n");
7841 /* pipes are inserted between pairs of commands */
7844 if (cmd_no < pi->num_cmds)
7845 xpiped_pair(pipefds);
7847 command->pid = BB_MMU ? fork() : vfork();
7848 if (!command->pid) { /* child */
7850 disable_restore_tty_pgrp_on_exit();
7851 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7853 /* Every child adds itself to new process group
7854 * with pgid == pid_of_first_child_in_pipe */
7855 if (G.run_list_level == 1 && G_interactive_fd) {
7858 if (pgrp < 0) /* true for 1st process only */
7860 if (setpgid(0, pgrp) == 0
7861 && pi->followup != PIPE_BG
7862 && G_saved_tty_pgrp /* we have ctty */
7864 /* We do it in *every* child, not just first,
7866 tcsetpgrp(G_interactive_fd, pgrp);
7870 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7871 /* 1st cmd in backgrounded pipe
7872 * should have its stdin /dev/null'ed */
7874 if (open(bb_dev_null, O_RDONLY))
7875 xopen("/", O_RDONLY);
7877 xmove_fd(next_infd, 0);
7879 xmove_fd(pipefds.wr, 1);
7882 /* Like bash, explicit redirects override pipes,
7883 * and the pipe fd (fd#1) is available for dup'ing:
7884 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7885 * of cmd1 goes into pipe.
7887 if (setup_redirects(command, NULL)) {
7888 /* Happens when redir file can't be opened:
7889 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7891 * hush: can't open '/qwe/rty': No such file or directory
7893 * (echo BAR is not executed, it hits _exit(1) below)
7898 /* Stores to nommu_save list of env vars putenv'ed
7899 * (NOMMU, on MMU we don't need that) */
7900 /* cast away volatility... */
7901 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7902 /* pseudo_exec() does not return */
7905 /* parent or error */
7906 #if ENABLE_HUSH_FAST
7908 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7910 enable_restore_tty_pgrp_on_exit();
7912 /* Clean up after vforked child */
7913 free(nommu_save.argv);
7914 free(nommu_save.argv_from_re_execing);
7915 unset_vars(nommu_save.new_env);
7916 add_vars(nommu_save.old_vars);
7918 free(argv_expanded);
7919 argv_expanded = NULL;
7920 if (command->pid < 0) { /* [v]fork failed */
7921 /* Clearly indicate, was it fork or vfork */
7922 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7926 /* Second and next children need to know pid of first one */
7928 pi->pgrp = command->pid;
7934 if (cmd_no < pi->num_cmds)
7936 /* Pass read (output) pipe end to next iteration */
7937 next_infd = pipefds.rd;
7940 if (!pi->alive_cmds) {
7942 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7947 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7951 /* NB: called by pseudo_exec, and therefore must not modify any
7952 * global data until exec/_exit (we can be a child after vfork!) */
7953 static int run_list(struct pipe *pi)
7955 #if ENABLE_HUSH_CASE
7956 char *case_word = NULL;
7958 #if ENABLE_HUSH_LOOPS
7959 struct pipe *loop_top = NULL;
7960 char **for_lcur = NULL;
7961 char **for_list = NULL;
7963 smallint last_followup;
7965 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7966 smalluint cond_code = 0;
7968 enum { cond_code = 0 };
7971 smallint rword; /* RES_foo */
7972 smallint last_rword; /* ditto */
7975 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7978 #if ENABLE_HUSH_LOOPS
7979 /* Check syntax for "for" */
7982 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7983 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7985 /* current word is FOR or IN (BOLD in comments below) */
7986 if (cpipe->next == NULL) {
7987 syntax_error("malformed for");
7989 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7992 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7993 if (cpipe->next->res_word == RES_DO)
7995 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7996 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7997 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7999 syntax_error("malformed for");
8001 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8008 /* Past this point, all code paths should jump to ret: label
8009 * in order to return, no direct "return" statements please.
8010 * This helps to ensure that no memory is leaked. */
8018 last_rword = RES_XXXX;
8020 last_followup = PIPE_SEQ;
8021 rcode = G.last_exitcode;
8023 /* Go through list of pipes, (maybe) executing them. */
8024 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8029 if (G_flag_return_in_progress == 1)
8032 IF_HAS_KEYWORDS(rword = pi->res_word;)
8033 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8034 rword, cond_code, last_rword);
8035 #if ENABLE_HUSH_LOOPS
8036 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8037 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8039 /* start of a loop: remember where loop starts */
8044 /* Still in the same "if...", "then..." or "do..." branch? */
8045 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8046 if ((rcode == 0 && last_followup == PIPE_OR)
8047 || (rcode != 0 && last_followup == PIPE_AND)
8049 /* It is "<true> || CMD" or "<false> && CMD"
8050 * and we should not execute CMD */
8051 debug_printf_exec("skipped cmd because of || or &&\n");
8052 last_followup = pi->followup;
8053 goto dont_check_jobs_but_continue;
8056 last_followup = pi->followup;
8057 IF_HAS_KEYWORDS(last_rword = rword;)
8060 if (rword == RES_THEN) {
8061 /* if false; then ... fi has exitcode 0! */
8062 G.last_exitcode = rcode = EXIT_SUCCESS;
8063 /* "if <false> THEN cmd": skip cmd */
8067 if (rword == RES_ELSE || rword == RES_ELIF) {
8068 /* "if <true> then ... ELSE/ELIF cmd":
8069 * skip cmd and all following ones */
8074 #if ENABLE_HUSH_LOOPS
8075 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8077 /* first loop through for */
8079 static const char encoded_dollar_at[] ALIGN1 = {
8080 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8081 }; /* encoded representation of "$@" */
8082 static const char *const encoded_dollar_at_argv[] = {
8083 encoded_dollar_at, NULL
8084 }; /* argv list with one element: "$@" */
8087 vals = (char**)encoded_dollar_at_argv;
8088 if (pi->next->res_word == RES_IN) {
8089 /* if no variable values after "in" we skip "for" */
8090 if (!pi->next->cmds[0].argv) {
8091 G.last_exitcode = rcode = EXIT_SUCCESS;
8092 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8095 vals = pi->next->cmds[0].argv;
8096 } /* else: "for var; do..." -> assume "$@" list */
8097 /* create list of variable values */
8098 debug_print_strings("for_list made from", vals);
8099 for_list = expand_strvec_to_strvec(vals);
8100 for_lcur = for_list;
8101 debug_print_strings("for_list", for_list);
8104 /* "for" loop is over, clean up */
8110 /* Insert next value from for_lcur */
8111 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8112 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
8115 if (rword == RES_IN) {
8116 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8118 if (rword == RES_DONE) {
8119 continue; /* "done" has no cmds too */
8122 #if ENABLE_HUSH_CASE
8123 if (rword == RES_CASE) {
8124 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8125 case_word = expand_strvec_to_string(pi->cmds->argv);
8126 unbackslash(case_word);
8129 if (rword == RES_MATCH) {
8132 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8133 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8135 /* all prev words didn't match, does this one match? */
8136 argv = pi->cmds->argv;
8138 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8139 /* TODO: which FNM_xxx flags to use? */
8140 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8141 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8143 if (cond_code == 0) { /* match! we will execute this branch */
8145 case_word = NULL; /* make future "word)" stop */
8152 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8153 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8155 continue; /* not matched yet, skip this pipe */
8157 if (rword == RES_ESAC) {
8158 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8160 /* "case" did not match anything: still set $? (to 0) */
8161 G.last_exitcode = rcode = EXIT_SUCCESS;
8165 /* Just pressing <enter> in shell should check for jobs.
8166 * OTOH, in non-interactive shell this is useless
8167 * and only leads to extra job checks */
8168 if (pi->num_cmds == 0) {
8169 if (G_interactive_fd)
8170 goto check_jobs_and_continue;
8174 /* After analyzing all keywords and conditions, we decided
8175 * to execute this pipe. NB: have to do checkjobs(NULL)
8176 * after run_pipe to collect any background children,
8177 * even if list execution is to be stopped. */
8178 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8179 #if ENABLE_HUSH_LOOPS
8180 G.flag_break_continue = 0;
8182 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8184 /* We ran a builtin, function, or group.
8185 * rcode is already known
8186 * and we don't need to wait for anything. */
8187 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8188 G.last_exitcode = rcode;
8189 check_and_run_traps();
8190 #if ENABLE_HUSH_LOOPS
8191 /* Was it "break" or "continue"? */
8192 if (G.flag_break_continue) {
8193 smallint fbc = G.flag_break_continue;
8194 /* We might fall into outer *loop*,
8195 * don't want to break it too */
8197 G.depth_break_continue--;
8198 if (G.depth_break_continue == 0)
8199 G.flag_break_continue = 0;
8200 /* else: e.g. "continue 2" should *break* once, *then* continue */
8201 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8202 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8203 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8206 /* "continue": simulate end of loop */
8211 if (G_flag_return_in_progress == 1) {
8212 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8215 } else if (pi->followup == PIPE_BG) {
8216 /* What does bash do with attempts to background builtins? */
8217 /* even bash 3.2 doesn't do that well with nested bg:
8218 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8219 * I'm NOT treating inner &'s as jobs */
8221 if (G.run_list_level == 1)
8224 /* Last command's pid goes to $! */
8225 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8226 G.last_bg_pid_exitcode = 0;
8227 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8228 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
8229 rcode = EXIT_SUCCESS;
8233 if (G.run_list_level == 1 && G_interactive_fd) {
8234 /* Waits for completion, then fg's main shell */
8235 rcode = checkjobs_and_fg_shell(pi);
8236 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8240 /* This one just waits for completion */
8241 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8242 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8244 G.last_exitcode = rcode;
8245 check_and_run_traps();
8248 /* Analyze how result affects subsequent commands */
8250 if (rword == RES_IF || rword == RES_ELIF)
8253 check_jobs_and_continue:
8254 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8255 dont_check_jobs_but_continue: ;
8256 #if ENABLE_HUSH_LOOPS
8257 /* Beware of "while false; true; do ..."! */
8259 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8260 /* check for RES_DONE is needed for "while ...; do \n done" case */
8262 if (rword == RES_WHILE) {
8264 /* "while false; do...done" - exitcode 0 */
8265 G.last_exitcode = rcode = EXIT_SUCCESS;
8266 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8270 if (rword == RES_UNTIL) {
8272 debug_printf_exec(": until expr is true: breaking\n");
8283 #if ENABLE_HUSH_LOOPS
8288 #if ENABLE_HUSH_CASE
8292 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8296 /* Select which version we will use */
8297 static int run_and_free_list(struct pipe *pi)
8300 debug_printf_exec("run_and_free_list entered\n");
8301 if (!G.o_opt[OPT_O_NOEXEC]) {
8302 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8303 rcode = run_list(pi);
8305 /* free_pipe_list has the side effect of clearing memory.
8306 * In the long run that function can be merged with run_list,
8307 * but doing that now would hobble the debugging effort. */
8309 debug_printf_exec("run_and_free_list return %d\n", rcode);
8314 static void install_sighandlers(unsigned mask)
8316 sighandler_t old_handler;
8318 while ((mask >>= 1) != 0) {
8322 old_handler = install_sighandler(sig, pick_sighandler(sig));
8323 /* POSIX allows shell to re-enable SIGCHLD
8324 * even if it was SIG_IGN on entry.
8325 * Therefore we skip IGN check for it:
8329 if (old_handler == SIG_IGN) {
8330 /* oops... restore back to IGN, and record this fact */
8331 install_sighandler(sig, old_handler);
8332 #if ENABLE_HUSH_TRAP
8334 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8336 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8342 /* Called a few times only (or even once if "sh -c") */
8343 static void install_special_sighandlers(void)
8347 /* Which signals are shell-special? */
8348 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8349 if (G_interactive_fd) {
8350 mask |= SPECIAL_INTERACTIVE_SIGS;
8351 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8352 mask |= SPECIAL_JOBSTOP_SIGS;
8354 /* Careful, do not re-install handlers we already installed */
8355 if (G.special_sig_mask != mask) {
8356 unsigned diff = mask & ~G.special_sig_mask;
8357 G.special_sig_mask = mask;
8358 install_sighandlers(diff);
8364 /* Set handlers to restore tty pgrp and exit */
8365 static void install_fatal_sighandlers(void)
8369 /* We will restore tty pgrp on these signals */
8371 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8372 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8373 + (1 << SIGBUS ) * HUSH_DEBUG
8374 + (1 << SIGSEGV) * HUSH_DEBUG
8375 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8377 /* bash 3.2 seems to handle these just like 'fatal' ones */
8380 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8381 * if we aren't interactive... but in this case
8382 * we never want to restore pgrp on exit, and this fn is not called
8384 /*+ (1 << SIGHUP )*/
8385 /*+ (1 << SIGTERM)*/
8386 /*+ (1 << SIGINT )*/
8388 G_fatal_sig_mask = mask;
8390 install_sighandlers(mask);
8394 static int set_mode(int state, char mode, const char *o_opt)
8399 G.o_opt[OPT_O_NOEXEC] = state;
8402 IF_HUSH_MODE_X(G_x_mode = state;)
8406 /* "set -+o" without parameter.
8407 * in bash, set -o produces this output:
8411 * We always use the second form.
8413 const char *p = o_opt_strings;
8416 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8422 idx = index_in_strings(o_opt_strings, o_opt);
8424 G.o_opt[idx] = state;
8428 return EXIT_FAILURE;
8430 return EXIT_SUCCESS;
8433 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8434 int hush_main(int argc, char **argv)
8437 OPT_login = (1 << 0),
8441 unsigned builtin_argc;
8443 struct variable *cur_var;
8444 struct variable *shell_ver;
8447 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8448 G.last_exitcode = EXIT_SUCCESS;
8450 #if ENABLE_HUSH_FAST
8451 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8454 G.argv0_for_re_execing = argv[0];
8456 /* Deal with HUSH_VERSION */
8457 shell_ver = xzalloc(sizeof(*shell_ver));
8458 shell_ver->flg_export = 1;
8459 shell_ver->flg_read_only = 1;
8460 /* Code which handles ${var<op>...} needs writable values for all variables,
8461 * therefore we xstrdup: */
8462 shell_ver->varstr = xstrdup(hush_version_str);
8463 /* Create shell local variables from the values
8464 * currently living in the environment */
8465 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8466 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8467 G.top_var = shell_ver;
8468 cur_var = G.top_var;
8471 char *value = strchr(*e, '=');
8472 if (value) { /* paranoia */
8473 cur_var->next = xzalloc(sizeof(*cur_var));
8474 cur_var = cur_var->next;
8475 cur_var->varstr = *e;
8476 cur_var->max_len = strlen(*e);
8477 cur_var->flg_export = 1;
8481 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8482 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8483 putenv(shell_ver->varstr);
8486 set_pwd_var(/*exp:*/ 1);
8488 #if BASH_HOSTNAME_VAR
8489 /* Set (but not export) HOSTNAME unless already set */
8490 if (!get_local_var_value("HOSTNAME")) {
8493 set_local_var_from_halves("HOSTNAME", uts.nodename);
8495 /* bash also exports SHLVL and _,
8496 * and sets (but doesn't export) the following variables:
8498 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8499 * BASH_VERSION='3.2.0(1)-release'
8501 * MACHTYPE=i386-pc-linux-gnu
8503 * PPID=<NNNNN> - we also do it elsewhere
8514 * PIPESTATUS=([0]="0")
8515 * HISTFILE=/<xxx>/.bash_history
8519 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8521 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8532 #if ENABLE_FEATURE_EDITING
8533 G.line_input_state = new_line_input_t(FOR_SHELL);
8536 /* Initialize some more globals to non-zero values */
8537 cmdedit_update_prompt();
8539 die_func = restore_ttypgrp_and__exit;
8541 /* Shell is non-interactive at first. We need to call
8542 * install_special_sighandlers() if we are going to execute "sh <script>",
8543 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8544 * If we later decide that we are interactive, we run install_special_sighandlers()
8545 * in order to intercept (more) signals.
8549 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8550 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8553 opt = getopt(argc, argv, "+c:xinsl"
8556 # if ENABLE_HUSH_FUNCTIONS
8566 * sh ... -c 'script'
8567 * sh ... -c 'script' ARG0 [ARG1...]
8568 * On NOMMU, if builtin_argc != 0,
8569 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8570 * "" needs to be replaced with NULL
8571 * and BARGV vector fed to builtin function.
8572 * Note: the form without ARG0 never happens:
8573 * sh ... -c 'builtin' BARGV... ""
8576 G.root_pid = getpid();
8577 G.root_ppid = getppid();
8579 G.global_argv = argv + optind;
8580 G.global_argc = argc - optind;
8582 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8583 const struct built_in_command *x;
8585 install_special_sighandlers();
8586 x = find_builtin(optarg);
8587 if (x) { /* paranoia */
8588 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8589 G.global_argv += builtin_argc;
8590 G.global_argv[-1] = NULL; /* replace "" */
8592 G.last_exitcode = x->b_function(argv + optind - 1);
8596 if (!G.global_argv[0]) {
8597 /* -c 'script' (no params): prevent empty $0 */
8598 G.global_argv--; /* points to argv[i] of 'script' */
8599 G.global_argv[0] = argv[0];
8601 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8602 install_special_sighandlers();
8603 parse_and_run_string(optarg);
8606 /* Well, we cannot just declare interactiveness,
8607 * we have to have some stuff (ctty, etc) */
8608 /* G_interactive_fd++; */
8611 /* "-s" means "read from stdin", but this is how we always
8612 * operate, so simply do nothing here. */
8618 case '<': /* "big heredoc" support */
8619 full_write1_str(optarg);
8622 unsigned long long empty_trap_mask;
8624 G.root_pid = bb_strtou(optarg, &optarg, 16);
8626 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8628 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8630 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8632 builtin_argc = bb_strtou(optarg, &optarg, 16);
8634 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8635 if (empty_trap_mask != 0) {
8636 IF_HUSH_TRAP(int sig;)
8637 install_special_sighandlers();
8638 # if ENABLE_HUSH_TRAP
8639 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8640 for (sig = 1; sig < NSIG; sig++) {
8641 if (empty_trap_mask & (1LL << sig)) {
8642 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8643 install_sighandler(sig, SIG_IGN);
8648 # if ENABLE_HUSH_LOOPS
8650 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8656 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8658 # if ENABLE_HUSH_FUNCTIONS
8660 struct function *funcp = new_function(optarg);
8661 /* funcp->name is already set to optarg */
8662 /* funcp->body is set to NULL. It's a special case. */
8663 funcp->body_as_string = argv[optind];
8671 if (set_mode(1, opt, NULL) == 0) /* no error */
8675 fprintf(stderr, "Usage: sh [FILE]...\n"
8676 " or: sh -c command [args]...\n\n");
8682 } /* option parsing loop */
8684 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8685 G.global_argc = argc - (optind - 1);
8686 G.global_argv = argv + (optind - 1);
8687 G.global_argv[0] = argv[0];
8690 G.root_pid = getpid();
8691 G.root_ppid = getppid();
8694 /* If we are login shell... */
8695 if (flags & OPT_login) {
8697 debug_printf("sourcing /etc/profile\n");
8698 input = fopen_for_read("/etc/profile");
8699 if (input != NULL) {
8700 remember_FILE(input);
8701 install_special_sighandlers();
8702 parse_and_run_file(input);
8703 fclose_and_forget(input);
8705 /* bash: after sourcing /etc/profile,
8706 * tries to source (in the given order):
8707 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8708 * stopping on first found. --noprofile turns this off.
8709 * bash also sources ~/.bash_logout on exit.
8710 * If called as sh, skips .bash_XXX files.
8714 if (G.global_argv[1]) {
8717 * "bash <script>" (which is never interactive (unless -i?))
8718 * sources $BASH_ENV here (without scanning $PATH).
8719 * If called as sh, does the same but with $ENV.
8720 * Also NB, per POSIX, $ENV should undergo parameter expansion.
8724 debug_printf("running script '%s'\n", G.global_argv[0]);
8725 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
8726 input = xfopen_for_read(G.global_argv[0]);
8727 xfunc_error_retval = 1;
8728 remember_FILE(input);
8729 install_special_sighandlers();
8730 parse_and_run_file(input);
8731 #if ENABLE_FEATURE_CLEAN_UP
8732 fclose_and_forget(input);
8737 /* Up to here, shell was non-interactive. Now it may become one.
8738 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8741 /* A shell is interactive if the '-i' flag was given,
8742 * or if all of the following conditions are met:
8744 * no arguments remaining or the -s flag given
8745 * standard input is a terminal
8746 * standard output is a terminal
8747 * Refer to Posix.2, the description of the 'sh' utility.
8750 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8751 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8752 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8753 if (G_saved_tty_pgrp < 0)
8754 G_saved_tty_pgrp = 0;
8756 /* try to dup stdin to high fd#, >= 255 */
8757 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
8758 if (G_interactive_fd < 0) {
8759 /* try to dup to any fd */
8760 G_interactive_fd = dup(STDIN_FILENO);
8761 if (G_interactive_fd < 0) {
8763 G_interactive_fd = 0;
8764 G_saved_tty_pgrp = 0;
8767 // TODO: track & disallow any attempts of user
8768 // to (inadvertently) close/redirect G_interactive_fd
8770 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8771 if (G_interactive_fd) {
8772 close_on_exec_on(G_interactive_fd);
8774 if (G_saved_tty_pgrp) {
8775 /* If we were run as 'hush &', sleep until we are
8776 * in the foreground (tty pgrp == our pgrp).
8777 * If we get started under a job aware app (like bash),
8778 * make sure we are now in charge so we don't fight over
8779 * who gets the foreground */
8781 pid_t shell_pgrp = getpgrp();
8782 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8783 if (G_saved_tty_pgrp == shell_pgrp)
8785 /* send TTIN to ourself (should stop us) */
8786 kill(- shell_pgrp, SIGTTIN);
8790 /* Install more signal handlers */
8791 install_special_sighandlers();
8793 if (G_saved_tty_pgrp) {
8794 /* Set other signals to restore saved_tty_pgrp */
8795 install_fatal_sighandlers();
8796 /* Put ourselves in our own process group
8797 * (bash, too, does this only if ctty is available) */
8798 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8799 /* Grab control of the terminal */
8800 tcsetpgrp(G_interactive_fd, getpid());
8802 enable_restore_tty_pgrp_on_exit();
8804 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8806 const char *hp = get_local_var_value("HISTFILE");
8808 hp = get_local_var_value("HOME");
8810 hp = concat_path_file(hp, ".hush_history");
8815 G.line_input_state->hist_file = hp;
8816 //set_local_var(xasprintf("HISTFILE=%s", ...));
8818 # if ENABLE_FEATURE_SH_HISTFILESIZE
8819 hp = get_local_var_value("HISTFILESIZE");
8820 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8825 install_special_sighandlers();
8827 #elif ENABLE_HUSH_INTERACTIVE
8828 /* No job control compiled in, only prompt/line editing */
8829 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8830 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
8831 if (G_interactive_fd < 0) {
8832 /* try to dup to any fd */
8833 G_interactive_fd = dup(STDIN_FILENO);
8834 if (G_interactive_fd < 0)
8836 G_interactive_fd = 0;
8839 if (G_interactive_fd) {
8840 close_on_exec_on(G_interactive_fd);
8842 install_special_sighandlers();
8844 /* We have interactiveness code disabled */
8845 install_special_sighandlers();
8848 * if interactive but not a login shell, sources ~/.bashrc
8849 * (--norc turns this off, --rcfile <file> overrides)
8852 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8853 /* note: ash and hush share this string */
8854 printf("\n\n%s %s\n"
8855 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8858 "hush - the humble shell"
8862 parse_and_run_file(stdin);
8865 hush_exit(G.last_exitcode);
8872 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8877 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
8878 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8880 int argc = string_array_len(argv);
8881 return applet_main_func(argc, argv);
8884 #if ENABLE_HUSH_TEST || BASH_TEST2
8885 static int FAST_FUNC builtin_test(char **argv)
8887 return run_applet_main(argv, test_main);
8890 #if ENABLE_HUSH_ECHO
8891 static int FAST_FUNC builtin_echo(char **argv)
8893 return run_applet_main(argv, echo_main);
8896 #if ENABLE_HUSH_PRINTF
8897 static int FAST_FUNC builtin_printf(char **argv)
8899 return run_applet_main(argv, printf_main);
8903 #if ENABLE_HUSH_HELP
8904 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8906 const struct built_in_command *x;
8909 "Built-in commands:\n"
8910 "------------------\n");
8911 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8913 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8915 return EXIT_SUCCESS;
8919 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
8920 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8922 show_history(G.line_input_state);
8923 return EXIT_SUCCESS;
8927 static char **skip_dash_dash(char **argv)
8930 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8935 static int FAST_FUNC builtin_cd(char **argv)
8939 argv = skip_dash_dash(argv);
8941 if (newdir == NULL) {
8942 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8943 * bash says "bash: cd: HOME not set" and does nothing
8946 const char *home = get_local_var_value("HOME");
8947 newdir = home ? home : "/";
8949 if (chdir(newdir)) {
8950 /* Mimic bash message exactly */
8951 bb_perror_msg("cd: %s", newdir);
8952 return EXIT_FAILURE;
8954 /* Read current dir (get_cwd(1) is inside) and set PWD.
8955 * Note: do not enforce exporting. If PWD was unset or unexported,
8956 * set it again, but do not export. bash does the same.
8958 set_pwd_var(/*exp:*/ 0);
8959 return EXIT_SUCCESS;
8962 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8965 return EXIT_SUCCESS;
8968 static int FAST_FUNC builtin_eval(char **argv)
8970 int rcode = EXIT_SUCCESS;
8972 argv = skip_dash_dash(argv);
8974 char *str = expand_strvec_to_string(argv);
8976 * eval "echo Hi; done" ("done" is syntax error):
8977 * "echo Hi" will not execute too.
8979 parse_and_run_string(str);
8981 rcode = G.last_exitcode;
8986 static int FAST_FUNC builtin_exec(char **argv)
8988 argv = skip_dash_dash(argv);
8989 if (argv[0] == NULL)
8990 return EXIT_SUCCESS; /* bash does this */
8992 /* Careful: we can end up here after [v]fork. Do not restore
8993 * tty pgrp then, only top-level shell process does that */
8994 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8995 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8997 /* TODO: if exec fails, bash does NOT exit! We do.
8998 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8999 * and tcsetpgrp, and this is inherently racy.
9001 execvp_or_die(argv);
9004 static int FAST_FUNC builtin_exit(char **argv)
9006 debug_printf_exec("%s()\n", __func__);
9008 /* interactive bash:
9009 * # trap "echo EEE" EXIT
9012 * There are stopped jobs.
9013 * (if there are _stopped_ jobs, running ones don't count)
9016 * EEE (then bash exits)
9018 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9021 /* note: EXIT trap is run by hush_exit */
9022 argv = skip_dash_dash(argv);
9023 if (argv[0] == NULL)
9024 hush_exit(G.last_exitcode);
9025 /* mimic bash: exit 123abc == exit 255 + error msg */
9026 xfunc_error_retval = 255;
9027 /* bash: exit -2 == exit 254, no error msg */
9028 hush_exit(xatoi(argv[0]) & 0xff);
9031 #if ENABLE_HUSH_TYPE
9032 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9033 static int FAST_FUNC builtin_type(char **argv)
9035 int ret = EXIT_SUCCESS;
9041 if (0) {} /* make conditional compile easier below */
9042 /*else if (find_alias(*argv))
9043 type = "an alias";*/
9044 #if ENABLE_HUSH_FUNCTIONS
9045 else if (find_function(*argv))
9046 type = "a function";
9048 else if (find_builtin(*argv))
9049 type = "a shell builtin";
9050 else if ((path = find_in_path(*argv)) != NULL)
9053 bb_error_msg("type: %s: not found", *argv);
9058 printf("%s is %s\n", *argv, type);
9066 #if ENABLE_HUSH_READ
9067 /* Interruptibility of read builtin in bash
9068 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9070 * Empty trap makes read ignore corresponding signal, for any signal.
9073 * - terminates non-interactive shell;
9074 * - interrupts read in interactive shell;
9075 * if it has non-empty trap:
9076 * - executes trap and returns to command prompt in interactive shell;
9077 * - executes trap and returns to read in non-interactive shell;
9079 * - is ignored (does not interrupt) read in interactive shell;
9080 * - terminates non-interactive shell;
9081 * if it has non-empty trap:
9082 * - executes trap and returns to read;
9084 * - terminates shell (regardless of interactivity);
9085 * if it has non-empty trap:
9086 * - executes trap and returns to read;
9087 * SIGCHLD from children:
9088 * - does not interrupt read regardless of interactivity:
9089 * try: sleep 1 & read x; echo $x
9091 static int FAST_FUNC builtin_read(char **argv)
9101 /* "!": do not abort on errors.
9102 * Option string must start with "sr" to match BUILTIN_READ_xxx
9104 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9105 if (read_flags == (uint32_t)-1)
9106 return EXIT_FAILURE;
9108 ifs = get_local_var_value("IFS"); /* can be NULL */
9111 r = shell_builtin_read(set_local_var_from_halves,
9121 if ((uintptr_t)r == 1 && errno == EINTR) {
9122 unsigned sig = check_and_run_traps();
9127 if ((uintptr_t)r > 1) {
9128 bb_error_msg("%s", r);
9129 r = (char*)(uintptr_t)1;
9132 return (uintptr_t)r;
9136 #if ENABLE_HUSH_UMASK
9137 static int FAST_FUNC builtin_umask(char **argv)
9144 argv = skip_dash_dash(argv);
9146 mode_t old_mask = mask;
9148 /* numeric umasks are taken as-is */
9149 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9150 if (!isdigit(argv[0][0]))
9152 mask = bb_parse_mode(argv[0], mask);
9153 if (!isdigit(argv[0][0]))
9155 if ((unsigned)mask > 0777) {
9158 * bash: umask: 'q': invalid symbolic mode operator
9159 * bash: umask: 999: octal number out of range
9161 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9166 printf("%04o\n", (unsigned) mask);
9167 /* fall through and restore mask which we set to 0 */
9171 return !rc; /* rc != 0 - success */
9175 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9176 static void print_escaped(const char *s)
9181 const char *p = strchrnul(s, '\'');
9182 /* print 'xxxx', possibly just '' */
9183 printf("'%.*s'", (int)(p - s), s);
9188 /* s points to '; print "'''...'''" */
9190 do putchar('\''); while (*++s == '\'');
9196 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL
9197 # if !ENABLE_HUSH_LOCAL
9198 #define helper_export_local(argv, exp, lvl) \
9199 helper_export_local(argv, exp)
9201 static void helper_export_local(char **argv, int exp, int lvl)
9205 char *name_end = strchrnul(name, '=');
9207 /* So far we do not check that name is valid (TODO?) */
9209 if (*name_end == '\0') {
9210 struct variable *var, **vpp;
9212 vpp = get_ptr_to_local_var(name, name_end - name);
9213 var = vpp ? *vpp : NULL;
9215 if (exp == -1) { /* unexporting? */
9216 /* export -n NAME (without =VALUE) */
9218 var->flg_export = 0;
9219 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9221 } /* else: export -n NOT_EXISTING_VAR: no-op */
9224 if (exp == 1) { /* exporting? */
9225 /* export NAME (without =VALUE) */
9227 var->flg_export = 1;
9228 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9229 putenv(var->varstr);
9233 # if ENABLE_HUSH_LOCAL
9234 if (exp == 0 /* local? */
9235 && var && var->func_nest_level == lvl
9237 /* "local x=abc; ...; local x" - ignore second local decl */
9241 /* Exporting non-existing variable.
9242 * bash does not put it in environment,
9243 * but remembers that it is exported,
9244 * and does put it in env when it is set later.
9245 * We just set it to "" and export. */
9246 /* Or, it's "local NAME" (without =VALUE).
9247 * bash sets the value to "". */
9248 name = xasprintf("%s=", name);
9250 /* (Un)exporting/making local NAME=VALUE */
9251 name = xstrdup(name);
9253 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
9258 #if ENABLE_HUSH_EXPORT
9259 static int FAST_FUNC builtin_export(char **argv)
9261 unsigned opt_unexport;
9263 #if ENABLE_HUSH_EXPORT_N
9264 /* "!": do not abort on errors */
9265 opt_unexport = getopt32(argv, "!n");
9266 if (opt_unexport == (uint32_t)-1)
9267 return EXIT_FAILURE;
9274 if (argv[0] == NULL) {
9281 /* ash emits: export VAR='VAL'
9282 * bash: declare -x VAR="VAL"
9283 * we follow ash example */
9284 const char *s = *e++;
9285 const char *p = strchr(s, '=');
9287 if (!p) /* wtf? take next variable */
9290 printf("export %.*s", (int)(p - s) + 1, s);
9291 print_escaped(p + 1);
9295 /*fflush_all(); - done after each builtin anyway */
9297 return EXIT_SUCCESS;
9300 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
9302 return EXIT_SUCCESS;
9306 #if ENABLE_HUSH_LOCAL
9307 static int FAST_FUNC builtin_local(char **argv)
9309 if (G.func_nest_level == 0) {
9310 bb_error_msg("%s: not in a function", argv[0]);
9311 return EXIT_FAILURE; /* bash compat */
9313 helper_export_local(argv, 0, G.func_nest_level);
9314 return EXIT_SUCCESS;
9318 #if ENABLE_HUSH_UNSET
9319 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9320 static int FAST_FUNC builtin_unset(char **argv)
9325 /* "!": do not abort on errors */
9326 /* "+": stop at 1st non-option */
9327 opts = getopt32(argv, "!+vf");
9328 if (opts == (unsigned)-1)
9329 return EXIT_FAILURE;
9331 bb_error_msg("unset: -v and -f are exclusive");
9332 return EXIT_FAILURE;
9338 if (!(opts & 2)) { /* not -f */
9339 if (unset_local_var(*argv)) {
9340 /* unset <nonexistent_var> doesn't fail.
9341 * Error is when one tries to unset RO var.
9342 * Message was printed by unset_local_var. */
9346 # if ENABLE_HUSH_FUNCTIONS
9358 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9359 * built-in 'set' handler
9361 * set [-abCefhmnuvx] [-o option] [argument...]
9362 * set [+abCefhmnuvx] [+o option] [argument...]
9363 * set -- [argument...]
9366 * Implementations shall support the options in both their hyphen and
9367 * plus-sign forms. These options can also be specified as options to sh.
9369 * Write out all variables and their values: set
9370 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9371 * Turn on the -x and -v options: set -xv
9372 * Unset all positional parameters: set --
9373 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9374 * Set the positional parameters to the expansion of x, even if x expands
9375 * with a leading '-' or '+': set -- $x
9377 * So far, we only support "set -- [argument...]" and some of the short names.
9379 static int FAST_FUNC builtin_set(char **argv)
9382 char **pp, **g_argv;
9383 char *arg = *++argv;
9387 for (e = G.top_var; e; e = e->next)
9389 return EXIT_SUCCESS;
9393 if (strcmp(arg, "--") == 0) {
9397 if (arg[0] != '+' && arg[0] != '-')
9399 for (n = 1; arg[n]; ++n) {
9400 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9402 if (arg[n] == 'o' && argv[1])
9405 } while ((arg = *++argv) != NULL);
9406 /* Now argv[0] is 1st argument */
9409 return EXIT_SUCCESS;
9412 /* NB: G.global_argv[0] ($0) is never freed/changed */
9413 g_argv = G.global_argv;
9414 if (G.global_args_malloced) {
9420 G.global_args_malloced = 1;
9421 pp = xzalloc(sizeof(pp[0]) * 2);
9422 pp[0] = g_argv[0]; /* retain $0 */
9425 /* This realloc's G.global_argv */
9426 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9428 G.global_argc = 1 + string_array_len(pp + 1);
9430 return EXIT_SUCCESS;
9432 /* Nothing known, so abort */
9434 bb_error_msg("set: %s: invalid option", arg);
9435 return EXIT_FAILURE;
9439 static int FAST_FUNC builtin_shift(char **argv)
9442 argv = skip_dash_dash(argv);
9444 n = bb_strtou(argv[0], NULL, 10);
9445 if (errno || n < 0) {
9446 /* shared string with ash.c */
9447 bb_error_msg("Illegal number: %s", argv[0]);
9449 * ash aborts in this case.
9450 * bash prints error message and set $? to 1.
9451 * Interestingly, for "shift 99999" bash does not
9452 * print error message, but does set $? to 1
9453 * (and does no shifting at all).
9457 if (n >= 0 && n < G.global_argc) {
9458 if (G_global_args_malloced) {
9461 free(G.global_argv[m++]);
9464 memmove(&G.global_argv[1], &G.global_argv[n+1],
9465 G.global_argc * sizeof(G.global_argv[0]));
9466 return EXIT_SUCCESS;
9468 return EXIT_FAILURE;
9471 static int FAST_FUNC builtin_source(char **argv)
9473 char *arg_path, *filename;
9476 char *args_need_save;
9477 #if ENABLE_HUSH_FUNCTIONS
9481 argv = skip_dash_dash(argv);
9484 /* bash says: "bash: .: filename argument required" */
9485 return 2; /* bash compat */
9488 if (!strchr(filename, '/')) {
9489 arg_path = find_in_path(filename);
9491 filename = arg_path;
9493 input = remember_FILE(fopen_or_warn(filename, "r"));
9496 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9497 /* POSIX: non-interactive shell should abort here,
9498 * not merely fail. So far no one complained :)
9500 return EXIT_FAILURE;
9503 #if ENABLE_HUSH_FUNCTIONS
9504 sv_flg = G_flag_return_in_progress;
9505 /* "we are inside sourced file, ok to use return" */
9506 G_flag_return_in_progress = -1;
9508 args_need_save = argv[1]; /* used as a boolean variable */
9510 save_and_replace_G_args(&sv, argv);
9512 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9513 G.last_exitcode = 0;
9514 parse_and_run_file(input);
9515 fclose_and_forget(input);
9517 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
9518 restore_G_args(&sv, argv);
9519 #if ENABLE_HUSH_FUNCTIONS
9520 G_flag_return_in_progress = sv_flg;
9523 return G.last_exitcode;
9526 #if ENABLE_HUSH_TRAP
9527 static int FAST_FUNC builtin_trap(char **argv)
9533 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9538 /* No args: print all trapped */
9539 for (i = 0; i < NSIG; ++i) {
9542 print_escaped(G_traps[i]);
9543 /* note: bash adds "SIG", but only if invoked
9544 * as "bash". If called as "sh", or if set -o posix,
9545 * then it prints short signal names.
9546 * We are printing short names: */
9547 printf(" %s\n", get_signame(i));
9550 /*fflush_all(); - done after each builtin anyway */
9551 return EXIT_SUCCESS;
9555 /* If first arg is a number: reset all specified signals */
9556 sig = bb_strtou(*argv, NULL, 10);
9562 sighandler_t handler;
9564 sig = get_signum(*argv++);
9565 if (sig < 0 || sig >= NSIG) {
9567 /* Mimic bash message exactly */
9568 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
9573 G_traps[sig] = xstrdup(new_cmd);
9575 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9576 get_signame(sig), sig, G_traps[sig]);
9578 /* There is no signal for 0 (EXIT) */
9583 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9585 /* We are removing trap handler */
9586 handler = pick_sighandler(sig);
9587 install_sighandler(sig, handler);
9592 if (!argv[1]) { /* no second arg */
9593 bb_error_msg("trap: invalid arguments");
9594 return EXIT_FAILURE;
9597 /* First arg is "-": reset all specified to default */
9598 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9599 /* Everything else: set arg as signal handler
9600 * (includes "" case, which ignores signal) */
9601 if (argv[0][0] == '-') {
9602 if (argv[0][1] == '\0') { /* "-" */
9603 /* new_cmd remains NULL: "reset these sigs" */
9606 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9609 /* else: "-something", no special meaning */
9614 goto process_sig_list;
9619 static struct pipe *parse_jobspec(const char *str)
9624 if (sscanf(str, "%%%u", &jobnum) != 1) {
9626 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
9628 bb_error_msg("bad argument '%s'", str);
9631 /* It is "%%", "%+" or "%" - current job */
9632 jobnum = G.last_jobid;
9634 bb_error_msg("no current job");
9638 for (pi = G.job_list; pi; pi = pi->next) {
9639 if (pi->jobid == jobnum) {
9643 bb_error_msg("%u: no such job", jobnum);
9647 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9650 const char *status_string;
9652 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9653 for (job = G.job_list; job; job = job->next) {
9654 if (job->alive_cmds == job->stopped_cmds)
9655 status_string = "Stopped";
9657 status_string = "Running";
9659 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9661 return EXIT_SUCCESS;
9664 /* built-in 'fg' and 'bg' handler */
9665 static int FAST_FUNC builtin_fg_bg(char **argv)
9670 if (!G_interactive_fd)
9671 return EXIT_FAILURE;
9673 /* If they gave us no args, assume they want the last backgrounded task */
9675 for (pi = G.job_list; pi; pi = pi->next) {
9676 if (pi->jobid == G.last_jobid) {
9680 bb_error_msg("%s: no current job", argv[0]);
9681 return EXIT_FAILURE;
9684 pi = parse_jobspec(argv[1]);
9686 return EXIT_FAILURE;
9688 /* TODO: bash prints a string representation
9689 * of job being foregrounded (like "sleep 1 | cat") */
9690 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
9691 /* Put the job into the foreground. */
9692 tcsetpgrp(G_interactive_fd, pi->pgrp);
9695 /* Restart the processes in the job */
9696 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9697 for (i = 0; i < pi->num_cmds; i++) {
9698 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
9700 pi->stopped_cmds = 0;
9702 i = kill(- pi->pgrp, SIGCONT);
9704 if (errno == ESRCH) {
9705 delete_finished_bg_job(pi);
9706 return EXIT_SUCCESS;
9708 bb_perror_msg("kill (SIGCONT)");
9711 if (argv[0][0] == 'f') {
9713 return checkjobs_and_fg_shell(pi);
9715 return EXIT_SUCCESS;
9719 #if ENABLE_HUSH_KILL
9720 static int FAST_FUNC builtin_kill(char **argv)
9724 # if ENABLE_HUSH_JOB
9725 if (argv[1] && strcmp(argv[1], "-l") != 0) {
9733 if (argv[i][0] != '%')
9736 * "kill %N" - job kill
9737 * Converting to pgrp / pid kill
9739 pi = parse_jobspec(argv[i]);
9741 /* Eat bad jobspec */
9745 argv[j - 1] = argv[j];
9752 * In jobs started under job control, we signal
9753 * entire process group by kill -PGRP_ID.
9754 * This happens, f.e., in interactive shell.
9756 * Otherwise, we signal each child via
9757 * kill PID1 PID2 PID3.
9759 * sh -c 'sleep 1|sleep 1 & kill %1'
9760 * sh -c 'true|sleep 2 & sleep 1; kill %1'
9761 * sh -c 'true|sleep 1 & sleep 2; kill %1'
9763 n = G_interactive_fd ? 1 : pi->num_cmds;
9764 dst = alloca(n * sizeof(int)*4);
9766 if (G_interactive_fd)
9767 dst += sprintf(dst, " -%u", (int)pi->pgrp);
9768 else for (j = 0; j < n; j++) {
9769 struct command *cmd = &pi->cmds[j];
9770 /* Skip exited members of the job */
9774 * kill_main has matching code to expect
9775 * leading space. Needed to not confuse
9776 * negative pids with "kill -SIGNAL_NO" syntax
9778 dst += sprintf(dst, " %u", (int)cmd->pid);
9781 } while (argv[++i]);
9785 if (argv[1] || ret == 0) {
9786 ret = run_applet_main(argv, kill_main);
9788 /* else: ret = 1, "kill %bad_jobspec" case */
9793 #if ENABLE_HUSH_WAIT
9794 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9795 #if !ENABLE_HUSH_JOB
9796 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9798 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
9805 if (!sigisemptyset(&G.pending_set))
9808 /* waitpid is not interruptible by SA_RESTARTed
9809 * signals which we use. Thus, this ugly dance:
9812 /* Make sure possible SIGCHLD is stored in kernel's
9813 * pending signal mask before we call waitpid.
9814 * Or else we may race with SIGCHLD, lose it,
9815 * and get stuck in sigsuspend...
9817 sigfillset(&oldset); /* block all signals, remember old set */
9818 sigprocmask(SIG_SETMASK, &oldset, &oldset);
9820 if (!sigisemptyset(&G.pending_set)) {
9821 /* Crap! we raced with some signal! */
9825 /*errno = 0; - checkjobs does this */
9826 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
9827 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
9828 debug_printf_exec("checkjobs:%d\n", ret);
9831 int rcode = job_exited_or_stopped(waitfor_pipe);
9832 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9835 sigprocmask(SIG_SETMASK, &oldset, NULL);
9840 /* if ECHILD, there are no children (ret is -1 or 0) */
9841 /* if ret == 0, no children changed state */
9842 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
9843 if (errno == ECHILD || ret) {
9845 if (ret < 0) /* if ECHILD, may need to fix "ret" */
9847 sigprocmask(SIG_SETMASK, &oldset, NULL);
9850 /* Wait for SIGCHLD or any other signal */
9851 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9852 /* Note: sigsuspend invokes signal handler */
9853 sigsuspend(&oldset);
9855 sigprocmask(SIG_SETMASK, &oldset, NULL);
9857 /* So, did we get a signal? */
9858 sig = check_and_run_traps();
9859 if (sig /*&& sig != SIGCHLD - always true */) {
9863 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9868 static int FAST_FUNC builtin_wait(char **argv)
9873 argv = skip_dash_dash(argv);
9874 if (argv[0] == NULL) {
9875 /* Don't care about wait results */
9876 /* Note 1: must wait until there are no more children */
9877 /* Note 2: must be interruptible */
9879 * $ sleep 3 & sleep 6 & wait
9884 * $ sleep 3 & sleep 6 & wait
9888 * ^C <-- after ~4 sec from keyboard
9891 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
9895 pid_t pid = bb_strtou(*argv, NULL, 10);
9896 if (errno || pid <= 0) {
9898 if (argv[0][0] == '%') {
9899 struct pipe *wait_pipe;
9900 ret = 127; /* bash compat for bad jobspecs */
9901 wait_pipe = parse_jobspec(*argv);
9903 ret = job_exited_or_stopped(wait_pipe);
9905 ret = wait_for_child_or_signal(wait_pipe, 0);
9906 //bash immediately deletes finished jobs from job table only in interactive mode,
9907 //we _always_ delete them at once. If we'd start doing that, this (and more)
9908 //would be necessary to avoid accumulating dead jobs:
9911 if (!wait_pipe->alive_cmds)
9912 delete_finished_bg_job(wait_pipe);
9916 /* else: parse_jobspec() already emitted error msg */
9920 /* mimic bash message */
9921 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9923 continue; /* bash checks all argv[] */
9926 /* Do we have such child? */
9927 ret = waitpid(pid, &status, WNOHANG);
9931 if (errno == ECHILD) {
9932 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9933 /* "wait $!" but last bg task has already exited. Try:
9934 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9935 * In bash it prints exitcode 0, then 3.
9936 * In dash, it is 127.
9938 ret = G.last_bg_pid_exitcode;
9940 /* Example: "wait 1". mimic bash message */
9941 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
9945 bb_perror_msg("wait %s", *argv);
9947 continue; /* bash checks all argv[] */
9950 /* Yes, and it still runs */
9951 ret = wait_for_child_or_signal(NULL, pid);
9953 /* Yes, and it just exited */
9954 process_wait_result(NULL, pid, status);
9955 ret = WEXITSTATUS(status);
9956 if (WIFSIGNALED(status))
9957 ret = 128 + WTERMSIG(status);
9965 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9966 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9969 def = bb_strtou(argv[1], NULL, 10);
9970 if (errno || def < def_min || argv[2]) {
9971 bb_error_msg("%s: bad arguments", argv[0]);
9979 #if ENABLE_HUSH_LOOPS
9980 static int FAST_FUNC builtin_break(char **argv)
9983 if (G.depth_of_loop == 0) {
9984 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9985 /* if we came from builtin_continue(), need to undo "= 1" */
9986 G.flag_break_continue = 0;
9987 return EXIT_SUCCESS; /* bash compat */
9989 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9991 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9992 if (depth == UINT_MAX)
9993 G.flag_break_continue = BC_BREAK;
9994 if (G.depth_of_loop < depth)
9995 G.depth_break_continue = G.depth_of_loop;
9997 return EXIT_SUCCESS;
10000 static int FAST_FUNC builtin_continue(char **argv)
10002 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10003 return builtin_break(argv);
10007 #if ENABLE_HUSH_FUNCTIONS
10008 static int FAST_FUNC builtin_return(char **argv)
10012 if (G_flag_return_in_progress != -1) {
10013 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10014 return EXIT_FAILURE; /* bash compat */
10017 G_flag_return_in_progress = 1;
10020 * out of range: wraps around at 256, does not error out
10021 * non-numeric param:
10022 * f() { false; return qwe; }; f; echo $?
10023 * bash: return: qwe: numeric argument required <== we do this
10024 * 255 <== we also do this
10026 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10031 #if ENABLE_HUSH_MEMLEAK
10032 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10037 # ifdef M_TRIM_THRESHOLD
10038 /* Optional. Reduces probability of false positives */
10041 /* Crude attempt to find where "free memory" starts,
10042 * sans fragmentation. */
10044 l = (unsigned long)p;
10047 if (l < (unsigned long)p) l = (unsigned long)p;
10053 struct mallinfo mi = mallinfo();
10054 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10055 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10059 if (!G.memleak_value)
10060 G.memleak_value = l;
10062 l -= G.memleak_value;
10069 /* Exitcode is "how many kilobytes we leaked since 1st call" */