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 * make complex ${var%...} constructs support optional
45 * make here documents optional
46 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
50 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
53 * command BLTIN: disables special-ness (e.g. errors do not abort)
54 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
57 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
62 * redirection of stdout+stderr: &> and >&
63 * reserved words: function select
64 * advanced test: [[ ]]
65 * process substitution: <(list) and >(list)
68 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
72 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
74 * $[EXPR]: synonym for $((EXPR))
75 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
79 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
82 * In bash, export builtin is special, its arguments are assignments
83 * and therefore expansion of them should be "one-word" expansion:
84 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
86 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
87 * ls: cannot access i=a: No such file or directory
88 * ls: cannot access b: No such file or directory
89 * Note1: same applies to local builtin.
90 * Note2: bash 3.2.33(1) does this only if export word itself
92 * $ export i=`echo 'aaa bbb'`; echo "$i"
94 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
98 //config: bool "hush (64 kb)"
101 //config: hush is a small shell. It handles the normal flow control
102 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
103 //config: case/esac. Redirections, here documents, $((arithmetic))
104 //config: and functions are supported.
106 //config: It will compile and work on no-mmu systems.
108 //config: It does not handle select, aliases, tilde expansion,
109 //config: &>file and >&file redirection of stdout+stderr.
111 //config:config HUSH_BASH_COMPAT
112 //config: bool "bash-compatible extensions"
114 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
116 //config:config HUSH_BRACE_EXPANSION
117 //config: bool "Brace expansion"
119 //config: depends on HUSH_BASH_COMPAT
121 //config: Enable {abc,def} extension.
123 //config:config HUSH_LINENO_VAR
124 //config: bool "$LINENO variable"
126 //config: depends on HUSH_BASH_COMPAT
128 //config:config HUSH_BASH_SOURCE_CURDIR
129 //config: bool "'source' and '.' builtins search current directory after $PATH"
130 //config: default n # do not encourage non-standard behavior
131 //config: depends on HUSH_BASH_COMPAT
133 //config: This is not compliant with standards. Avoid if possible.
135 //config:config HUSH_INTERACTIVE
136 //config: bool "Interactive mode"
138 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
140 //config: Enable interactive mode (prompt and command editing).
141 //config: Without this, hush simply reads and executes commands
142 //config: from stdin just like a shell script from a file.
143 //config: No prompt, no PS1/PS2 magic shell variables.
145 //config:config HUSH_SAVEHISTORY
146 //config: bool "Save command history to .hush_history"
148 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
150 //config:config HUSH_JOB
151 //config: bool "Job control"
153 //config: depends on HUSH_INTERACTIVE
155 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
156 //config: command (not entire shell), fg/bg builtins work. Without this option,
157 //config: "cmd &" still works by simply spawning a process and immediately
158 //config: prompting for next command (or executing next command in a script),
159 //config: but no separate process group is formed.
161 //config:config HUSH_TICK
162 //config: bool "Support process substitution"
164 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
166 //config: Enable `command` and $(command).
168 //config:config HUSH_IF
169 //config: bool "Support if/then/elif/else/fi"
171 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
173 //config:config HUSH_LOOPS
174 //config: bool "Support for, while and until loops"
176 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
178 //config:config HUSH_CASE
179 //config: bool "Support case ... esac statement"
181 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
183 //config: Enable case ... esac statement. +400 bytes.
185 //config:config HUSH_FUNCTIONS
186 //config: bool "Support funcname() { commands; } syntax"
188 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
190 //config: Enable support for shell functions. +800 bytes.
192 //config:config HUSH_LOCAL
193 //config: bool "local builtin"
195 //config: depends on HUSH_FUNCTIONS
197 //config: Enable support for local variables in functions.
199 //config:config HUSH_RANDOM_SUPPORT
200 //config: bool "Pseudorandom generator and $RANDOM variable"
202 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
204 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
205 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
207 //config:config HUSH_MODE_X
208 //config: bool "Support 'hush -x' option and 'set -x' command"
210 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
212 //config: This instructs hush to print commands before execution.
213 //config: Adds ~300 bytes.
215 //config:config HUSH_ECHO
216 //config: bool "echo builtin"
218 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
220 //config:config HUSH_PRINTF
221 //config: bool "printf builtin"
223 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
225 //config:config HUSH_TEST
226 //config: bool "test builtin"
228 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
230 //config:config HUSH_HELP
231 //config: bool "help builtin"
233 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
235 //config:config HUSH_EXPORT
236 //config: bool "export builtin"
238 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
240 //config:config HUSH_EXPORT_N
241 //config: bool "Support 'export -n' option"
243 //config: depends on HUSH_EXPORT
245 //config: export -n unexports variables. It is a bash extension.
247 //config:config HUSH_READONLY
248 //config: bool "readonly builtin"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config: Enable support for read-only variables.
254 //config:config HUSH_KILL
255 //config: bool "kill builtin (supports kill %jobspec)"
257 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
259 //config:config HUSH_WAIT
260 //config: bool "wait builtin"
262 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
264 //config:config HUSH_COMMAND
265 //config: bool "command builtin"
267 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
269 //config:config HUSH_TRAP
270 //config: bool "trap builtin"
272 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
274 //config:config HUSH_TYPE
275 //config: bool "type builtin"
277 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
279 //config:config HUSH_TIMES
280 //config: bool "times builtin"
282 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
284 //config:config HUSH_READ
285 //config: bool "read builtin"
287 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
289 //config:config HUSH_SET
290 //config: bool "set builtin"
292 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
294 //config:config HUSH_UNSET
295 //config: bool "unset builtin"
297 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
299 //config:config HUSH_ULIMIT
300 //config: bool "ulimit builtin"
302 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
304 //config:config HUSH_UMASK
305 //config: bool "umask builtin"
307 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
309 //config:config HUSH_GETOPTS
310 //config: bool "getopts builtin"
312 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
314 //config:config HUSH_MEMLEAK
315 //config: bool "memleak builtin (debugging)"
317 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
319 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
320 // APPLET_ODDNAME:name main location suid_type help
321 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
322 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
324 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
325 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
326 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
327 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
329 /* -i (interactive) and -s (read stdin) are also accepted,
330 * but currently do nothing, therefore aren't shown in help.
331 * NOMMU-specific options are not meant to be used by users,
332 * therefore we don't show them either.
334 //usage:#define hush_trivial_usage
335 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
336 //usage:#define hush_full_usage "\n\n"
337 //usage: "Unix shell interpreter"
339 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
340 || defined(__APPLE__) \
342 # include <malloc.h> /* for malloc_trim */
345 /* #include <dmalloc.h> */
347 # include <fnmatch.h>
349 #include <sys/times.h>
350 #include <sys/utsname.h> /* for setting $HOSTNAME */
352 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
354 #include "shell_common.h"
357 #if ENABLE_HUSH_RANDOM_SUPPORT
360 # define CLEAR_RANDOM_T(rnd) ((void)0)
362 #ifndef F_DUPFD_CLOEXEC
363 # define F_DUPFD_CLOEXEC F_DUPFD
366 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
370 /* So far, all bash compat is controlled by one config option */
371 /* Separate defines document which part of code implements what */
372 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
373 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
374 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
375 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
376 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
377 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
381 #define LEAK_HUNTING 0
382 #define BUILD_AS_NOMMU 0
383 /* Enable/disable sanity checks. Ok to enable in production,
384 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
385 * Keeping 1 for now even in released versions.
388 /* Slightly bigger (+200 bytes), but faster hush.
389 * So far it only enables a trick with counting SIGCHLDs and forks,
390 * which allows us to do fewer waitpid's.
391 * (we can detect a case where neither forks were done nor SIGCHLDs happened
392 * and therefore waitpid will return the same result as last time)
394 #define ENABLE_HUSH_FAST 0
395 /* TODO: implement simplified code for users which do not need ${var%...} ops
396 * So far ${var%...} ops are always enabled:
398 #define ENABLE_HUSH_DOLLAR_OPS 1
403 # undef USE_FOR_NOMMU
406 # define USE_FOR_NOMMU(...) __VA_ARGS__
407 # define USE_FOR_MMU(...)
410 #include "NUM_APPLETS.h"
412 /* STANDALONE does not make sense, and won't compile */
413 # undef CONFIG_FEATURE_SH_STANDALONE
414 # undef ENABLE_FEATURE_SH_STANDALONE
415 # undef IF_FEATURE_SH_STANDALONE
416 # undef IF_NOT_FEATURE_SH_STANDALONE
417 # define ENABLE_FEATURE_SH_STANDALONE 0
418 # define IF_FEATURE_SH_STANDALONE(...)
419 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
422 #if !ENABLE_HUSH_INTERACTIVE
423 # undef ENABLE_FEATURE_EDITING
424 # define ENABLE_FEATURE_EDITING 0
425 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
426 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
427 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
428 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
431 /* Do we support ANY keywords? */
432 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
433 # define HAS_KEYWORDS 1
434 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
435 # define IF_HAS_NO_KEYWORDS(...)
437 # define HAS_KEYWORDS 0
438 # define IF_HAS_KEYWORDS(...)
439 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
442 /* If you comment out one of these below, it will be #defined later
443 * to perform debug printfs to stderr: */
444 #define debug_printf(...) do {} while (0)
445 /* Finer-grained debug switches */
446 #define debug_printf_parse(...) do {} while (0)
447 #define debug_print_tree(a, b) do {} while (0)
448 #define debug_printf_exec(...) do {} while (0)
449 #define debug_printf_env(...) do {} while (0)
450 #define debug_printf_jobs(...) do {} while (0)
451 #define debug_printf_expand(...) do {} while (0)
452 #define debug_printf_varexp(...) do {} while (0)
453 #define debug_printf_glob(...) do {} while (0)
454 #define debug_printf_redir(...) do {} while (0)
455 #define debug_printf_list(...) do {} while (0)
456 #define debug_printf_subst(...) do {} while (0)
457 #define debug_printf_clean(...) do {} while (0)
459 #define ERR_PTR ((void*)(long)1)
461 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
463 #define _SPECIAL_VARS_STR "_*@$!?#"
464 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
465 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
466 #if BASH_PATTERN_SUBST
467 /* Support / and // replace ops */
468 /* Note that // is stored as \ in "encoded" string representation */
469 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
470 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
471 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
473 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
474 # define VAR_SUBST_OPS "%#:-=+?"
475 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
478 #define SPECIAL_VAR_SYMBOL_STR "\3"
479 #define SPECIAL_VAR_SYMBOL 3
480 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
481 #define SPECIAL_VAR_QUOTED_SVS 1
485 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
487 /* This supports saving pointers malloced in vfork child,
488 * to be freed in the parent.
491 typedef struct nommu_save_t {
493 struct variable *old_vars;
495 char **argv_from_re_execing;
508 #if ENABLE_HUSH_LOOPS
515 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
520 /* three pseudo-keywords support contrived "case" syntax: */
521 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
522 RES_MATCH , /* "word)" */
523 RES_CASE_BODY, /* "this command is inside CASE" */
530 typedef struct o_string {
532 int length; /* position where data is appended */
535 /* At least some part of the string was inside '' or "",
536 * possibly empty one: word"", wo''rd etc. */
537 smallint has_quoted_part;
538 smallint has_empty_slot;
539 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
542 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
544 /* Protect newly added chars against globbing
545 * by prepending \ to *, ?, [, \ */
546 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
549 MAYBE_ASSIGNMENT = 0,
550 DEFINITELY_ASSIGNMENT = 1,
552 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
555 /* Used for initialization: o_string foo = NULL_O_STRING; */
556 #define NULL_O_STRING { NULL }
558 #ifndef debug_printf_parse
559 static const char *const assignment_flag[] = {
561 "DEFINITELY_ASSIGNMENT",
567 typedef struct in_str {
569 #if ENABLE_HUSH_INTERACTIVE
570 smallint promptmode; /* 0: PS1, 1: PS2 */
577 /* The descrip member of this structure is only used to make
578 * debugging output pretty */
579 static const struct {
581 signed char default_fd;
584 { O_RDONLY, 0, "<" },
585 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
586 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
587 { O_CREAT|O_RDWR, 1, "<>" },
588 { O_RDONLY, 0, "<<" },
589 /* Should not be needed. Bogus default_fd helps in debugging */
590 /* { O_RDONLY, 77, "<<" }, */
593 struct redir_struct {
594 struct redir_struct *next;
595 char *rd_filename; /* filename */
596 int rd_fd; /* fd to redirect */
597 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
599 smallint rd_type; /* (enum redir_type) */
600 /* note: for heredocs, rd_filename contains heredoc delimiter,
601 * and subsequently heredoc itself; and rd_dup is a bitmask:
602 * bit 0: do we need to trim leading tabs?
603 * bit 1: is heredoc quoted (<<'delim' syntax) ?
606 typedef enum redir_type {
608 REDIRECT_OVERWRITE = 1,
611 REDIRECT_HEREDOC = 4,
612 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
615 REDIRFD_SYNTAX_ERR = -2,
616 REDIRFD_TO_FILE = -1,
617 /* otherwise, rd_fd is redirected to rd_dup */
619 HEREDOC_SKIPTABS = 1,
625 pid_t pid; /* 0 if exited */
626 int assignment_cnt; /* how many argv[i] are assignments? */
627 #if ENABLE_HUSH_LINENO_VAR
630 smallint cmd_type; /* CMD_xxx */
632 #define CMD_SUBSHELL 1
634 /* used for "[[ EXPR ]]" */
635 # define CMD_SINGLEWORD_NOGLOB 2
637 #if ENABLE_HUSH_FUNCTIONS
638 # define CMD_FUNCDEF 3
641 smalluint cmd_exitcode;
642 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
645 char *group_as_string;
647 #if ENABLE_HUSH_FUNCTIONS
648 struct function *child_func;
649 /* This field is used to prevent a bug here:
650 * while...do f1() {a;}; f1; f1() {b;}; f1; done
651 * When we execute "f1() {a;}" cmd, we create new function and clear
652 * cmd->group, cmd->group_as_string, cmd->argv[0].
653 * When we execute "f1() {b;}", we notice that f1 exists,
654 * and that its "parent cmd" struct is still "alive",
655 * we put those fields back into cmd->xxx
656 * (struct function has ->parent_cmd ptr to facilitate that).
657 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
658 * Without this trick, loop would execute a;b;b;b;...
659 * instead of correct sequence a;b;a;b;...
660 * When command is freed, it severs the link
661 * (sets ->child_func->parent_cmd to NULL).
664 char **argv; /* command name and arguments */
665 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
666 * and on execution these are substituted with their values.
667 * Substitution can make _several_ words out of one argv[n]!
668 * Example: argv[0]=='.^C*^C.' here: echo .$*.
669 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
671 struct redir_struct *redirects; /* I/O redirections */
673 /* Is there anything in this command at all? */
674 #define IS_NULL_CMD(cmd) \
675 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
679 int num_cmds; /* total number of commands in pipe */
680 int alive_cmds; /* number of commands running (not exited) */
681 int stopped_cmds; /* number of commands alive, but stopped */
683 unsigned jobid; /* job number */
684 pid_t pgrp; /* process group ID for the job */
685 char *cmdtext; /* name of job */
687 struct command *cmds; /* array of commands in pipe */
688 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
689 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
690 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
692 typedef enum pipe_style {
698 /* Is there anything in this pipe at all? */
699 #define IS_NULL_PIPE(pi) \
700 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
702 /* This holds pointers to the various results of parsing */
703 struct parse_context {
704 /* linked list of pipes */
705 struct pipe *list_head;
706 /* last pipe (being constructed right now) */
708 /* last command in pipe (being constructed right now) */
709 struct command *command;
710 /* last redirect in command->redirects list */
711 struct redir_struct *pending_redirect;
717 smallint ctx_inverted; /* "! cmd | cmd" */
719 smallint ctx_dsemicolon; /* ";;" seen */
721 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
723 /* group we are enclosed in:
724 * example: "if pipe1; pipe2; then pipe3; fi"
725 * when we see "if" or "then", we malloc and copy current context,
726 * and make ->stack point to it. then we parse pipeN.
727 * when closing "then" / fi" / whatever is found,
728 * we move list_head into ->stack->command->group,
729 * copy ->stack into current context, and delete ->stack.
730 * (parsing of { list } and ( list ) doesn't use this method)
732 struct parse_context *stack;
736 /* On program start, environ points to initial environment.
737 * putenv adds new pointers into it, unsetenv removes them.
738 * Neither of these (de)allocates the strings.
739 * setenv allocates new strings in malloc space and does putenv,
740 * and thus setenv is unusable (leaky) for shell's purposes */
741 #define setenv(...) setenv_is_leaky_dont_use()
743 struct variable *next;
744 char *varstr; /* points to "name=" portion */
745 #if ENABLE_HUSH_LOCAL
746 unsigned func_nest_level;
748 int max_len; /* if > 0, name is part of initial env; else name is malloced */
749 smallint flg_export; /* putenv should be done on this var */
750 smallint flg_read_only;
758 #if ENABLE_HUSH_FUNCTIONS
760 struct function *next;
762 struct command *parent_cmd;
765 char *body_as_string;
771 /* set -/+o OPT support. (TODO: make it optional)
772 * bash supports the following opts:
783 * interactive-comments on
801 static const char o_opt_strings[] ALIGN1 =
805 #if ENABLE_HUSH_MODE_X
813 #if ENABLE_HUSH_MODE_X
821 struct FILE_list *next;
827 /* "Globals" within this file */
828 /* Sorted roughly by size (smaller offsets == smaller code) */
830 /* interactive_fd != 0 means we are an interactive shell.
831 * If we are, then saved_tty_pgrp can also be != 0, meaning
832 * that controlling tty is available. With saved_tty_pgrp == 0,
833 * job control still works, but terminal signals
834 * (^C, ^Z, ^Y, ^\) won't work at all, and background
835 * process groups can only be created with "cmd &".
836 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
837 * to give tty to the foreground process group,
838 * and will take it back when the group is stopped (^Z)
841 #if ENABLE_HUSH_INTERACTIVE
842 /* 'interactive_fd' is a fd# open to ctty, if we have one
843 * _AND_ if we decided to act interactively */
847 # define G_interactive_fd (G.interactive_fd)
849 # define G_interactive_fd 0
851 #if ENABLE_FEATURE_EDITING
852 line_input_t *line_input_state;
857 #if ENABLE_HUSH_RANDOM_SUPPORT
863 pid_t saved_tty_pgrp;
864 struct pipe *job_list;
865 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
867 # define G_saved_tty_pgrp 0
869 /* How deeply are we in context where "set -e" is ignored */
871 /* "set -e" rules (do we follow them correctly?):
872 * Exit if pipe, list, or compound command exits with a non-zero status.
873 * Shell does not exit if failed command is part of condition in
874 * if/while, part of && or || list except the last command, any command
875 * in a pipe but the last, or if the command's return value is being
876 * inverted with !. If a compound command other than a subshell returns a
877 * non-zero status because a command failed while -e was being ignored, the
878 * shell does not exit. A trap on ERR, if set, is executed before the shell
879 * exits [ERR is a bashism].
881 * If a compound command or function executes in a context where -e is
882 * ignored, none of the commands executed within are affected by the -e
883 * setting. If a compound command or function sets -e while executing in a
884 * context where -e is ignored, that setting does not have any effect until
885 * the compound command or the command containing the function call completes.
888 char o_opt[NUM_OPT_O];
889 #if ENABLE_HUSH_MODE_X
890 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
894 smallint flag_SIGINT;
895 #if ENABLE_HUSH_LOOPS
896 smallint flag_break_continue;
898 #if ENABLE_HUSH_FUNCTIONS
899 /* 0: outside of a function (or sourced file)
900 * -1: inside of a function, ok to use return builtin
901 * 1: return is invoked, skip all till end of func
903 smallint flag_return_in_progress;
904 # define G_flag_return_in_progress (G.flag_return_in_progress)
906 # define G_flag_return_in_progress 0
908 smallint exiting; /* used to prevent EXIT trap recursion */
909 /* These four support $?, $#, and $1 */
910 smalluint last_exitcode;
911 smalluint last_bg_pid_exitcode;
913 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
914 smalluint global_args_malloced;
915 # define G_global_args_malloced (G.global_args_malloced)
917 # define G_global_args_malloced 0
919 /* how many non-NULL argv's we have. NB: $# + 1 */
923 char *argv0_for_re_execing;
925 #if ENABLE_HUSH_LOOPS
926 unsigned depth_break_continue;
927 unsigned depth_of_loop;
929 #if ENABLE_HUSH_GETOPTS
930 unsigned getopt_count;
934 struct variable *top_var;
935 char **expanded_assignments;
936 #if ENABLE_HUSH_FUNCTIONS
937 struct function *top_func;
938 # if ENABLE_HUSH_LOCAL
939 struct variable **shadowed_vars_pp;
940 unsigned func_nest_level;
943 /* Signal and trap handling */
945 unsigned count_SIGCHLD;
946 unsigned handled_SIGCHLD;
947 smallint we_have_children;
949 #if ENABLE_HUSH_LINENO_VAR
953 struct FILE_list *FILE_list;
954 /* Which signals have non-DFL handler (even with no traps set)?
955 * Set at the start to:
956 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
957 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
958 * The rest is cleared right before execv syscalls.
959 * Other than these two times, never modified.
961 unsigned special_sig_mask;
963 unsigned fatal_sig_mask;
964 # define G_fatal_sig_mask (G.fatal_sig_mask)
966 # define G_fatal_sig_mask 0
969 char **traps; /* char *traps[NSIG] */
970 # define G_traps G.traps
972 # define G_traps ((char**)NULL)
974 sigset_t pending_set;
975 #if ENABLE_HUSH_MEMLEAK
976 unsigned long memleak_value;
982 #if ENABLE_FEATURE_EDITING
983 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
986 #define G (*ptr_to_globals)
987 /* Not #defining name to G.name - this quickly gets unwieldy
988 * (too many defines). Also, I actually prefer to see when a variable
989 * is global, thus "G." prefix is a useful hint */
990 #define INIT_G() do { \
991 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
992 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
993 sigfillset(&G.sa.sa_mask); \
994 G.sa.sa_flags = SA_RESTART; \
998 /* Function prototypes for builtins */
999 static int builtin_cd(char **argv) FAST_FUNC;
1000 #if ENABLE_HUSH_ECHO
1001 static int builtin_echo(char **argv) FAST_FUNC;
1003 static int builtin_eval(char **argv) FAST_FUNC;
1004 static int builtin_exec(char **argv) FAST_FUNC;
1005 static int builtin_exit(char **argv) FAST_FUNC;
1006 #if ENABLE_HUSH_EXPORT
1007 static int builtin_export(char **argv) FAST_FUNC;
1009 #if ENABLE_HUSH_READONLY
1010 static int builtin_readonly(char **argv) FAST_FUNC;
1013 static int builtin_fg_bg(char **argv) FAST_FUNC;
1014 static int builtin_jobs(char **argv) FAST_FUNC;
1016 #if ENABLE_HUSH_GETOPTS
1017 static int builtin_getopts(char **argv) FAST_FUNC;
1019 #if ENABLE_HUSH_HELP
1020 static int builtin_help(char **argv) FAST_FUNC;
1022 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1023 static int builtin_history(char **argv) FAST_FUNC;
1025 #if ENABLE_HUSH_LOCAL
1026 static int builtin_local(char **argv) FAST_FUNC;
1028 #if ENABLE_HUSH_MEMLEAK
1029 static int builtin_memleak(char **argv) FAST_FUNC;
1031 #if ENABLE_HUSH_PRINTF
1032 static int builtin_printf(char **argv) FAST_FUNC;
1034 static int builtin_pwd(char **argv) FAST_FUNC;
1035 #if ENABLE_HUSH_READ
1036 static int builtin_read(char **argv) FAST_FUNC;
1039 static int builtin_set(char **argv) FAST_FUNC;
1041 static int builtin_shift(char **argv) FAST_FUNC;
1042 static int builtin_source(char **argv) FAST_FUNC;
1043 #if ENABLE_HUSH_TEST || BASH_TEST2
1044 static int builtin_test(char **argv) FAST_FUNC;
1046 #if ENABLE_HUSH_TRAP
1047 static int builtin_trap(char **argv) FAST_FUNC;
1049 #if ENABLE_HUSH_TYPE
1050 static int builtin_type(char **argv) FAST_FUNC;
1052 #if ENABLE_HUSH_TIMES
1053 static int builtin_times(char **argv) FAST_FUNC;
1055 static int builtin_true(char **argv) FAST_FUNC;
1056 #if ENABLE_HUSH_UMASK
1057 static int builtin_umask(char **argv) FAST_FUNC;
1059 #if ENABLE_HUSH_UNSET
1060 static int builtin_unset(char **argv) FAST_FUNC;
1062 #if ENABLE_HUSH_KILL
1063 static int builtin_kill(char **argv) FAST_FUNC;
1065 #if ENABLE_HUSH_WAIT
1066 static int builtin_wait(char **argv) FAST_FUNC;
1068 #if ENABLE_HUSH_LOOPS
1069 static int builtin_break(char **argv) FAST_FUNC;
1070 static int builtin_continue(char **argv) FAST_FUNC;
1072 #if ENABLE_HUSH_FUNCTIONS
1073 static int builtin_return(char **argv) FAST_FUNC;
1076 /* Table of built-in functions. They can be forked or not, depending on
1077 * context: within pipes, they fork. As simple commands, they do not.
1078 * When used in non-forking context, they can change global variables
1079 * in the parent shell process. If forked, of course they cannot.
1080 * For example, 'unset foo | whatever' will parse and run, but foo will
1081 * still be set at the end. */
1082 struct built_in_command {
1084 int (*b_function)(char **argv) FAST_FUNC;
1085 #if ENABLE_HUSH_HELP
1086 const char *b_descr;
1087 # define BLTIN(cmd, func, help) { cmd, func, help }
1089 # define BLTIN(cmd, func, help) { cmd, func }
1093 static const struct built_in_command bltins1[] = {
1094 BLTIN("." , builtin_source , "Run commands in file"),
1095 BLTIN(":" , builtin_true , NULL),
1097 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1099 #if ENABLE_HUSH_LOOPS
1100 BLTIN("break" , builtin_break , "Exit loop"),
1102 BLTIN("cd" , builtin_cd , "Change directory"),
1103 #if ENABLE_HUSH_LOOPS
1104 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1106 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1107 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1108 BLTIN("exit" , builtin_exit , NULL),
1109 #if ENABLE_HUSH_EXPORT
1110 BLTIN("export" , builtin_export , "Set environment variables"),
1113 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1115 #if ENABLE_HUSH_GETOPTS
1116 BLTIN("getopts" , builtin_getopts , NULL),
1118 #if ENABLE_HUSH_HELP
1119 BLTIN("help" , builtin_help , NULL),
1121 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1122 BLTIN("history" , builtin_history , "Show history"),
1125 BLTIN("jobs" , builtin_jobs , "List jobs"),
1127 #if ENABLE_HUSH_KILL
1128 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1130 #if ENABLE_HUSH_LOCAL
1131 BLTIN("local" , builtin_local , "Set local variables"),
1133 #if ENABLE_HUSH_MEMLEAK
1134 BLTIN("memleak" , builtin_memleak , NULL),
1136 #if ENABLE_HUSH_READ
1137 BLTIN("read" , builtin_read , "Input into variable"),
1139 #if ENABLE_HUSH_READONLY
1140 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1142 #if ENABLE_HUSH_FUNCTIONS
1143 BLTIN("return" , builtin_return , "Return from function"),
1146 BLTIN("set" , builtin_set , "Set positional parameters"),
1148 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1150 BLTIN("source" , builtin_source , NULL),
1152 #if ENABLE_HUSH_TIMES
1153 BLTIN("times" , builtin_times , NULL),
1155 #if ENABLE_HUSH_TRAP
1156 BLTIN("trap" , builtin_trap , "Trap signals"),
1158 BLTIN("true" , builtin_true , NULL),
1159 #if ENABLE_HUSH_TYPE
1160 BLTIN("type" , builtin_type , "Show command type"),
1162 #if ENABLE_HUSH_ULIMIT
1163 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1165 #if ENABLE_HUSH_UMASK
1166 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1168 #if ENABLE_HUSH_UNSET
1169 BLTIN("unset" , builtin_unset , "Unset variables"),
1171 #if ENABLE_HUSH_WAIT
1172 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1175 /* These builtins won't be used if we are on NOMMU and need to re-exec
1176 * (it's cheaper to run an external program in this case):
1178 static const struct built_in_command bltins2[] = {
1179 #if ENABLE_HUSH_TEST
1180 BLTIN("[" , builtin_test , NULL),
1183 BLTIN("[[" , builtin_test , NULL),
1185 #if ENABLE_HUSH_ECHO
1186 BLTIN("echo" , builtin_echo , NULL),
1188 #if ENABLE_HUSH_PRINTF
1189 BLTIN("printf" , builtin_printf , NULL),
1191 BLTIN("pwd" , builtin_pwd , NULL),
1192 #if ENABLE_HUSH_TEST
1193 BLTIN("test" , builtin_test , NULL),
1201 /* prevent disasters with G.debug_indent < 0 */
1202 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1203 # define debug_enter() (G.debug_indent++)
1204 # define debug_leave() (G.debug_indent--)
1206 # define indent() ((void)0)
1207 # define debug_enter() ((void)0)
1208 # define debug_leave() ((void)0)
1211 #ifndef debug_printf
1212 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1215 #ifndef debug_printf_parse
1216 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1219 #ifndef debug_printf_exec
1220 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1223 #ifndef debug_printf_env
1224 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1227 #ifndef debug_printf_jobs
1228 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1229 # define DEBUG_JOBS 1
1231 # define DEBUG_JOBS 0
1234 #ifndef debug_printf_expand
1235 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1236 # define DEBUG_EXPAND 1
1238 # define DEBUG_EXPAND 0
1241 #ifndef debug_printf_varexp
1242 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1245 #ifndef debug_printf_glob
1246 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1247 # define DEBUG_GLOB 1
1249 # define DEBUG_GLOB 0
1252 #ifndef debug_printf_redir
1253 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1256 #ifndef debug_printf_list
1257 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1260 #ifndef debug_printf_subst
1261 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1264 #ifndef debug_printf_clean
1265 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1266 # define DEBUG_CLEAN 1
1268 # define DEBUG_CLEAN 0
1272 static void debug_print_strings(const char *prefix, char **vv)
1275 fdprintf(2, "%s:\n", prefix);
1277 fdprintf(2, " '%s'\n", *vv++);
1280 # define debug_print_strings(prefix, vv) ((void)0)
1284 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1287 static void *xxmalloc(int lineno, size_t size)
1289 void *ptr = xmalloc((size + 0xff) & ~0xff);
1290 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1293 static void *xxrealloc(int lineno, void *ptr, size_t size)
1295 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1296 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1299 static char *xxstrdup(int lineno, const char *str)
1301 char *ptr = xstrdup(str);
1302 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1305 static void xxfree(void *ptr)
1307 fdprintf(2, "free %p\n", ptr);
1310 # define xmalloc(s) xxmalloc(__LINE__, s)
1311 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1312 # define xstrdup(s) xxstrdup(__LINE__, s)
1313 # define free(p) xxfree(p)
1317 /* Syntax and runtime errors. They always abort scripts.
1318 * In interactive use they usually discard unparsed and/or unexecuted commands
1319 * and return to the prompt.
1320 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1323 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1324 # define syntax_error(lineno, msg) syntax_error(msg)
1325 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1326 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1327 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1328 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1331 static void die_if_script(void)
1333 if (!G_interactive_fd) {
1334 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1335 xfunc_error_retval = G.last_exitcode;
1340 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1345 bb_error_msg("hush.c:%u", lineno);
1348 bb_verror_msg(fmt, p, NULL);
1353 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1356 bb_error_msg("syntax error: %s", msg);
1358 bb_error_msg("syntax error");
1362 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1364 bb_error_msg("syntax error at '%s'", msg);
1368 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1370 bb_error_msg("syntax error: unterminated %s", s);
1371 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1375 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1377 char msg[2] = { ch, '\0' };
1378 syntax_error_unterm_str(lineno, msg);
1381 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1387 bb_error_msg("hush.c:%u", lineno);
1389 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1394 # undef msg_and_die_if_script
1395 # undef syntax_error
1396 # undef syntax_error_at
1397 # undef syntax_error_unterm_ch
1398 # undef syntax_error_unterm_str
1399 # undef syntax_error_unexpected_ch
1401 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1402 # define syntax_error(msg) syntax_error(__LINE__, msg)
1403 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1404 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1405 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1406 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1410 #if ENABLE_HUSH_INTERACTIVE
1411 static void cmdedit_update_prompt(void);
1413 # define cmdedit_update_prompt() ((void)0)
1417 /* Utility functions
1419 /* Replace each \x with x in place, return ptr past NUL. */
1420 static char *unbackslash(char *src)
1422 char *dst = src = strchrnul(src, '\\');
1426 if ((*dst++ = *src++) == '\0')
1432 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1453 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1454 v[count1 + count2] = NULL;
1457 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1461 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1463 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1464 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1467 #define add_strings_to_strings(strings, add, need_to_dup) \
1468 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1471 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1472 static char **add_string_to_strings(char **strings, char *add)
1477 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1480 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1482 char **ptr = add_string_to_strings(strings, add);
1483 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1486 #define add_string_to_strings(strings, add) \
1487 xx_add_string_to_strings(__LINE__, strings, add)
1490 static void free_strings(char **strings)
1504 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1508 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1518 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1522 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1528 /* fd was not open? */
1533 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1534 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1540 /* Manipulating the list of open FILEs */
1541 static FILE *remember_FILE(FILE *fp)
1544 struct FILE_list *n = xmalloc(sizeof(*n));
1545 n->next = G.FILE_list;
1549 close_on_exec_on(n->fd);
1553 static void fclose_and_forget(FILE *fp)
1555 struct FILE_list **pp = &G.FILE_list;
1557 struct FILE_list *cur = *pp;
1558 if (cur->fp == fp) {
1567 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1569 struct FILE_list *fl = G.FILE_list;
1572 /* We use it only on script files, they are all CLOEXEC */
1573 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1574 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1581 static void restore_redirected_FILEs(void)
1583 struct FILE_list *fl = G.FILE_list;
1585 int should_be = fileno(fl->fp);
1586 if (fl->fd != should_be) {
1587 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1588 xmove_fd(fl->fd, should_be);
1594 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1595 static void close_all_FILE_list(void)
1597 struct FILE_list *fl = G.FILE_list;
1599 /* fclose would also free FILE object.
1600 * It is disastrous if we share memory with a vforked parent.
1601 * I'm not sure we never come here after vfork.
1602 * Therefore just close fd, nothing more.
1604 /*fclose(fl->fp); - unsafe */
1610 static int fd_in_FILEs(int fd)
1612 struct FILE_list *fl = G.FILE_list;
1622 /* Helpers for setting new $n and restoring them back
1624 typedef struct save_arg_t {
1628 IF_HUSH_SET(smallint sv_g_malloced;)
1631 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1633 sv->sv_argv0 = argv[0];
1634 sv->sv_g_argv = G.global_argv;
1635 sv->sv_g_argc = G.global_argc;
1636 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1638 argv[0] = G.global_argv[0]; /* retain $0 */
1639 G.global_argv = argv;
1640 IF_HUSH_SET(G.global_args_malloced = 0;)
1642 G.global_argc = 1 + string_array_len(argv + 1);
1645 static void restore_G_args(save_arg_t *sv, char **argv)
1648 if (G.global_args_malloced) {
1649 /* someone ran "set -- arg1 arg2 ...", undo */
1650 char **pp = G.global_argv;
1651 while (*++pp) /* note: does not free $0 */
1653 free(G.global_argv);
1656 argv[0] = sv->sv_argv0;
1657 G.global_argv = sv->sv_g_argv;
1658 G.global_argc = sv->sv_g_argc;
1659 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1663 /* Basic theory of signal handling in shell
1664 * ========================================
1665 * This does not describe what hush does, rather, it is current understanding
1666 * what it _should_ do. If it doesn't, it's a bug.
1667 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1669 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1670 * is finished or backgrounded. It is the same in interactive and
1671 * non-interactive shells, and is the same regardless of whether
1672 * a user trap handler is installed or a shell special one is in effect.
1673 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1674 * backgrounds (i.e. stops) or kills all members of currently running
1677 * Wait builtin is interruptible by signals for which user trap is set
1678 * or by SIGINT in interactive shell.
1680 * Trap handlers will execute even within trap handlers. (right?)
1682 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1683 * except for handlers set to '' (empty string).
1685 * If job control is off, backgrounded commands ("cmd &")
1686 * have SIGINT, SIGQUIT set to SIG_IGN.
1688 * Commands which are run in command substitution ("`cmd`")
1689 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1691 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1692 * by the shell from its parent.
1694 * Signals which differ from SIG_DFL action
1695 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1698 * SIGTERM (interactive): ignore
1699 * SIGHUP (interactive):
1700 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1701 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1702 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1703 * that all pipe members are stopped. Try this in bash:
1704 * while :; do :; done - ^Z does not background it
1705 * (while :; do :; done) - ^Z backgrounds it
1706 * SIGINT (interactive): wait for last pipe, ignore the rest
1707 * of the command line, show prompt. NB: ^C does not send SIGINT
1708 * to interactive shell while shell is waiting for a pipe,
1709 * since shell is bg'ed (is not in foreground process group).
1710 * Example 1: this waits 5 sec, but does not execute ls:
1711 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1712 * Example 2: this does not wait and does not execute ls:
1713 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1714 * Example 3: this does not wait 5 sec, but executes ls:
1715 * "sleep 5; ls -l" + press ^C
1716 * Example 4: this does not wait and does not execute ls:
1717 * "sleep 5 & wait; ls -l" + press ^C
1719 * (What happens to signals which are IGN on shell start?)
1720 * (What happens with signal mask on shell start?)
1722 * Old implementation
1723 * ==================
1724 * We use in-kernel pending signal mask to determine which signals were sent.
1725 * We block all signals which we don't want to take action immediately,
1726 * i.e. we block all signals which need to have special handling as described
1727 * above, and all signals which have traps set.
1728 * After each pipe execution, we extract any pending signals via sigtimedwait()
1731 * unsigned special_sig_mask: a mask of such "special" signals
1732 * sigset_t blocked_set: current blocked signal set
1735 * clear bit in blocked_set unless it is also in special_sig_mask
1736 * "trap 'cmd' SIGxxx":
1737 * set bit in blocked_set (even if 'cmd' is '')
1738 * after [v]fork, if we plan to be a shell:
1739 * unblock signals with special interactive handling
1740 * (child shell is not interactive),
1741 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1742 * after [v]fork, if we plan to exec:
1743 * POSIX says fork clears pending signal mask in child - no need to clear it.
1744 * Restore blocked signal set to one inherited by shell just prior to exec.
1746 * Note: as a result, we do not use signal handlers much. The only uses
1747 * are to count SIGCHLDs
1748 * and to restore tty pgrp on signal-induced exit.
1751 * Standard says "When a subshell is entered, traps that are not being ignored
1752 * are set to the default actions". bash interprets it so that traps which
1753 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1755 * Problem: the above approach makes it unwieldy to catch signals while
1756 * we are in read builtin, or while we read commands from stdin:
1757 * masked signals are not visible!
1759 * New implementation
1760 * ==================
1761 * We record each signal we are interested in by installing signal handler
1762 * for them - a bit like emulating kernel pending signal mask in userspace.
1763 * We are interested in: signals which need to have special handling
1764 * as described above, and all signals which have traps set.
1765 * Signals are recorded in pending_set.
1766 * After each pipe execution, we extract any pending signals
1769 * unsigned special_sig_mask: a mask of shell-special signals.
1770 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1771 * char *traps[sig] if trap for sig is set (even if it's '').
1772 * sigset_t pending_set: set of sigs we received.
1775 * if sig is in special_sig_mask, set handler back to:
1776 * record_pending_signo, or to IGN if it's a tty stop signal
1777 * if sig is in fatal_sig_mask, set handler back to sigexit.
1778 * else: set handler back to SIG_DFL
1779 * "trap 'cmd' SIGxxx":
1780 * set handler to record_pending_signo.
1782 * set handler to SIG_IGN.
1783 * after [v]fork, if we plan to be a shell:
1784 * set signals with special interactive handling to SIG_DFL
1785 * (because child shell is not interactive),
1786 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1787 * after [v]fork, if we plan to exec:
1788 * POSIX says fork clears pending signal mask in child - no need to clear it.
1790 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1791 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1794 * Standard says "When a subshell is entered, traps that are not being ignored
1795 * are set to the default actions". bash interprets it so that traps which
1796 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1799 SPECIAL_INTERACTIVE_SIGS = 0
1804 SPECIAL_JOBSTOP_SIGS = 0
1813 static void record_pending_signo(int sig)
1815 sigaddset(&G.pending_set, sig);
1816 #if ENABLE_HUSH_FAST
1817 if (sig == SIGCHLD) {
1819 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1824 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1826 struct sigaction old_sa;
1828 /* We could use signal() to install handlers... almost:
1829 * except that we need to mask ALL signals while handlers run.
1830 * I saw signal nesting in strace, race window isn't small.
1831 * SA_RESTART is also needed, but in Linux, signal()
1832 * sets SA_RESTART too.
1834 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1835 /* sigfillset(&G.sa.sa_mask); - already done */
1836 /* G.sa.sa_flags = SA_RESTART; - already done */
1837 G.sa.sa_handler = handler;
1838 sigaction(sig, &G.sa, &old_sa);
1839 return old_sa.sa_handler;
1842 static void hush_exit(int exitcode) NORETURN;
1844 static void restore_ttypgrp_and__exit(void) NORETURN;
1845 static void restore_ttypgrp_and__exit(void)
1847 /* xfunc has failed! die die die */
1848 /* no EXIT traps, this is an escape hatch! */
1850 hush_exit(xfunc_error_retval);
1855 /* Needed only on some libc:
1856 * It was observed that on exit(), fgetc'ed buffered data
1857 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1858 * With the net effect that even after fork(), not vfork(),
1859 * exit() in NOEXECed applet in "sh SCRIPT":
1860 * noexec_applet_here
1861 * echo END_OF_SCRIPT
1862 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1863 * This makes "echo END_OF_SCRIPT" executed twice.
1864 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1865 * and in `cmd` handling.
1866 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1868 static void fflush_and__exit(void) NORETURN;
1869 static void fflush_and__exit(void)
1872 _exit(xfunc_error_retval);
1875 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1876 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1877 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1878 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1880 /* Restores tty foreground process group, and exits.
1881 * May be called as signal handler for fatal signal
1882 * (will resend signal to itself, producing correct exit state)
1883 * or called directly with -EXITCODE.
1884 * We also call it if xfunc is exiting.
1886 static void sigexit(int sig) NORETURN;
1887 static void sigexit(int sig)
1889 /* Careful: we can end up here after [v]fork. Do not restore
1890 * tty pgrp then, only top-level shell process does that */
1891 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1892 /* Disable all signals: job control, SIGPIPE, etc.
1893 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1895 sigprocmask_allsigs(SIG_BLOCK);
1896 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1899 /* Not a signal, just exit */
1903 kill_myself_with_sig(sig); /* does not return */
1907 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1908 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1912 static sighandler_t pick_sighandler(unsigned sig)
1914 sighandler_t handler = SIG_DFL;
1915 if (sig < sizeof(unsigned)*8) {
1916 unsigned sigmask = (1 << sig);
1920 if (G_fatal_sig_mask & sigmask)
1924 /* sig has special handling? */
1925 if (G.special_sig_mask & sigmask) {
1926 handler = record_pending_signo;
1927 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1928 * in order to ignore them: they will be raised
1929 * in an endless loop when we try to do some
1930 * terminal ioctls! We do have to _ignore_ these.
1932 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1939 /* Restores tty foreground process group, and exits. */
1940 static void hush_exit(int exitcode)
1942 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1943 save_history(G.line_input_state);
1947 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1949 /* argv[0] is unused */
1950 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
1952 G.exiting = 1; /* prevent EXIT trap recursion */
1953 /* Note: G_traps[0] is not cleared!
1954 * "trap" will still show it, if executed
1959 #if ENABLE_FEATURE_CLEAN_UP
1961 struct variable *cur_var;
1962 if (G.cwd != bb_msg_unknown)
1964 cur_var = G.top_var;
1966 struct variable *tmp = cur_var;
1967 if (!cur_var->max_len)
1968 free(cur_var->varstr);
1969 cur_var = cur_var->next;
1977 sigexit(- (exitcode & 0xff));
1984 //TODO: return a mask of ALL handled sigs?
1985 static int check_and_run_traps(void)
1992 if (sigisemptyset(&G.pending_set))
1997 if (sigismember(&G.pending_set, sig)) {
1998 sigdelset(&G.pending_set, sig);
2001 } while (sig < NSIG);
2004 if (G_traps && G_traps[sig]) {
2005 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
2006 if (G_traps[sig][0]) {
2007 /* We have user-defined handler */
2008 smalluint save_rcode;
2010 /* argv[0] is unused */
2011 argv[1] = xstrdup(G_traps[sig]);
2012 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
2014 save_rcode = G.last_exitcode;
2017 //FIXME: shouldn't it be set to 128 + sig instead?
2018 G.last_exitcode = save_rcode;
2020 } /* else: "" trap, ignoring signal */
2023 /* not a trap: special action */
2026 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2032 //TODO: why are we doing this? ash and dash don't do this,
2033 //they have no handler for SIGHUP at all,
2034 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2036 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2037 /* bash is observed to signal whole process groups,
2038 * not individual processes */
2039 for (job = G.job_list; job; job = job->next) {
2042 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2043 if (kill(- job->pgrp, SIGHUP) == 0)
2044 kill(- job->pgrp, SIGCONT);
2049 #if ENABLE_HUSH_FAST
2051 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2053 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2055 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2056 * This simplifies wait builtin a bit.
2060 default: /* ignored: */
2061 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2062 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2064 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2065 * Example: wait is not interrupted by TERM
2066 * in interactive shell, because TERM is ignored.
2075 static const char *get_cwd(int force)
2077 if (force || G.cwd == NULL) {
2078 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2079 * we must not try to free(bb_msg_unknown) */
2080 if (G.cwd == bb_msg_unknown)
2082 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2084 G.cwd = bb_msg_unknown;
2091 * Shell and environment variable support
2093 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2095 struct variable **pp;
2096 struct variable *cur;
2099 while ((cur = *pp) != NULL) {
2100 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2107 static const char* FAST_FUNC get_local_var_value(const char *name)
2109 struct variable **vpp;
2110 unsigned len = strlen(name);
2112 if (G.expanded_assignments) {
2113 char **cpp = G.expanded_assignments;
2116 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2117 return cp + len + 1;
2122 vpp = get_ptr_to_local_var(name, len);
2124 return (*vpp)->varstr + len + 1;
2126 if (strcmp(name, "PPID") == 0)
2127 return utoa(G.root_ppid);
2128 // bash compat: UID? EUID?
2129 #if ENABLE_HUSH_RANDOM_SUPPORT
2130 if (strcmp(name, "RANDOM") == 0)
2131 return utoa(next_random(&G.random_gen));
2136 /* str holds "NAME=VAL" and is expected to be malloced.
2137 * We take ownership of it.
2139 #define SETFLAG_EXPORT (1 << 0)
2140 #define SETFLAG_UNEXPORT (1 << 1)
2141 #define SETFLAG_MAKE_RO (1 << 2)
2142 #define SETFLAG_LOCAL_SHIFT 3
2143 static int set_local_var(char *str, unsigned flags)
2145 struct variable **var_pp;
2146 struct variable *cur;
2147 char *free_me = NULL;
2150 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2152 eq_sign = strchr(str, '=');
2153 if (!eq_sign) { /* not expected to ever happen? */
2158 name_len = eq_sign - str + 1; /* including '=' */
2159 #if ENABLE_HUSH_LINENO_VAR
2161 if (name_len == 7 && strncmp("LINENO", str, 6) == 0)
2162 G.lineno_var = NULL;
2166 var_pp = &G.top_var;
2167 while ((cur = *var_pp) != NULL) {
2168 if (strncmp(cur->varstr, str, name_len) != 0) {
2169 var_pp = &cur->next;
2173 /* We found an existing var with this name */
2174 if (cur->flg_read_only) {
2175 bb_error_msg("%s: readonly variable", str);
2177 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2178 //but export per se succeeds (does put the var in env). We don't mimic that.
2181 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2182 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2187 #if ENABLE_HUSH_LOCAL
2188 if (cur->func_nest_level < local_lvl) {
2189 /* New variable is declared as local,
2190 * and existing one is global, or local
2191 * from enclosing function.
2192 * Remove and save old one: */
2193 *var_pp = cur->next;
2194 cur->next = *G.shadowed_vars_pp;
2195 *G.shadowed_vars_pp = cur;
2196 /* bash 3.2.33(1) and exported vars:
2198 * # f() { local z=a; env | grep ^z; }
2204 if (cur->flg_export)
2205 flags |= SETFLAG_EXPORT;
2209 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2214 if (cur->max_len != 0) {
2215 if (cur->max_len >= strlen(str)) {
2216 /* This one is from startup env, reuse space */
2217 strcpy(cur->varstr, str);
2222 goto set_str_and_exp;
2224 /* max_len == 0 signifies "malloced" var, which we can
2225 * (and have to) free. But we can't free(cur->varstr) here:
2226 * if cur->flg_export is 1, it is in the environment.
2227 * We should either unsetenv+free, or wait until putenv,
2228 * then putenv(new)+free(old).
2230 free_me = cur->varstr;
2231 goto set_str_and_exp;
2234 /* Not found - create new variable struct */
2235 cur = xzalloc(sizeof(*cur));
2236 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2237 cur->next = *var_pp;
2243 #if !BB_MMU || ENABLE_HUSH_READONLY
2244 if (flags & SETFLAG_MAKE_RO) {
2245 cur->flg_read_only = 1;
2248 if (flags & SETFLAG_EXPORT)
2249 cur->flg_export = 1;
2250 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2251 cmdedit_update_prompt();
2252 #if ENABLE_HUSH_GETOPTS
2253 /* defoptindvar is a "OPTIND=..." constant string */
2254 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
2257 if (cur->flg_export) {
2258 if (flags & SETFLAG_UNEXPORT) {
2259 cur->flg_export = 0;
2260 /* unsetenv was already done */
2263 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2264 i = putenv(cur->varstr);
2265 /* only now we can free old exported malloced string */
2274 /* Used at startup and after each cd */
2275 static void set_pwd_var(unsigned flag)
2277 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2280 static int unset_local_var_len(const char *name, int name_len)
2282 struct variable *cur;
2283 struct variable **var_pp;
2286 return EXIT_SUCCESS;
2288 #if ENABLE_HUSH_GETOPTS
2289 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2292 #if ENABLE_HUSH_LINENO_VAR
2293 if (name_len == 6 && G.lineno_var && strncmp(name, "LINENO", 6) == 0)
2294 G.lineno_var = NULL;
2297 var_pp = &G.top_var;
2298 while ((cur = *var_pp) != NULL) {
2299 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2300 if (cur->flg_read_only) {
2301 bb_error_msg("%s: readonly variable", name);
2302 return EXIT_FAILURE;
2304 *var_pp = cur->next;
2305 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2306 bb_unsetenv(cur->varstr);
2307 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2308 cmdedit_update_prompt();
2312 return EXIT_SUCCESS;
2314 var_pp = &cur->next;
2316 return EXIT_SUCCESS;
2319 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2320 static int unset_local_var(const char *name)
2322 return unset_local_var_len(name, strlen(name));
2326 static void unset_vars(char **strings)
2334 const char *eq = strchrnul(*v, '=');
2335 unset_local_var_len(*v, (int)(eq - *v));
2341 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
2342 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2344 char *var = xasprintf("%s=%s", name, val);
2345 set_local_var(var, /*flag:*/ 0);
2351 * Helpers for "var1=val1 var2=val2 cmd" feature
2353 static void add_vars(struct variable *var)
2355 struct variable *next;
2359 var->next = G.top_var;
2361 if (var->flg_export) {
2362 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2363 putenv(var->varstr);
2365 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2371 static struct variable *set_vars_and_save_old(char **strings)
2374 struct variable *old = NULL;
2380 struct variable *var_p;
2381 struct variable **var_pp;
2384 eq = strchr(*s, '=');
2386 var_pp = get_ptr_to_local_var(*s, eq - *s);
2389 if (var_p->flg_read_only) {
2391 bb_error_msg("%s: readonly variable", *s);
2393 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2394 * If VAR is readonly, leaving it in the list
2395 * after asssignment error (msg above)
2396 * causes doubled error message later, on unset.
2398 debug_printf_env("removing/freeing '%s' element\n", *s);
2401 do { *p = p[1]; p++; } while (*p);
2404 /* Remove variable from global linked list */
2405 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2406 *var_pp = var_p->next;
2407 /* Add it to returned list */
2411 set_local_var(*s, SETFLAG_EXPORT);
2423 static void reinit_unicode_for_hush(void)
2425 /* Unicode support should be activated even if LANG is set
2426 * _during_ shell execution, not only if it was set when
2427 * shell was started. Therefore, re-check LANG every time:
2429 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2430 || ENABLE_UNICODE_USING_LOCALE
2432 const char *s = get_local_var_value("LC_ALL");
2433 if (!s) s = get_local_var_value("LC_CTYPE");
2434 if (!s) s = get_local_var_value("LANG");
2440 * in_str support (strings, and "strings" read from files).
2443 #if ENABLE_HUSH_INTERACTIVE
2444 /* To test correct lineedit/interactive behavior, type from command line:
2450 * It exercises a lot of corner cases.
2452 static void cmdedit_update_prompt(void)
2454 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2455 G.PS1 = get_local_var_value("PS1");
2458 G.PS2 = get_local_var_value("PS2");
2465 static const char *setup_prompt_string(int promptmode)
2467 const char *prompt_str;
2468 debug_printf("setup_prompt_string %d ", promptmode);
2469 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2470 /* Set up the prompt */
2471 if (promptmode == 0) { /* PS1 */
2473 /* bash uses $PWD value, even if it is set by user.
2474 * It uses current dir only if PWD is unset.
2475 * We always use current dir. */
2476 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2481 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2482 debug_printf("prompt_str '%s'\n", prompt_str);
2485 static int get_user_input(struct in_str *i)
2488 const char *prompt_str;
2490 prompt_str = setup_prompt_string(i->promptmode);
2491 # if ENABLE_FEATURE_EDITING
2493 reinit_unicode_for_hush();
2494 if (G.flag_SIGINT) {
2495 /* There was ^C'ed, make it look prettier: */
2499 /* buglet: SIGINT will not make new prompt to appear _at once_,
2500 * only after <Enter>. (^C works immediately) */
2501 r = read_line_input(G.line_input_state, prompt_str,
2502 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2504 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2507 check_and_run_traps();
2508 if (r != 0 && !G.flag_SIGINT)
2510 /* ^C or SIGINT: repeat */
2511 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2512 write(STDOUT_FILENO, "^C", 2);
2513 G.last_exitcode = 128 + SIGINT;
2516 /* EOF/error detected */
2518 i->peek_buf[0] = r = EOF;
2521 i->p = G.user_input_buf;
2522 return (unsigned char)*i->p++;
2526 if (i->last_char == '\0' || i->last_char == '\n') {
2527 /* Why check_and_run_traps here? Try this interactively:
2528 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2529 * $ <[enter], repeatedly...>
2530 * Without check_and_run_traps, handler never runs.
2532 check_and_run_traps();
2533 fputs(prompt_str, stdout);
2536 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2538 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2539 * no ^C masking happens during fgetc, no special code for ^C:
2540 * it generates SIGINT as usual.
2542 check_and_run_traps();
2544 G.last_exitcode = 128 + SIGINT;
2551 /* This is the magic location that prints prompts
2552 * and gets data back from the user */
2553 static int fgetc_interactive(struct in_str *i)
2556 /* If it's interactive stdin, get new line. */
2557 if (G_interactive_fd && i->file == stdin) {
2558 /* Returns first char (or EOF), the rest is in i->p[] */
2559 ch = get_user_input(i);
2560 i->promptmode = 1; /* PS2 */
2562 /* Not stdin: script file, sourced file, etc */
2563 do ch = fgetc(i->file); while (ch == '\0');
2568 static inline int fgetc_interactive(struct in_str *i)
2571 do ch = fgetc(i->file); while (ch == '\0');
2574 #endif /* INTERACTIVE */
2576 static int i_getch(struct in_str *i)
2581 /* string-based in_str */
2582 ch = (unsigned char)*i->p;
2591 /* FILE-based in_str */
2593 #if ENABLE_FEATURE_EDITING
2594 /* This can be stdin, check line editing char[] buffer */
2595 if (i->p && *i->p != '\0') {
2596 ch = (unsigned char)*i->p++;
2600 /* peek_buf[] is an int array, not char. Can contain EOF. */
2601 ch = i->peek_buf[0];
2603 int ch2 = i->peek_buf[1];
2604 i->peek_buf[0] = ch2;
2605 if (ch2 == 0) /* very likely, avoid redundant write */
2611 ch = fgetc_interactive(i);
2613 debug_printf("file_get: got '%c' %d\n", ch, ch);
2615 #if ENABLE_HUSH_LINENO_VAR
2618 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2624 static int i_peek(struct in_str *i)
2629 /* string-based in_str */
2630 /* Doesn't report EOF on NUL. None of the callers care. */
2631 return (unsigned char)*i->p;
2634 /* FILE-based in_str */
2636 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2637 /* This can be stdin, check line editing char[] buffer */
2638 if (i->p && *i->p != '\0')
2639 return (unsigned char)*i->p;
2641 /* peek_buf[] is an int array, not char. Can contain EOF. */
2642 ch = i->peek_buf[0];
2646 /* Need to get a new char */
2647 ch = fgetc_interactive(i);
2648 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2650 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2651 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2657 i->peek_buf[0] = ch;
2658 /*i->peek_buf[1] = 0; - already is */
2662 /* Only ever called if i_peek() was called, and did not return EOF.
2663 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2664 * not end-of-line. Therefore we never need to read a new editing line here.
2666 static int i_peek2(struct in_str *i)
2670 /* There are two cases when i->p[] buffer exists.
2671 * (1) it's a string in_str.
2672 * (2) It's a file, and we have a saved line editing buffer.
2673 * In both cases, we know that i->p[0] exists and not NUL, and
2674 * the peek2 result is in i->p[1].
2677 return (unsigned char)i->p[1];
2679 /* Now we know it is a file-based in_str. */
2681 /* peek_buf[] is an int array, not char. Can contain EOF. */
2682 /* Is there 2nd char? */
2683 ch = i->peek_buf[1];
2685 /* We did not read it yet, get it now */
2686 do ch = fgetc(i->file); while (ch == '\0');
2687 i->peek_buf[1] = ch;
2690 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2694 static void setup_file_in_str(struct in_str *i, FILE *f)
2696 memset(i, 0, sizeof(*i));
2697 /* i->promptmode = 0; - PS1 (memset did it) */
2702 static void setup_string_in_str(struct in_str *i, const char *s)
2704 memset(i, 0, sizeof(*i));
2705 /* i->promptmode = 0; - PS1 (memset did it) */
2706 /*i->file = NULL */;
2714 #define B_CHUNK (32 * sizeof(char*))
2716 static void o_reset_to_empty_unquoted(o_string *o)
2719 o->has_quoted_part = 0;
2724 static void o_free(o_string *o)
2727 memset(o, 0, sizeof(*o));
2730 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2735 static void o_grow_by(o_string *o, int len)
2737 if (o->length + len > o->maxlen) {
2738 o->maxlen += (2 * len) | (B_CHUNK-1);
2739 o->data = xrealloc(o->data, 1 + o->maxlen);
2743 static void o_addchr(o_string *o, int ch)
2745 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2746 if (o->length < o->maxlen) {
2747 /* likely. avoid o_grow_by() call */
2749 o->data[o->length] = ch;
2751 o->data[o->length] = '\0';
2759 /* Valid only if we know o_string is not empty */
2760 static void o_delchr(o_string *o)
2763 o->data[o->length] = '\0';
2767 static void o_addblock(o_string *o, const char *str, int len)
2770 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2774 static void o_addstr(o_string *o, const char *str)
2776 o_addblock(o, str, strlen(str));
2780 static void nommu_addchr(o_string *o, int ch)
2786 # define nommu_addchr(o, str) ((void)0)
2789 static void o_addstr_with_NUL(o_string *o, const char *str)
2791 o_addblock(o, str, strlen(str) + 1);
2795 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2796 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2797 * Apparently, on unquoted $v bash still does globbing
2798 * ("v='*.txt'; echo $v" prints all .txt files),
2799 * but NOT brace expansion! Thus, there should be TWO independent
2800 * quoting mechanisms on $v expansion side: one protects
2801 * $v from brace expansion, and other additionally protects "$v" against globbing.
2802 * We have only second one.
2805 #if ENABLE_HUSH_BRACE_EXPANSION
2806 # define MAYBE_BRACES "{}"
2808 # define MAYBE_BRACES ""
2811 /* My analysis of quoting semantics tells me that state information
2812 * is associated with a destination, not a source.
2814 static void o_addqchr(o_string *o, int ch)
2817 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2822 o->data[o->length] = '\\';
2825 o->data[o->length] = ch;
2827 o->data[o->length] = '\0';
2830 static void o_addQchr(o_string *o, int ch)
2833 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2834 && strchr("*?[\\" MAYBE_BRACES, ch)
2837 o->data[o->length] = '\\';
2841 o->data[o->length] = ch;
2843 o->data[o->length] = '\0';
2846 static void o_addqblock(o_string *o, const char *str, int len)
2851 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2852 if (ordinary_cnt > len) /* paranoia */
2854 o_addblock(o, str, ordinary_cnt);
2855 if (ordinary_cnt == len)
2856 return; /* NUL is already added by o_addblock */
2857 str += ordinary_cnt;
2858 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2862 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2864 o->data[o->length] = '\\';
2868 o->data[o->length] = ch;
2871 o->data[o->length] = '\0';
2874 static void o_addQblock(o_string *o, const char *str, int len)
2876 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2877 o_addblock(o, str, len);
2880 o_addqblock(o, str, len);
2883 static void o_addQstr(o_string *o, const char *str)
2885 o_addQblock(o, str, strlen(str));
2888 /* A special kind of o_string for $VAR and `cmd` expansion.
2889 * It contains char* list[] at the beginning, which is grown in 16 element
2890 * increments. Actual string data starts at the next multiple of 16 * (char*).
2891 * list[i] contains an INDEX (int!) into this string data.
2892 * It means that if list[] needs to grow, data needs to be moved higher up
2893 * but list[i]'s need not be modified.
2894 * NB: remembering how many list[i]'s you have there is crucial.
2895 * o_finalize_list() operation post-processes this structure - calculates
2896 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2898 #if DEBUG_EXPAND || DEBUG_GLOB
2899 static void debug_print_list(const char *prefix, o_string *o, int n)
2901 char **list = (char**)o->data;
2902 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2906 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2907 prefix, list, n, string_start, o->length, o->maxlen,
2908 !!(o->o_expflags & EXP_FLAG_GLOB),
2910 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2913 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2914 o->data + (int)(uintptr_t)list[i] + string_start,
2915 o->data + (int)(uintptr_t)list[i] + string_start);
2919 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2921 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2925 # define debug_print_list(prefix, o, n) ((void)0)
2928 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2929 * in list[n] so that it points past last stored byte so far.
2930 * It returns n+1. */
2931 static int o_save_ptr_helper(o_string *o, int n)
2933 char **list = (char**)o->data;
2937 if (!o->has_empty_slot) {
2938 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2939 string_len = o->length - string_start;
2940 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2941 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2942 /* list[n] points to string_start, make space for 16 more pointers */
2943 o->maxlen += 0x10 * sizeof(list[0]);
2944 o->data = xrealloc(o->data, o->maxlen + 1);
2945 list = (char**)o->data;
2946 memmove(list + n + 0x10, list + n, string_len);
2947 o->length += 0x10 * sizeof(list[0]);
2949 debug_printf_list("list[%d]=%d string_start=%d\n",
2950 n, string_len, string_start);
2953 /* We have empty slot at list[n], reuse without growth */
2954 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2955 string_len = o->length - string_start;
2956 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2957 n, string_len, string_start);
2958 o->has_empty_slot = 0;
2960 o->has_quoted_part = 0;
2961 list[n] = (char*)(uintptr_t)string_len;
2965 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2966 static int o_get_last_ptr(o_string *o, int n)
2968 char **list = (char**)o->data;
2969 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2971 return ((int)(uintptr_t)list[n-1]) + string_start;
2974 #if ENABLE_HUSH_BRACE_EXPANSION
2975 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2976 * first, it processes even {a} (no commas), second,
2977 * I didn't manage to make it return strings when they don't match
2978 * existing files. Need to re-implement it.
2982 static int glob_needed(const char *s)
2991 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2997 /* Return pointer to next closing brace or to comma */
2998 static const char *next_brace_sub(const char *cp)
3002 while (*cp != '\0') {
3009 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3015 return *cp != '\0' ? cp : NULL;
3017 /* Recursive brace globber. Note: may garble pattern[]. */
3018 static int glob_brace(char *pattern, o_string *o, int n)
3020 char *new_pattern_buf;
3027 debug_printf_glob("glob_brace('%s')\n", pattern);
3033 if (*begin == '{') {
3034 /* Find the first sub-pattern and at the same time
3035 * find the rest after the closing brace */
3036 next = next_brace_sub(begin);
3038 /* An illegal expression */
3042 /* "{abc}" with no commas - illegal
3043 * brace expr, disregard and skip it */
3049 if (*begin == '\\' && begin[1] != '\0')
3053 debug_printf_glob("begin:%s\n", begin);
3054 debug_printf_glob("next:%s\n", next);
3056 /* Now find the end of the whole brace expression */
3058 while (*rest != '}') {
3059 rest = next_brace_sub(rest);
3061 /* An illegal expression */
3064 debug_printf_glob("rest:%s\n", rest);
3066 rest_len = strlen(++rest) + 1;
3068 /* We are sure the brace expression is well-formed */
3070 /* Allocate working buffer large enough for our work */
3071 new_pattern_buf = xmalloc(strlen(pattern));
3073 /* We have a brace expression. BEGIN points to the opening {,
3074 * NEXT points past the terminator of the first element, and REST
3075 * points past the final }. We will accumulate result names from
3076 * recursive runs for each brace alternative in the buffer using
3081 /* Construct the new glob expression */
3084 mempcpy(new_pattern_buf,
3085 /* We know the prefix for all sub-patterns */
3086 pattern, begin - pattern),
3090 /* Note: glob_brace() may garble new_pattern_buf[].
3091 * That's why we re-copy prefix every time (1st memcpy above).
3093 n = glob_brace(new_pattern_buf, o, n);
3095 /* We saw the last entry */
3099 next = next_brace_sub(next);
3101 free(new_pattern_buf);
3109 memset(&globdata, 0, sizeof(globdata));
3110 gr = glob(pattern, 0, NULL, &globdata);
3111 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3113 if (gr == GLOB_NOMATCH) {
3114 globfree(&globdata);
3115 /* NB: garbles parameter */
3116 unbackslash(pattern);
3117 o_addstr_with_NUL(o, pattern);
3118 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3119 return o_save_ptr_helper(o, n);
3121 if (gr == GLOB_NOSPACE)
3122 bb_error_msg_and_die(bb_msg_memory_exhausted);
3123 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3124 * but we didn't specify it. Paranoia again. */
3125 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3127 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3128 char **argv = globdata.gl_pathv;
3130 o_addstr_with_NUL(o, *argv);
3131 n = o_save_ptr_helper(o, n);
3137 globfree(&globdata);
3141 /* Performs globbing on last list[],
3142 * saving each result as a new list[].
3144 static int perform_glob(o_string *o, int n)
3146 char *pattern, *copy;
3148 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3150 return o_save_ptr_helper(o, n);
3151 pattern = o->data + o_get_last_ptr(o, n);
3152 debug_printf_glob("glob pattern '%s'\n", pattern);
3153 if (!glob_needed(pattern)) {
3154 /* unbackslash last string in o in place, fix length */
3155 o->length = unbackslash(pattern) - o->data;
3156 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3157 return o_save_ptr_helper(o, n);
3160 copy = xstrdup(pattern);
3161 /* "forget" pattern in o */
3162 o->length = pattern - o->data;
3163 n = glob_brace(copy, o, n);
3166 debug_print_list("perform_glob returning", o, n);
3170 #else /* !HUSH_BRACE_EXPANSION */
3173 static int glob_needed(const char *s)
3182 if (*s == '*' || *s == '[' || *s == '?')
3188 /* Performs globbing on last list[],
3189 * saving each result as a new list[].
3191 static int perform_glob(o_string *o, int n)
3197 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3199 return o_save_ptr_helper(o, n);
3200 pattern = o->data + o_get_last_ptr(o, n);
3201 debug_printf_glob("glob pattern '%s'\n", pattern);
3202 if (!glob_needed(pattern)) {
3204 /* unbackslash last string in o in place, fix length */
3205 o->length = unbackslash(pattern) - o->data;
3206 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3207 return o_save_ptr_helper(o, n);
3210 memset(&globdata, 0, sizeof(globdata));
3211 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3212 * If we glob "*.\*" and don't find anything, we need
3213 * to fall back to using literal "*.*", but GLOB_NOCHECK
3214 * will return "*.\*"!
3216 gr = glob(pattern, 0, NULL, &globdata);
3217 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3219 if (gr == GLOB_NOMATCH) {
3220 globfree(&globdata);
3223 if (gr == GLOB_NOSPACE)
3224 bb_error_msg_and_die(bb_msg_memory_exhausted);
3225 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3226 * but we didn't specify it. Paranoia again. */
3227 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3229 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3230 char **argv = globdata.gl_pathv;
3231 /* "forget" pattern in o */
3232 o->length = pattern - o->data;
3234 o_addstr_with_NUL(o, *argv);
3235 n = o_save_ptr_helper(o, n);
3241 globfree(&globdata);
3243 debug_print_list("perform_glob returning", o, n);
3247 #endif /* !HUSH_BRACE_EXPANSION */
3249 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3250 * Otherwise, just finish current list[] and start new */
3251 static int o_save_ptr(o_string *o, int n)
3253 if (o->o_expflags & EXP_FLAG_GLOB) {
3254 /* If o->has_empty_slot, list[n] was already globbed
3255 * (if it was requested back then when it was filled)
3256 * so don't do that again! */
3257 if (!o->has_empty_slot)
3258 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3260 return o_save_ptr_helper(o, n);
3263 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3264 static char **o_finalize_list(o_string *o, int n)
3269 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3271 debug_print_list("finalized", o, n);
3272 debug_printf_expand("finalized n:%d\n", n);
3273 list = (char**)o->data;
3274 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3278 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3283 static void free_pipe_list(struct pipe *pi);
3285 /* Returns pi->next - next pipe in the list */
3286 static struct pipe *free_pipe(struct pipe *pi)
3291 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3292 for (i = 0; i < pi->num_cmds; i++) {
3293 struct command *command;
3294 struct redir_struct *r, *rnext;
3296 command = &pi->cmds[i];
3297 debug_printf_clean(" command %d:\n", i);
3298 if (command->argv) {
3302 for (a = 0, p = command->argv; *p; a++, p++) {
3303 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3306 free_strings(command->argv);
3307 //command->argv = NULL;
3309 /* not "else if": on syntax error, we may have both! */
3310 if (command->group) {
3311 debug_printf_clean(" begin group (cmd_type:%d)\n",
3313 free_pipe_list(command->group);
3314 debug_printf_clean(" end group\n");
3315 //command->group = NULL;
3317 /* else is crucial here.
3318 * If group != NULL, child_func is meaningless */
3319 #if ENABLE_HUSH_FUNCTIONS
3320 else if (command->child_func) {
3321 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3322 command->child_func->parent_cmd = NULL;
3326 free(command->group_as_string);
3327 //command->group_as_string = NULL;
3329 for (r = command->redirects; r; r = rnext) {
3330 debug_printf_clean(" redirect %d%s",
3331 r->rd_fd, redir_table[r->rd_type].descrip);
3332 /* guard against the case >$FOO, where foo is unset or blank */
3333 if (r->rd_filename) {
3334 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3335 free(r->rd_filename);
3336 //r->rd_filename = NULL;
3338 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3342 //command->redirects = NULL;
3344 free(pi->cmds); /* children are an array, they get freed all at once */
3348 //pi->cmdtext = NULL;
3356 static void free_pipe_list(struct pipe *pi)
3360 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3362 debug_printf_clean("pipe followup code %d\n", pi->followup);
3368 /*** Parsing routines ***/
3370 #ifndef debug_print_tree
3371 static void debug_print_tree(struct pipe *pi, int lvl)
3373 static const char *const PIPE[] = {
3379 static const char *RES[] = {
3380 [RES_NONE ] = "NONE" ,
3383 [RES_THEN ] = "THEN" ,
3384 [RES_ELIF ] = "ELIF" ,
3385 [RES_ELSE ] = "ELSE" ,
3388 # if ENABLE_HUSH_LOOPS
3389 [RES_FOR ] = "FOR" ,
3390 [RES_WHILE] = "WHILE",
3391 [RES_UNTIL] = "UNTIL",
3393 [RES_DONE ] = "DONE" ,
3395 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3398 # if ENABLE_HUSH_CASE
3399 [RES_CASE ] = "CASE" ,
3400 [RES_CASE_IN ] = "CASE_IN" ,
3401 [RES_MATCH] = "MATCH",
3402 [RES_CASE_BODY] = "CASE_BODY",
3403 [RES_ESAC ] = "ESAC" ,
3405 [RES_XXXX ] = "XXXX" ,
3406 [RES_SNTX ] = "SNTX" ,
3408 static const char *const CMDTYPE[] = {
3412 # if ENABLE_HUSH_FUNCTIONS
3421 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3424 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3426 pi->followup, PIPE[pi->followup]
3429 while (prn < pi->num_cmds) {
3430 struct command *command = &pi->cmds[prn];
3431 char **argv = command->argv;
3433 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3435 command->assignment_cnt);
3436 #if ENABLE_HUSH_LINENO_VAR
3437 fdprintf(2, " LINENO:%u", command->lineno);
3439 if (command->group) {
3440 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3441 CMDTYPE[command->cmd_type],
3444 , " group_as_string:", command->group_as_string
3449 debug_print_tree(command->group, lvl+1);
3453 if (argv) while (*argv) {
3454 fdprintf(2, " '%s'", *argv);
3464 #endif /* debug_print_tree */
3466 static struct pipe *new_pipe(void)
3469 pi = xzalloc(sizeof(struct pipe));
3470 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3474 /* Command (member of a pipe) is complete, or we start a new pipe
3475 * if ctx->command is NULL.
3476 * No errors possible here.
3478 static int done_command(struct parse_context *ctx)
3480 /* The command is really already in the pipe structure, so
3481 * advance the pipe counter and make a new, null command. */
3482 struct pipe *pi = ctx->pipe;
3483 struct command *command = ctx->command;
3485 #if 0 /* Instead we emit error message at run time */
3486 if (ctx->pending_redirect) {
3487 /* For example, "cmd >" (no filename to redirect to) */
3488 syntax_error("invalid redirect");
3489 ctx->pending_redirect = NULL;
3494 if (IS_NULL_CMD(command)) {
3495 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3499 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3500 //debug_print_tree(ctx->list_head, 20);
3502 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3505 /* Only real trickiness here is that the uncommitted
3506 * command structure is not counted in pi->num_cmds. */
3507 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3508 ctx->command = command = &pi->cmds[pi->num_cmds];
3510 memset(command, 0, sizeof(*command));
3511 #if ENABLE_HUSH_LINENO_VAR
3512 command->lineno = G.lineno;
3513 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
3515 return pi->num_cmds; /* used only for 0/nonzero check */
3518 static void done_pipe(struct parse_context *ctx, pipe_style type)
3522 debug_printf_parse("done_pipe entered, followup %d\n", type);
3523 /* Close previous command */
3524 not_null = done_command(ctx);
3526 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3527 ctx->ctx_inverted = 0;
3528 ctx->pipe->res_word = ctx->ctx_res_w;
3530 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3531 /* Necessary since && and || have precedence over &:
3532 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3533 * in a backgrounded subshell.
3536 struct command *command;
3538 /* Is this actually this construct, all pipes end with && or ||? */
3539 pi = ctx->list_head;
3540 while (pi != ctx->pipe) {
3541 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3546 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3547 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3548 pi = xzalloc(sizeof(*pi));
3549 pi->followup = PIPE_BG;
3551 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3552 command = &pi->cmds[0];
3553 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3554 command->cmd_type = CMD_NORMAL;
3555 command->group = ctx->list_head;
3557 command->group_as_string = xstrndup(
3558 ctx->as_string.data,
3559 ctx->as_string.length - 1 /* do not copy last char, "&" */
3562 /* Replace all pipes in ctx with one newly created */
3563 ctx->list_head = ctx->pipe = pi;
3566 ctx->pipe->followup = type;
3569 /* Without this check, even just <enter> on command line generates
3570 * tree of three NOPs (!). Which is harmless but annoying.
3571 * IOW: it is safe to do it unconditionally. */
3574 || ctx->ctx_res_w == RES_FI
3576 #if ENABLE_HUSH_LOOPS
3577 || ctx->ctx_res_w == RES_DONE
3578 || ctx->ctx_res_w == RES_FOR
3579 || ctx->ctx_res_w == RES_IN
3581 #if ENABLE_HUSH_CASE
3582 || ctx->ctx_res_w == RES_ESAC
3586 debug_printf_parse("done_pipe: adding new pipe: "
3587 "not_null:%d ctx->ctx_res_w:%d\n",
3588 not_null, ctx->ctx_res_w);
3590 ctx->pipe->next = new_p;
3592 /* RES_THEN, RES_DO etc are "sticky" -
3593 * they remain set for pipes inside if/while.
3594 * This is used to control execution.
3595 * RES_FOR and RES_IN are NOT sticky (needed to support
3596 * cases where variable or value happens to match a keyword):
3598 #if ENABLE_HUSH_LOOPS
3599 if (ctx->ctx_res_w == RES_FOR
3600 || ctx->ctx_res_w == RES_IN)
3601 ctx->ctx_res_w = RES_NONE;
3603 #if ENABLE_HUSH_CASE
3604 if (ctx->ctx_res_w == RES_MATCH)
3605 ctx->ctx_res_w = RES_CASE_BODY;
3606 if (ctx->ctx_res_w == RES_CASE)
3607 ctx->ctx_res_w = RES_CASE_IN;
3609 ctx->command = NULL; /* trick done_command below */
3610 /* Create the memory for command, roughly:
3611 * ctx->pipe->cmds = new struct command;
3612 * ctx->command = &ctx->pipe->cmds[0];
3615 //debug_print_tree(ctx->list_head, 10);
3617 debug_printf_parse("done_pipe return\n");
3620 static void initialize_context(struct parse_context *ctx)
3622 memset(ctx, 0, sizeof(*ctx));
3623 ctx->pipe = ctx->list_head = new_pipe();
3624 /* Create the memory for command, roughly:
3625 * ctx->pipe->cmds = new struct command;
3626 * ctx->command = &ctx->pipe->cmds[0];
3631 /* If a reserved word is found and processed, parse context is modified
3632 * and 1 is returned.
3635 struct reserved_combo {
3638 unsigned char assignment_flag;
3642 FLAG_END = (1 << RES_NONE ),
3644 FLAG_IF = (1 << RES_IF ),
3645 FLAG_THEN = (1 << RES_THEN ),
3646 FLAG_ELIF = (1 << RES_ELIF ),
3647 FLAG_ELSE = (1 << RES_ELSE ),
3648 FLAG_FI = (1 << RES_FI ),
3650 # if ENABLE_HUSH_LOOPS
3651 FLAG_FOR = (1 << RES_FOR ),
3652 FLAG_WHILE = (1 << RES_WHILE),
3653 FLAG_UNTIL = (1 << RES_UNTIL),
3654 FLAG_DO = (1 << RES_DO ),
3655 FLAG_DONE = (1 << RES_DONE ),
3656 FLAG_IN = (1 << RES_IN ),
3658 # if ENABLE_HUSH_CASE
3659 FLAG_MATCH = (1 << RES_MATCH),
3660 FLAG_ESAC = (1 << RES_ESAC ),
3662 FLAG_START = (1 << RES_XXXX ),
3665 static const struct reserved_combo* match_reserved_word(o_string *word)
3667 /* Mostly a list of accepted follow-up reserved words.
3668 * FLAG_END means we are done with the sequence, and are ready
3669 * to turn the compound list into a command.
3670 * FLAG_START means the word must start a new compound list.
3672 static const struct reserved_combo reserved_list[] = {
3674 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3675 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3676 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3677 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3678 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3679 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3681 # if ENABLE_HUSH_LOOPS
3682 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3683 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3684 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3685 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3686 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3687 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3689 # if ENABLE_HUSH_CASE
3690 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3691 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3694 const struct reserved_combo *r;
3696 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3697 if (strcmp(word->data, r->literal) == 0)
3702 /* Return NULL: not a keyword, else: keyword
3704 static const struct reserved_combo* reserved_word(o_string *word, struct parse_context *ctx)
3706 # if ENABLE_HUSH_CASE
3707 static const struct reserved_combo reserved_match = {
3708 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3711 const struct reserved_combo *r;
3713 if (word->has_quoted_part)
3715 r = match_reserved_word(word);
3717 return r; /* NULL */
3719 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3720 # if ENABLE_HUSH_CASE
3721 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3722 /* "case word IN ..." - IN part starts first MATCH part */
3723 r = &reserved_match;
3726 if (r->flag == 0) { /* '!' */
3727 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3728 syntax_error("! ! command");
3729 ctx->ctx_res_w = RES_SNTX;
3731 ctx->ctx_inverted = 1;
3734 if (r->flag & FLAG_START) {
3735 struct parse_context *old;
3737 old = xmemdup(ctx, sizeof(*ctx));
3738 debug_printf_parse("push stack %p\n", old);
3739 initialize_context(ctx);
3741 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3742 syntax_error_at(word->data);
3743 ctx->ctx_res_w = RES_SNTX;
3746 /* "{...} fi" is ok. "{...} if" is not
3748 * if { echo foo; } then { echo bar; } fi */
3749 if (ctx->command->group)
3750 done_pipe(ctx, PIPE_SEQ);
3753 ctx->ctx_res_w = r->res;
3754 ctx->old_flag = r->flag;
3755 word->o_assignment = r->assignment_flag;
3756 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3758 if (ctx->old_flag & FLAG_END) {
3759 struct parse_context *old;
3761 done_pipe(ctx, PIPE_SEQ);
3762 debug_printf_parse("pop stack %p\n", ctx->stack);
3764 old->command->group = ctx->list_head;
3765 old->command->cmd_type = CMD_NORMAL;
3767 /* At this point, the compound command's string is in
3768 * ctx->as_string... except for the leading keyword!
3769 * Consider this example: "echo a | if true; then echo a; fi"
3770 * ctx->as_string will contain "true; then echo a; fi",
3771 * with "if " remaining in old->as_string!
3775 int len = old->as_string.length;
3776 /* Concatenate halves */
3777 o_addstr(&old->as_string, ctx->as_string.data);
3778 o_free_unsafe(&ctx->as_string);
3779 /* Find where leading keyword starts in first half */
3780 str = old->as_string.data + len;
3781 if (str > old->as_string.data)
3782 str--; /* skip whitespace after keyword */
3783 while (str > old->as_string.data && isalpha(str[-1]))
3785 /* Ugh, we're done with this horrid hack */
3786 old->command->group_as_string = xstrdup(str);
3787 debug_printf_parse("pop, remembering as:'%s'\n",
3788 old->command->group_as_string);
3791 *ctx = *old; /* physical copy */
3796 #endif /* HAS_KEYWORDS */
3798 /* Word is complete, look at it and update parsing context.
3799 * Normal return is 0. Syntax errors return 1.
3800 * Note: on return, word is reset, but not o_free'd!
3802 static int done_word(o_string *word, struct parse_context *ctx)
3804 struct command *command = ctx->command;
3806 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3807 if (word->length == 0 && !word->has_quoted_part) {
3808 debug_printf_parse("done_word return 0: true null, ignored\n");
3812 if (ctx->pending_redirect) {
3813 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3814 * only if run as "bash", not "sh" */
3815 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3817 * ...the word that follows the redirection operator
3818 * shall be subjected to tilde expansion, parameter expansion,
3819 * command substitution, arithmetic expansion, and quote
3820 * removal. Pathname expansion shall not be performed
3821 * on the word by a non-interactive shell; an interactive
3822 * shell may perform it, but shall do so only when
3823 * the expansion would result in one word."
3825 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3826 /* Cater for >\file case:
3827 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3828 * Same with heredocs:
3829 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3831 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3832 unbackslash(ctx->pending_redirect->rd_filename);
3833 /* Is it <<"HEREDOC"? */
3834 if (word->has_quoted_part) {
3835 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3838 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3839 ctx->pending_redirect = NULL;
3842 # if ENABLE_HUSH_CASE
3843 if (ctx->ctx_dsemicolon
3844 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3846 /* already done when ctx_dsemicolon was set to 1: */
3847 /* ctx->ctx_res_w = RES_MATCH; */
3848 ctx->ctx_dsemicolon = 0;
3851 if (!command->argv /* if it's the first word... */
3852 # if ENABLE_HUSH_LOOPS
3853 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3854 && ctx->ctx_res_w != RES_IN
3856 # if ENABLE_HUSH_CASE
3857 && ctx->ctx_res_w != RES_CASE
3860 const struct reserved_combo *reserved;
3861 reserved = reserved_word(word, ctx);
3862 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
3864 # if ENABLE_HUSH_LINENO_VAR
3868 * If we don't close the pipe _now_, immediately after "do", lineno logic
3869 * sees "cmd" as starting at "do" - i.e., at the previous line.
3872 IF_HUSH_IF(|| reserved->res == RES_THEN)
3873 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3874 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3875 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3877 done_pipe(ctx, PIPE_SEQ);
3880 o_reset_to_empty_unquoted(word);
3881 debug_printf_parse("done_word return %d\n",
3882 (ctx->ctx_res_w == RES_SNTX));
3883 return (ctx->ctx_res_w == RES_SNTX);
3886 if (strcmp(word->data, "[[") == 0) {
3887 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3893 if (command->group) {
3894 /* "{ echo foo; } echo bar" - bad */
3895 syntax_error_at(word->data);
3896 debug_printf_parse("done_word return 1: syntax error, "
3897 "groups and arglists don't mix\n");
3901 /* If this word wasn't an assignment, next ones definitely
3902 * can't be assignments. Even if they look like ones. */
3903 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3904 && word->o_assignment != WORD_IS_KEYWORD
3906 word->o_assignment = NOT_ASSIGNMENT;
3908 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3909 command->assignment_cnt++;
3910 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3912 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3913 word->o_assignment = MAYBE_ASSIGNMENT;
3915 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3916 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3917 debug_print_strings("word appended to argv", command->argv);
3920 #if ENABLE_HUSH_LOOPS
3921 if (ctx->ctx_res_w == RES_FOR) {
3922 if (word->has_quoted_part
3923 || !is_well_formed_var_name(command->argv[0], '\0')
3925 /* bash says just "not a valid identifier" */
3926 syntax_error("not a valid identifier in for");
3929 /* Force FOR to have just one word (variable name) */
3930 /* NB: basically, this makes hush see "for v in ..."
3931 * syntax as if it is "for v; in ...". FOR and IN become
3932 * two pipe structs in parse tree. */
3933 done_pipe(ctx, PIPE_SEQ);
3936 #if ENABLE_HUSH_CASE
3937 /* Force CASE to have just one word */
3938 if (ctx->ctx_res_w == RES_CASE) {
3939 done_pipe(ctx, PIPE_SEQ);
3943 o_reset_to_empty_unquoted(word);
3945 debug_printf_parse("done_word return 0\n");
3950 /* Peek ahead in the input to find out if we have a "&n" construct,
3951 * as in "2>&1", that represents duplicating a file descriptor.
3953 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3954 * REDIRFD_SYNTAX_ERR if syntax error,
3955 * REDIRFD_TO_FILE if no & was seen,
3956 * or the number found.
3959 #define parse_redir_right_fd(as_string, input) \
3960 parse_redir_right_fd(input)
3962 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3968 return REDIRFD_TO_FILE;
3970 ch = i_getch(input); /* get the & */
3971 nommu_addchr(as_string, ch);
3974 ch = i_getch(input);
3975 nommu_addchr(as_string, ch);
3976 return REDIRFD_CLOSE;
3980 while (ch != EOF && isdigit(ch)) {
3981 d = d*10 + (ch-'0');
3983 ch = i_getch(input);
3984 nommu_addchr(as_string, ch);
3989 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3991 bb_error_msg("ambiguous redirect");
3992 return REDIRFD_SYNTAX_ERR;
3995 /* Return code is 0 normal, 1 if a syntax error is detected
3997 static int parse_redirect(struct parse_context *ctx,
4000 struct in_str *input)
4002 struct command *command = ctx->command;
4003 struct redir_struct *redir;
4004 struct redir_struct **redirp;
4007 dup_num = REDIRFD_TO_FILE;
4008 if (style != REDIRECT_HEREDOC) {
4009 /* Check for a '>&1' type redirect */
4010 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4011 if (dup_num == REDIRFD_SYNTAX_ERR)
4014 int ch = i_peek(input);
4015 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4016 if (dup_num) { /* <<-... */
4017 ch = i_getch(input);
4018 nommu_addchr(&ctx->as_string, ch);
4023 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4024 int ch = i_peek(input);
4026 /* >|FILE redirect ("clobbering" >).
4027 * Since we do not support "set -o noclobber" yet,
4028 * >| and > are the same for now. Just eat |.
4030 ch = i_getch(input);
4031 nommu_addchr(&ctx->as_string, ch);
4035 /* Create a new redir_struct and append it to the linked list */
4036 redirp = &command->redirects;
4037 while ((redir = *redirp) != NULL) {
4038 redirp = &(redir->next);
4040 *redirp = redir = xzalloc(sizeof(*redir));
4041 /* redir->next = NULL; */
4042 /* redir->rd_filename = NULL; */
4043 redir->rd_type = style;
4044 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4046 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4047 redir_table[style].descrip);
4049 redir->rd_dup = dup_num;
4050 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4051 /* Erik had a check here that the file descriptor in question
4052 * is legit; I postpone that to "run time"
4053 * A "-" representation of "close me" shows up as a -3 here */
4054 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4055 redir->rd_fd, redir->rd_dup);
4057 #if 0 /* Instead we emit error message at run time */
4058 if (ctx->pending_redirect) {
4059 /* For example, "cmd > <file" */
4060 syntax_error("invalid redirect");
4063 /* Set ctx->pending_redirect, so we know what to do at the
4064 * end of the next parsed word. */
4065 ctx->pending_redirect = redir;
4070 /* If a redirect is immediately preceded by a number, that number is
4071 * supposed to tell which file descriptor to redirect. This routine
4072 * looks for such preceding numbers. In an ideal world this routine
4073 * needs to handle all the following classes of redirects...
4074 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4075 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4076 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4077 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4079 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4081 * ... If n is quoted, the number shall not be recognized as part of
4082 * the redirection expression. For example:
4084 * writes the character 2 into file a"
4085 * We are getting it right by setting ->has_quoted_part on any \<char>
4087 * A -1 return means no valid number was found,
4088 * the caller should use the appropriate default for this redirection.
4090 static int redirect_opt_num(o_string *o)
4094 if (o->data == NULL)
4096 num = bb_strtou(o->data, NULL, 10);
4097 if (errno || num < 0)
4099 o_reset_to_empty_unquoted(o);
4104 #define fetch_till_str(as_string, input, word, skip_tabs) \
4105 fetch_till_str(input, word, skip_tabs)
4107 static char *fetch_till_str(o_string *as_string,
4108 struct in_str *input,
4112 o_string heredoc = NULL_O_STRING;
4114 int prev = 0; /* not \ */
4120 ch = i_getch(input);
4122 nommu_addchr(as_string, ch);
4123 if (ch == '\n' || ch == EOF) {
4125 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4126 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4127 heredoc.data[past_EOL] = '\0';
4128 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4129 return heredoc.data;
4132 /* This is a new line.
4133 * Remember position and backslash-escaping status.
4135 o_addchr(&heredoc, ch);
4138 past_EOL = heredoc.length;
4139 /* Get 1st char of next line, possibly skipping leading tabs */
4141 ch = i_getch(input);
4143 nommu_addchr(as_string, ch);
4144 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4145 /* If this immediately ended the line,
4146 * go back to end-of-line checks.
4149 goto check_heredoc_end;
4154 o_free_unsafe(&heredoc);
4157 o_addchr(&heredoc, ch);
4158 nommu_addchr(as_string, ch);
4159 if (prev == '\\' && ch == '\\')
4160 /* Correctly handle foo\\<eol> (not a line cont.) */
4161 prev = 0; /* not \ */
4167 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4168 * and load them all. There should be exactly heredoc_cnt of them.
4170 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4172 struct pipe *pi = ctx->list_head;
4174 while (pi && heredoc_cnt) {
4176 struct command *cmd = pi->cmds;
4178 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4180 cmd->argv ? cmd->argv[0] : "NONE");
4181 for (i = 0; i < pi->num_cmds; i++) {
4182 struct redir_struct *redir = cmd->redirects;
4184 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4185 i, cmd->argv ? cmd->argv[0] : "NONE");
4187 if (redir->rd_type == REDIRECT_HEREDOC) {
4190 redir->rd_type = REDIRECT_HEREDOC2;
4191 /* redir->rd_dup is (ab)used to indicate <<- */
4192 p = fetch_till_str(&ctx->as_string, input,
4193 redir->rd_filename, redir->rd_dup);
4195 syntax_error("unexpected EOF in here document");
4198 free(redir->rd_filename);
4199 redir->rd_filename = p;
4202 redir = redir->next;
4209 /* Should be 0. If it isn't, it's a parse error */
4211 bb_error_msg_and_die("heredoc BUG 2");
4217 static int run_list(struct pipe *pi);
4219 #define parse_stream(pstring, input, end_trigger) \
4220 parse_stream(input, end_trigger)
4222 static struct pipe *parse_stream(char **pstring,
4223 struct in_str *input,
4227 #if !ENABLE_HUSH_FUNCTIONS
4228 #define parse_group(dest, ctx, input, ch) \
4229 parse_group(ctx, input, ch)
4231 static int parse_group(o_string *dest, struct parse_context *ctx,
4232 struct in_str *input, int ch)
4234 /* dest contains characters seen prior to ( or {.
4235 * Typically it's empty, but for function defs,
4236 * it contains function name (without '()'). */
4237 struct pipe *pipe_list;
4239 struct command *command = ctx->command;
4241 debug_printf_parse("parse_group entered\n");
4242 #if ENABLE_HUSH_FUNCTIONS
4243 if (ch == '(' && !dest->has_quoted_part) {
4245 if (done_word(dest, ctx))
4248 goto skip; /* (... */
4249 if (command->argv[1]) { /* word word ... (... */
4250 syntax_error_unexpected_ch('(');
4253 /* it is "word(..." or "word (..." */
4255 ch = i_getch(input);
4256 while (ch == ' ' || ch == '\t');
4258 syntax_error_unexpected_ch(ch);
4261 nommu_addchr(&ctx->as_string, ch);
4263 ch = i_getch(input);
4264 while (ch == ' ' || ch == '\t' || ch == '\n');
4266 syntax_error_unexpected_ch(ch);
4269 nommu_addchr(&ctx->as_string, ch);
4270 command->cmd_type = CMD_FUNCDEF;
4275 #if 0 /* Prevented by caller */
4276 if (command->argv /* word [word]{... */
4277 || dest->length /* word{... */
4278 || dest->has_quoted_part /* ""{... */
4281 debug_printf_parse("parse_group return 1: "
4282 "syntax error, groups and arglists don't mix\n");
4287 #if ENABLE_HUSH_FUNCTIONS
4293 command->cmd_type = CMD_SUBSHELL;
4295 /* bash does not allow "{echo...", requires whitespace */
4297 if (ch != ' ' && ch != '\t' && ch != '\n'
4298 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4300 syntax_error_unexpected_ch(ch);
4304 ch = i_getch(input);
4305 nommu_addchr(&ctx->as_string, ch);
4311 # define as_string NULL
4313 char *as_string = NULL;
4315 pipe_list = parse_stream(&as_string, input, endch);
4318 o_addstr(&ctx->as_string, as_string);
4320 /* empty ()/{} or parse error? */
4321 if (!pipe_list || pipe_list == ERR_PTR) {
4322 /* parse_stream already emitted error msg */
4325 debug_printf_parse("parse_group return 1: "
4326 "parse_stream returned %p\n", pipe_list);
4329 command->group = pipe_list;
4331 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4332 command->group_as_string = as_string;
4333 debug_printf_parse("end of group, remembering as:'%s'\n",
4334 command->group_as_string);
4338 debug_printf_parse("parse_group return 0\n");
4340 /* command remains "open", available for possible redirects */
4343 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4348 ch = i_getch(input);
4351 ch2 = i_peek(input);
4354 /* backslash+newline, skip it */
4359 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4367 ch2 = i_peek2(input);
4370 /* backslash+newline, skip it */
4376 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4377 /* Subroutines for copying $(...) and `...` things */
4378 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4380 static int add_till_single_quote(o_string *dest, struct in_str *input)
4383 int ch = i_getch(input);
4385 syntax_error_unterm_ch('\'');
4393 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4394 static int add_till_double_quote(o_string *dest, struct in_str *input)
4397 int ch = i_getch(input);
4399 syntax_error_unterm_ch('"');
4404 if (ch == '\\') { /* \x. Copy both chars. */
4406 ch = i_getch(input);
4410 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4415 //if (ch == '$') ...
4418 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4420 * "Within the backquoted style of command substitution, backslash
4421 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4422 * The search for the matching backquote shall be satisfied by the first
4423 * backquote found without a preceding backslash; during this search,
4424 * if a non-escaped backquote is encountered within a shell comment,
4425 * a here-document, an embedded command substitution of the $(command)
4426 * form, or a quoted string, undefined results occur. A single-quoted
4427 * or double-quoted string that begins, but does not end, within the
4428 * "`...`" sequence produces undefined results."
4430 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4432 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4435 int ch = i_getch(input);
4439 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4440 ch = i_getch(input);
4444 && (!in_dquote || ch != '"')
4446 o_addchr(dest, '\\');
4450 syntax_error_unterm_ch('`');
4456 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4457 * quoting and nested ()s.
4458 * "With the $(command) style of command substitution, all characters
4459 * following the open parenthesis to the matching closing parenthesis
4460 * constitute the command. Any valid shell script can be used for command,
4461 * except a script consisting solely of redirections which produces
4462 * unspecified results."
4464 * echo $(echo '(TEST)' BEST) (TEST) BEST
4465 * echo $(echo 'TEST)' BEST) TEST) BEST
4466 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4468 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4469 * can contain arbitrary constructs, just like $(cmd).
4470 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4471 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4473 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4474 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4477 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4478 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4479 char end_char2 = end_ch >> 8;
4481 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4484 ch = i_getch(input);
4486 syntax_error_unterm_ch(end_ch);
4490 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4496 /* we look for closing )) of $((EXPR)) */
4497 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4498 i_getch(input); /* eat second ')' */
4503 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
4504 if (ch == '(' || ch == '{') {
4505 ch = (ch == '(' ? ')' : '}');
4506 if (!add_till_closing_bracket(dest, input, ch))
4512 if (!add_till_single_quote(dest, input))
4518 if (!add_till_double_quote(dest, input))
4524 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4530 /* \x. Copy verbatim. Important for \(, \) */
4531 ch = i_getch(input);
4533 syntax_error_unterm_ch(end_ch);
4538 /* "backslash+newline", ignore both */
4539 o_delchr(dest); /* undo insertion of '\' */
4544 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
4550 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4552 /* Return code: 0 for OK, 1 for syntax error */
4554 #define parse_dollar(as_string, dest, input, quote_mask) \
4555 parse_dollar(dest, input, quote_mask)
4556 #define as_string NULL
4558 static int parse_dollar(o_string *as_string,
4560 struct in_str *input, unsigned char quote_mask)
4562 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4564 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4567 ch = i_getch(input);
4568 nommu_addchr(as_string, ch);
4570 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4572 debug_printf_parse(": '%c'\n", ch);
4573 o_addchr(dest, ch | quote_mask);
4575 ch = i_peek_and_eat_bkslash_nl(input);
4576 if (!isalnum(ch) && ch != '_') {
4577 /* End of variable name reached */
4580 ch = i_getch(input);
4581 nommu_addchr(as_string, ch);
4583 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4584 } else if (isdigit(ch)) {
4586 ch = i_getch(input);
4587 nommu_addchr(as_string, ch);
4588 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4589 debug_printf_parse(": '%c'\n", ch);
4590 o_addchr(dest, ch | quote_mask);
4591 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4592 } else switch (ch) {
4594 case '!': /* last bg pid */
4595 case '?': /* last exit code */
4596 case '#': /* number of args */
4597 case '*': /* args */
4598 case '@': /* args */
4599 goto make_one_char_var;
4603 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4605 ch = i_getch(input); /* eat '{' */
4606 nommu_addchr(as_string, ch);
4608 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4609 /* It should be ${?}, or ${#var},
4610 * or even ${?+subst} - operator acting on a special variable,
4611 * or the beginning of variable name.
4614 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4617 syntax_error_unterm_str("${name}");
4618 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4621 nommu_addchr(as_string, ch);
4625 /* It's possible to just call add_till_closing_bracket() at this point.
4626 * However, this regresses some of our testsuite cases
4627 * which check invalid constructs like ${%}.
4628 * Oh well... let's check that the var name part is fine... */
4634 debug_printf_parse(": '%c'\n", ch);
4636 ch = i_getch(input);
4637 nommu_addchr(as_string, ch);
4641 if (!isalnum(ch) && ch != '_') {
4643 unsigned char last_ch;
4644 /* handle parameter expansions
4645 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4647 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4648 if (len_single_ch != '#'
4649 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4650 || i_peek(input) != '}'
4652 goto bad_dollar_syntax;
4654 /* else: it's "length of C" ${#C} op,
4655 * where C is a single char
4656 * special var name, e.g. ${#!}.
4659 /* Eat everything until closing '}' (or ':') */
4663 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4665 /* It's ${var:N[:M]} thing */
4666 end_ch = '}' * 0x100 + ':';
4668 if (BASH_PATTERN_SUBST
4671 /* It's ${var/[/]pattern[/repl]} thing */
4672 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4674 nommu_addchr(as_string, '/');
4677 end_ch = '}' * 0x100 + '/';
4683 #if ENABLE_HUSH_DOLLAR_OPS
4684 last_ch = add_till_closing_bracket(dest, input, end_ch);
4685 if (last_ch == 0) /* error? */
4688 #error Simple code to only allow ${var} is not implemented
4691 o_addstr(as_string, dest->data + pos);
4692 o_addchr(as_string, last_ch);
4695 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4696 && (end_ch & 0xff00)
4698 /* close the first block: */
4699 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4700 /* while parsing N from ${var:N[:M]}
4701 * or pattern from ${var/[/]pattern[/repl]} */
4702 if ((end_ch & 0xff) == last_ch) {
4703 /* got ':' or '/'- parse the rest */
4708 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4709 /* it's ${var:N} - emulate :999999999 */
4710 o_addstr(dest, "999999999");
4711 } /* else: it's ${var/[/]pattern} */
4715 len_single_ch = 0; /* it can't be ${#C} op */
4717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4720 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4724 ch = i_getch(input);
4725 nommu_addchr(as_string, ch);
4726 # if ENABLE_FEATURE_SH_MATH
4727 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4728 ch = i_getch(input);
4729 nommu_addchr(as_string, ch);
4730 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4731 o_addchr(dest, /*quote_mask |*/ '+');
4734 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4735 return 0; /* error */
4737 o_addstr(as_string, dest->data + pos);
4738 o_addchr(as_string, ')');
4739 o_addchr(as_string, ')');
4741 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4745 # if ENABLE_HUSH_TICK
4746 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4747 o_addchr(dest, quote_mask | '`');
4750 if (!add_till_closing_bracket(dest, input, ')'))
4751 return 0; /* error */
4753 o_addstr(as_string, dest->data + pos);
4754 o_addchr(as_string, ')');
4756 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4764 /* TODO: $_ and $-: */
4765 /* $_ Shell or shell script name; or last argument of last command
4766 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4767 * but in command's env, set to full pathname used to invoke it */
4768 /* $- Option flags set by set builtin or shell options (-i etc) */
4769 ch = i_getch(input);
4770 nommu_addchr(as_string, ch);
4771 ch = i_peek_and_eat_bkslash_nl(input);
4772 if (isalnum(ch)) { /* it's $_name or $_123 */
4779 o_addQchr(dest, '$');
4781 debug_printf_parse("parse_dollar return 1 (ok)\n");
4787 # if BASH_PATTERN_SUBST
4788 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4789 encode_string(dest, input, dquote_end, process_bkslash)
4791 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4792 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4793 encode_string(dest, input, dquote_end)
4795 #define as_string NULL
4799 # if BASH_PATTERN_SUBST
4800 /* all parameters are needed, no macro tricks */
4802 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4803 encode_string(as_string, dest, input, dquote_end)
4806 static int encode_string(o_string *as_string,
4808 struct in_str *input,
4810 int process_bkslash)
4812 #if !BASH_PATTERN_SUBST
4813 const int process_bkslash = 1;
4819 ch = i_getch(input);
4821 nommu_addchr(as_string, ch);
4822 if (ch == dquote_end) { /* may be only '"' or EOF */
4823 debug_printf_parse("encode_string return 1 (ok)\n");
4826 /* note: can't move it above ch == dquote_end check! */
4828 syntax_error_unterm_ch('"');
4829 return 0; /* error */
4833 next = i_peek(input);
4835 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4836 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4837 if (process_bkslash && ch == '\\') {
4839 syntax_error("\\<eof>");
4843 * "The backslash retains its special meaning [in "..."]
4844 * only when followed by one of the following characters:
4845 * $, `, ", \, or <newline>. A double quote may be quoted
4846 * within double quotes by preceding it with a backslash."
4847 * NB: in (unquoted) heredoc, above does not apply to ",
4848 * therefore we check for it by "next == dquote_end" cond.
4850 if (next == dquote_end || strchr("$`\\\n", next)) {
4851 ch = i_getch(input); /* eat next */
4853 goto again; /* skip \<newline> */
4854 } /* else: ch remains == '\\', and we double it below: */
4855 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4856 nommu_addchr(as_string, ch);
4860 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4861 debug_printf_parse("encode_string return 0: "
4862 "parse_dollar returned 0 (error)\n");
4867 #if ENABLE_HUSH_TICK
4869 //unsigned pos = dest->length;
4870 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4871 o_addchr(dest, 0x80 | '`');
4872 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4873 return 0; /* error */
4874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4875 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4879 o_addQchr(dest, ch);
4885 * Scan input until EOF or end_trigger char.
4886 * Return a list of pipes to execute, or NULL on EOF
4887 * or if end_trigger character is met.
4888 * On syntax error, exit if shell is not interactive,
4889 * reset parsing machinery and start parsing anew,
4890 * or return ERR_PTR.
4892 static struct pipe *parse_stream(char **pstring,
4893 struct in_str *input,
4896 struct parse_context ctx;
4897 o_string dest = NULL_O_STRING;
4900 /* Single-quote triggers a bypass of the main loop until its mate is
4901 * found. When recursing, quote state is passed in via dest->o_expflags.
4903 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4904 end_trigger ? end_trigger : 'X');
4907 /* If very first arg is "" or '', dest.data may end up NULL.
4908 * Preventing this: */
4909 o_addchr(&dest, '\0');
4912 /* We used to separate words on $IFS here. This was wrong.
4913 * $IFS is used only for word splitting when $var is expanded,
4914 * here we should use blank chars as separators, not $IFS
4917 if (MAYBE_ASSIGNMENT != 0)
4918 dest.o_assignment = MAYBE_ASSIGNMENT;
4919 initialize_context(&ctx);
4922 const char *is_blank;
4923 const char *is_special;
4927 redir_type redir_style;
4929 ch = i_getch(input);
4930 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4931 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4936 syntax_error_unterm_str("here document");
4939 if (end_trigger == ')') {
4940 syntax_error_unterm_ch('(');
4943 if (end_trigger == '}') {
4944 syntax_error_unterm_ch('{');
4948 if (done_word(&dest, &ctx)) {
4952 done_pipe(&ctx, PIPE_SEQ);
4954 /* If we got nothing... */
4955 /* (this makes bare "&" cmd a no-op.
4956 * bash says: "syntax error near unexpected token '&'") */
4957 if (pi->num_cmds == 0
4958 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4964 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4966 *pstring = ctx.as_string.data;
4968 o_free_unsafe(&ctx.as_string);
4971 debug_printf_parse("parse_stream return %p\n", pi);
4974 nommu_addchr(&ctx.as_string, ch);
4978 next = i_peek(input);
4980 is_special = "{}<>;&|()#'" /* special outside of "str" */
4981 "\\$\"" IF_HUSH_TICK("`") /* always special */
4982 SPECIAL_VAR_SYMBOL_STR;
4983 /* Are { and } special here? */
4984 if (ctx.command->argv /* word [word]{... - non-special */
4985 || dest.length /* word{... - non-special */
4986 || dest.has_quoted_part /* ""{... - non-special */
4987 || (next != ';' /* }; - special */
4988 && next != ')' /* }) - special */
4989 && next != '(' /* {( - special */
4990 && next != '&' /* }& and }&& ... - special */
4991 && next != '|' /* }|| ... - special */
4992 && !strchr(defifs, next) /* {word - non-special */
4995 /* They are not special, skip "{}" */
4998 is_special = strchr(is_special, ch);
4999 is_blank = strchr(defifs, ch);
5001 if (!is_special && !is_blank) { /* ordinary char */
5003 o_addQchr(&dest, ch);
5004 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5005 || dest.o_assignment == WORD_IS_KEYWORD)
5007 && is_well_formed_var_name(dest.data, '=')
5009 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5010 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5016 #if ENABLE_HUSH_LINENO_VAR
5018 * "while ...; do<whitespace><newline>
5020 * would think that "cmd" starts in <whitespace> -
5021 * i.e., at the previous line.
5022 * We need to skip all whitespace before newlines.
5024 while (ch != '\n') {
5025 next = i_peek(input);
5026 if (next != ' ' && next != '\t' && next != '\n')
5027 break; /* next char is not ws */
5028 ch = i_getch(input);
5030 /* ch == last eaten whitespace char */
5032 if (done_word(&dest, &ctx)) {
5036 /* Is this a case when newline is simply ignored?
5038 * "cmd | <newline> cmd ..."
5039 * "case ... in <newline> word) ..."
5041 if (IS_NULL_CMD(ctx.command)
5042 && dest.length == 0 && !dest.has_quoted_part
5044 /* This newline can be ignored. But...
5045 * Without check #1, interactive shell
5046 * ignores even bare <newline>,
5047 * and shows the continuation prompt:
5048 * ps1_prompt$ <enter>
5049 * ps2> _ <=== wrong, should be ps1
5050 * Without check #2, "cmd & <newline>"
5051 * is similarly mistreated.
5052 * (BTW, this makes "cmd & cmd"
5053 * and "cmd && cmd" non-orthogonal.
5054 * Really, ask yourself, why
5055 * "cmd && <newline>" doesn't start
5056 * cmd but waits for more input?
5057 * The only reason is that it might be
5058 * a "cmd1 && <nl> cmd2 &" construct,
5059 * cmd1 may need to run in BG).
5061 struct pipe *pi = ctx.list_head;
5062 if (pi->num_cmds != 0 /* check #1 */
5063 && pi->followup != PIPE_BG /* check #2 */
5068 /* Treat newline as a command separator. */
5069 done_pipe(&ctx, PIPE_SEQ);
5070 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5072 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5077 dest.o_assignment = MAYBE_ASSIGNMENT;
5078 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5080 /* note: if (is_blank) continue;
5081 * will still trigger for us */
5085 /* "cmd}" or "cmd }..." without semicolon or &:
5086 * } is an ordinary char in this case, even inside { cmd; }
5087 * Pathological example: { ""}; } should exec "}" cmd
5090 if (dest.length != 0 /* word} */
5091 || dest.has_quoted_part /* ""} */
5095 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5096 /* Generally, there should be semicolon: "cmd; }"
5097 * However, bash allows to omit it if "cmd" is
5098 * a group. Examples:
5101 * { echo 0 >&2 | { echo 1; } }
5102 * { while false; do :; done }
5103 * { case a in b) ;; esac }
5105 if (ctx.command->group)
5109 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5110 /* Can't be an end of {cmd}, skip the check */
5111 goto skip_end_trigger;
5112 /* else: } does terminate a group */
5115 if (end_trigger && end_trigger == ch
5116 && (ch != ';' || heredoc_cnt == 0)
5117 #if ENABLE_HUSH_CASE
5119 || ctx.ctx_res_w != RES_MATCH
5120 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5125 /* This is technically valid:
5126 * { cat <<HERE; }; echo Ok
5130 * but we don't support this.
5131 * We require heredoc to be in enclosing {}/(),
5134 syntax_error_unterm_str("here document");
5137 if (done_word(&dest, &ctx)) {
5140 done_pipe(&ctx, PIPE_SEQ);
5141 dest.o_assignment = MAYBE_ASSIGNMENT;
5142 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5143 /* Do we sit outside of any if's, loops or case's? */
5145 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5149 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5151 *pstring = ctx.as_string.data;
5153 o_free_unsafe(&ctx.as_string);
5155 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5156 /* Example: bare "{ }", "()" */
5157 G.last_exitcode = 2; /* bash compat */
5158 syntax_error_unexpected_ch(ch);
5161 debug_printf_parse("parse_stream return %p: "
5162 "end_trigger char found\n",
5165 return ctx.list_head;
5172 /* Catch <, > before deciding whether this word is
5173 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5176 redir_fd = redirect_opt_num(&dest);
5177 if (done_word(&dest, &ctx)) {
5180 redir_style = REDIRECT_OVERWRITE;
5182 redir_style = REDIRECT_APPEND;
5183 ch = i_getch(input);
5184 nommu_addchr(&ctx.as_string, ch);
5187 else if (next == '(') {
5188 syntax_error(">(process) not supported");
5192 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5194 continue; /* back to top of while (1) */
5196 redir_fd = redirect_opt_num(&dest);
5197 if (done_word(&dest, &ctx)) {
5200 redir_style = REDIRECT_INPUT;
5202 redir_style = REDIRECT_HEREDOC;
5204 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5205 ch = i_getch(input);
5206 nommu_addchr(&ctx.as_string, ch);
5207 } else if (next == '>') {
5208 redir_style = REDIRECT_IO;
5209 ch = i_getch(input);
5210 nommu_addchr(&ctx.as_string, ch);
5213 else if (next == '(') {
5214 syntax_error("<(process) not supported");
5218 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5220 continue; /* back to top of while (1) */
5222 if (dest.length == 0 && !dest.has_quoted_part) {
5223 /* skip "#comment" */
5224 /* note: we do not add it to &ctx.as_string */
5226 * comment inside $() goes to the next \n, even inside quoted string (!):
5227 * cmd "$(cmd2 #comment)" - syntax error
5228 * cmd "`cmd2 #comment`" - ok
5229 * We accept both (comment ends where command subst ends, in both cases).
5234 nommu_addchr(&ctx.as_string, '\n');
5237 ch = i_getch(input);
5241 continue; /* back to top of while (1) */
5246 /* It's "\<newline>" */
5248 /* Remove trailing '\' from ctx.as_string */
5249 ctx.as_string.data[--ctx.as_string.length] = '\0';
5251 ch = i_getch(input); /* eat it */
5252 continue; /* back to top of while (1) */
5257 if (dest.o_assignment == MAYBE_ASSIGNMENT
5258 /* check that we are not in word in "a=1 2>word b=1": */
5259 && !ctx.pending_redirect
5261 /* ch is a special char and thus this word
5262 * cannot be an assignment */
5263 dest.o_assignment = NOT_ASSIGNMENT;
5264 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5267 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5270 case SPECIAL_VAR_SYMBOL:
5271 /* Convert raw ^C to corresponding special variable reference */
5272 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5273 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5276 /* non-comment #: "echo a#b" etc */
5277 o_addchr(&dest, ch);
5281 syntax_error("\\<eof>");
5284 ch = i_getch(input);
5285 /* note: ch != '\n' (that case does not reach this place) */
5286 o_addchr(&dest, '\\');
5287 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5288 o_addchr(&dest, ch);
5289 nommu_addchr(&ctx.as_string, ch);
5290 /* Example: echo Hello \2>file
5291 * we need to know that word 2 is quoted */
5292 dest.has_quoted_part = 1;
5295 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5296 debug_printf_parse("parse_stream parse error: "
5297 "parse_dollar returned 0 (error)\n");
5302 dest.has_quoted_part = 1;
5303 if (next == '\'' && !ctx.pending_redirect) {
5304 insert_empty_quoted_str_marker:
5305 nommu_addchr(&ctx.as_string, next);
5306 i_getch(input); /* eat second ' */
5307 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5308 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5311 ch = i_getch(input);
5313 syntax_error_unterm_ch('\'');
5316 nommu_addchr(&ctx.as_string, ch);
5319 if (ch == SPECIAL_VAR_SYMBOL) {
5320 /* Convert raw ^C to corresponding special variable reference */
5321 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5322 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5324 o_addqchr(&dest, ch);
5329 dest.has_quoted_part = 1;
5330 if (next == '"' && !ctx.pending_redirect)
5331 goto insert_empty_quoted_str_marker;
5332 if (dest.o_assignment == NOT_ASSIGNMENT)
5333 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5334 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5336 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5338 #if ENABLE_HUSH_TICK
5340 USE_FOR_NOMMU(unsigned pos;)
5342 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5343 o_addchr(&dest, '`');
5344 USE_FOR_NOMMU(pos = dest.length;)
5345 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5348 o_addstr(&ctx.as_string, dest.data + pos);
5349 o_addchr(&ctx.as_string, '`');
5351 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5352 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5357 #if ENABLE_HUSH_CASE
5360 if (done_word(&dest, &ctx)) {
5363 done_pipe(&ctx, PIPE_SEQ);
5364 #if ENABLE_HUSH_CASE
5365 /* Eat multiple semicolons, detect
5366 * whether it means something special */
5371 ch = i_getch(input);
5372 nommu_addchr(&ctx.as_string, ch);
5373 if (ctx.ctx_res_w == RES_CASE_BODY) {
5374 ctx.ctx_dsemicolon = 1;
5375 ctx.ctx_res_w = RES_MATCH;
5381 /* We just finished a cmd. New one may start
5382 * with an assignment */
5383 dest.o_assignment = MAYBE_ASSIGNMENT;
5384 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5387 if (done_word(&dest, &ctx)) {
5391 ch = i_getch(input);
5392 nommu_addchr(&ctx.as_string, ch);
5393 done_pipe(&ctx, PIPE_AND);
5395 done_pipe(&ctx, PIPE_BG);
5399 if (done_word(&dest, &ctx)) {
5402 #if ENABLE_HUSH_CASE
5403 if (ctx.ctx_res_w == RES_MATCH)
5404 break; /* we are in case's "word | word)" */
5406 if (next == '|') { /* || */
5407 ch = i_getch(input);
5408 nommu_addchr(&ctx.as_string, ch);
5409 done_pipe(&ctx, PIPE_OR);
5411 /* we could pick up a file descriptor choice here
5412 * with redirect_opt_num(), but bash doesn't do it.
5413 * "echo foo 2| cat" yields "foo 2". */
5418 #if ENABLE_HUSH_CASE
5419 /* "case... in [(]word)..." - skip '(' */
5420 if (ctx.ctx_res_w == RES_MATCH
5421 && ctx.command->argv == NULL /* not (word|(... */
5422 && dest.length == 0 /* not word(... */
5423 && dest.has_quoted_part == 0 /* not ""(... */
5429 if (parse_group(&dest, &ctx, input, ch) != 0) {
5434 #if ENABLE_HUSH_CASE
5435 if (ctx.ctx_res_w == RES_MATCH)
5439 /* proper use of this character is caught by end_trigger:
5440 * if we see {, we call parse_group(..., end_trigger='}')
5441 * and it will match } earlier (not here). */
5442 G.last_exitcode = 2;
5443 syntax_error_unexpected_ch(ch);
5447 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5452 G.last_exitcode = 1;
5455 struct parse_context *pctx;
5456 IF_HAS_KEYWORDS(struct parse_context *p2;)
5458 /* Clean up allocated tree.
5459 * Sample for finding leaks on syntax error recovery path.
5460 * Run it from interactive shell, watch pmap `pidof hush`.
5461 * while if false; then false; fi; do break; fi
5462 * Samples to catch leaks at execution:
5463 * while if (true | { true;}); then echo ok; fi; do break; done
5464 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5468 /* Update pipe/command counts,
5469 * otherwise freeing may miss some */
5470 done_pipe(pctx, PIPE_SEQ);
5471 debug_printf_clean("freeing list %p from ctx %p\n",
5472 pctx->list_head, pctx);
5473 debug_print_tree(pctx->list_head, 0);
5474 free_pipe_list(pctx->list_head);
5475 debug_printf_clean("freed list %p\n", pctx->list_head);
5477 o_free_unsafe(&pctx->as_string);
5479 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5483 IF_HAS_KEYWORDS(pctx = p2;)
5484 } while (HAS_KEYWORDS && pctx);
5497 /*** Execution routines ***/
5499 /* Expansion can recurse, need forward decls: */
5500 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5501 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5502 #define expand_string_to_string(str, do_unbackslash) \
5503 expand_string_to_string(str)
5505 static char *expand_string_to_string(const char *str, int do_unbackslash);
5506 #if ENABLE_HUSH_TICK
5507 static int process_command_subs(o_string *dest, const char *s);
5510 /* expand_strvec_to_strvec() takes a list of strings, expands
5511 * all variable references within and returns a pointer to
5512 * a list of expanded strings, possibly with larger number
5513 * of strings. (Think VAR="a b"; echo $VAR).
5514 * This new list is allocated as a single malloc block.
5515 * NULL-terminated list of char* pointers is at the beginning of it,
5516 * followed by strings themselves.
5517 * Caller can deallocate entire list by single free(list). */
5519 /* A horde of its helpers come first: */
5521 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5523 while (--len >= 0) {
5526 #if ENABLE_HUSH_BRACE_EXPANSION
5527 if (c == '{' || c == '}') {
5528 /* { -> \{, } -> \} */
5530 /* And now we want to add { or } and continue:
5533 * luckily, just falling through achieves this.
5539 /* \z -> \\\z; \<eol> -> \\<eol> */
5544 o_addchr(o, *str++);
5550 /* Store given string, finalizing the word and starting new one whenever
5551 * we encounter IFS char(s). This is used for expanding variable values.
5552 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5553 * Return in *ended_with_ifs:
5554 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5556 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5558 int last_is_ifs = 0;
5563 if (!*str) /* EOL - do not finalize word */
5565 word_len = strcspn(str, G.ifs);
5567 /* We have WORD_LEN leading non-IFS chars */
5568 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5569 o_addblock(output, str, word_len);
5571 /* Protect backslashes against globbing up :)
5572 * Example: "v='\*'; echo b$v" prints "b\*"
5573 * (and does not try to glob on "*")
5575 o_addblock_duplicate_backslash(output, str, word_len);
5576 /*/ Why can't we do it easier? */
5577 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5578 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5582 if (!*str) /* EOL - do not finalize word */
5586 /* We know str here points to at least one IFS char */
5588 str += strspn(str, G.ifs); /* skip IFS chars */
5589 if (!*str) /* EOL - do not finalize word */
5592 /* Start new word... but not always! */
5593 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5594 if (output->has_quoted_part
5595 /* Case "v=' a'; echo $v":
5596 * here nothing precedes the space in $v expansion,
5597 * therefore we should not finish the word
5598 * (IOW: if there *is* word to finalize, only then do it):
5600 || (n > 0 && output->data[output->length - 1])
5602 o_addchr(output, '\0');
5603 debug_print_list("expand_on_ifs", output, n);
5604 n = o_save_ptr(output, n);
5609 *ended_with_ifs = last_is_ifs;
5610 debug_print_list("expand_on_ifs[1]", output, n);
5614 /* Helper to expand $((...)) and heredoc body. These act as if
5615 * they are in double quotes, with the exception that they are not :).
5616 * Just the rules are similar: "expand only $var and `cmd`"
5618 * Returns malloced string.
5619 * As an optimization, we return NULL if expansion is not needed.
5621 #if !BASH_PATTERN_SUBST
5622 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5623 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5624 encode_then_expand_string(str)
5626 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5628 #if !BASH_PATTERN_SUBST
5629 enum { do_unbackslash = 1 };
5632 struct in_str input;
5633 o_string dest = NULL_O_STRING;
5635 if (!strchr(str, '$')
5636 && !strchr(str, '\\')
5637 #if ENABLE_HUSH_TICK
5638 && !strchr(str, '`')
5644 /* We need to expand. Example:
5645 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5647 setup_string_in_str(&input, str);
5648 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5649 //TODO: error check (encode_string returns 0 on error)?
5650 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5651 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5652 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5653 o_free_unsafe(&dest);
5657 #if ENABLE_FEATURE_SH_MATH
5658 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5660 arith_state_t math_state;
5664 math_state.lookupvar = get_local_var_value;
5665 math_state.setvar = set_local_var_from_halves;
5666 //math_state.endofname = endofname;
5667 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5668 res = arith(&math_state, exp_str ? exp_str : arg);
5671 *errmsg_p = math_state.errmsg;
5672 if (math_state.errmsg)
5673 msg_and_die_if_script(math_state.errmsg);
5678 #if BASH_PATTERN_SUBST
5679 /* ${var/[/]pattern[/repl]} helpers */
5680 static char *strstr_pattern(char *val, const char *pattern, int *size)
5683 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5684 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5691 /* Optimization: if "*pat" did not match the start of "string",
5692 * we know that "tring", "ring" etc will not match too:
5694 if (pattern[0] == '*')
5699 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5701 char *result = NULL;
5702 unsigned res_len = 0;
5703 unsigned repl_len = strlen(repl);
5705 /* Null pattern never matches, including if "var" is empty */
5707 return result; /* NULL, no replaces happened */
5711 char *s = strstr_pattern(val, pattern, &size);
5715 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5716 strcpy(mempcpy(result + res_len, val, s - val), repl);
5717 res_len += (s - val) + repl_len;
5718 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5724 if (*val && result) {
5725 result = xrealloc(result, res_len + strlen(val) + 1);
5726 strcpy(result + res_len, val);
5727 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5729 debug_printf_varexp("result:'%s'\n", result);
5732 #endif /* BASH_PATTERN_SUBST */
5735 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5737 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5745 char exp_save = exp_save; /* for compiler */
5746 char *exp_saveptr; /* points to expansion operator */
5747 char *exp_word = exp_word; /* for compiler */
5753 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5755 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5757 first_char = arg[0] = arg0 & 0x7f;
5760 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5761 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5762 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5763 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5765 /* It must be length operator: ${#var} */
5769 /* Maybe handle parameter expansion */
5770 if (exp_saveptr /* if 2nd char is one of expansion operators */
5771 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5773 /* ${?:0}, ${#[:]%0} etc */
5774 exp_saveptr = var + 1;
5776 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5777 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5779 exp_op = exp_save = *exp_saveptr;
5781 exp_word = exp_saveptr + 1;
5782 if (exp_op == ':') {
5783 exp_op = *exp_word++;
5784 //TODO: try ${var:} and ${var:bogus} in non-bash config
5786 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5788 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5793 *exp_saveptr = '\0';
5794 } /* else: it's not an expansion op, but bare ${var} */
5797 /* Look up the variable in question */
5798 if (isdigit(var[0])) {
5799 /* parse_dollar should have vetted var for us */
5800 int n = xatoi_positive(var);
5801 if (n < G.global_argc)
5802 val = G.global_argv[n];
5803 /* else val remains NULL: $N with too big N */
5807 val = utoa(G.root_pid);
5809 case '!': /* bg pid */
5810 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5812 case '?': /* exitcode */
5813 val = utoa(G.last_exitcode);
5815 case '#': /* argc */
5816 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5819 val = get_local_var_value(var);
5823 /* Handle any expansions */
5824 if (exp_op == 'L') {
5825 reinit_unicode_for_hush();
5826 debug_printf_expand("expand: length(%s)=", val);
5827 val = utoa(val ? unicode_strlen(val) : 0);
5828 debug_printf_expand("%s\n", val);
5829 } else if (exp_op) {
5830 if (exp_op == '%' || exp_op == '#') {
5831 /* Standard-mandated substring removal ops:
5832 * ${parameter%word} - remove smallest suffix pattern
5833 * ${parameter%%word} - remove largest suffix pattern
5834 * ${parameter#word} - remove smallest prefix pattern
5835 * ${parameter##word} - remove largest prefix pattern
5837 * Word is expanded to produce a glob pattern.
5838 * Then var's value is matched to it and matching part removed.
5840 if (val && val[0]) {
5844 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5845 if (exp_op == *exp_word) /* ## or %% */
5847 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
5849 * process_bkslash:1 unbackslash:1 breaks this:
5850 * a='a\\'; echo ${a%\\\\} # correct output is: a
5851 * process_bkslash:1 unbackslash:0 breaks this:
5852 * a='a}'; echo ${a%\}} # correct output is: a
5854 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5856 exp_word = exp_exp_word;
5857 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
5858 /* HACK ALERT. We depend here on the fact that
5859 * G.global_argv and results of utoa and get_local_var_value
5860 * are actually in writable memory:
5861 * scan_and_match momentarily stores NULs there. */
5863 loc = scan_and_match(t, exp_word, scan_flags);
5864 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
5866 if (loc) { /* match was found */
5867 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5868 val = loc; /* take right part */
5870 val = to_be_freed = xstrndup(val, loc - val); /* left */
5874 #if BASH_PATTERN_SUBST
5875 else if (exp_op == '/' || exp_op == '\\') {
5876 /* It's ${var/[/]pattern[/repl]} thing.
5877 * Note that in encoded form it has TWO parts:
5878 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5879 * and if // is used, it is encoded as \:
5880 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5882 if (val && val[0]) {
5883 /* pattern uses non-standard expansion.
5884 * repl should be unbackslashed and globbed
5885 * by the usual expansion rules:
5887 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5888 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5889 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5890 * v='a bz'; echo ${v/a*z/\z} prints "z"
5891 * (note that a*z _pattern_ is never globbed!)
5893 char *pattern, *repl, *t;
5894 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5896 pattern = xstrdup(exp_word);
5897 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5898 *p++ = SPECIAL_VAR_SYMBOL;
5900 p = strchr(p, SPECIAL_VAR_SYMBOL);
5902 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5903 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5904 /* HACK ALERT. We depend here on the fact that
5905 * G.global_argv and results of utoa and get_local_var_value
5906 * are actually in writable memory:
5907 * replace_pattern momentarily stores NULs there. */
5909 to_be_freed = replace_pattern(t,
5911 (repl ? repl : exp_word),
5913 if (to_be_freed) /* at least one replace happened */
5918 /* Empty variable always gives nothing */
5919 // "v=''; echo ${v/*/w}" prints "", not "w"
5920 /* Just skip "replace" part */
5921 *p++ = SPECIAL_VAR_SYMBOL;
5922 p = strchr(p, SPECIAL_VAR_SYMBOL);
5926 #endif /* BASH_PATTERN_SUBST */
5927 else if (exp_op == ':') {
5928 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5929 /* It's ${var:N[:M]} bashism.
5930 * Note that in encoded form it has TWO parts:
5931 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5936 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5939 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5940 *p++ = SPECIAL_VAR_SYMBOL;
5942 p = strchr(p, SPECIAL_VAR_SYMBOL);
5944 len = expand_and_evaluate_arith(exp_word, &errmsg);
5947 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5949 /* negative beg counts from the end */
5950 beg = (arith_t)strlen(val) + beg;
5951 if (beg < 0) /* ${v: -999999} is "" */
5954 debug_printf_varexp("from val:'%s'\n", val);
5956 /* in bash, len=-n means strlen()-n */
5957 len = (arith_t)strlen(val) - beg + len;
5958 if (len < 0) /* bash compat */
5959 msg_and_die_if_script("%s: substring expression < 0", var);
5961 if (len <= 0 || !val || beg >= strlen(val)) {
5965 /* Paranoia. What if user entered 9999999999999
5966 * which fits in arith_t but not int? */
5969 val = to_be_freed = xstrndup(val + beg, len);
5971 debug_printf_varexp("val:'%s'\n", val);
5972 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5973 msg_and_die_if_script("malformed ${%s:...}", var);
5976 } else { /* one of "-=+?" */
5977 /* Standard-mandated substitution ops:
5978 * ${var?word} - indicate error if unset
5979 * If var is unset, word (or a message indicating it is unset
5980 * if word is null) is written to standard error
5981 * and the shell exits with a non-zero exit status.
5982 * Otherwise, the value of var is substituted.
5983 * ${var-word} - use default value
5984 * If var is unset, word is substituted.
5985 * ${var=word} - assign and use default value
5986 * If var is unset, word is assigned to var.
5987 * In all cases, final value of var is substituted.
5988 * ${var+word} - use alternative value
5989 * If var is unset, null is substituted.
5990 * Otherwise, word is substituted.
5992 * Word is subjected to tilde expansion, parameter expansion,
5993 * command substitution, and arithmetic expansion.
5994 * If word is not needed, it is not expanded.
5996 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5997 * but also treat null var as if it is unset.
5999 int use_word = (!val || ((exp_save == ':') && !val[0]));
6001 use_word = !use_word;
6002 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6003 (exp_save == ':') ? "true" : "false", use_word);
6005 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6007 exp_word = to_be_freed;
6008 if (exp_op == '?') {
6009 /* mimic bash message */
6010 msg_and_die_if_script("%s: %s",
6014 : "parameter null or not set"
6015 /* ash has more specific messages, a-la: */
6016 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6018 //TODO: how interactive bash aborts expansion mid-command?
6023 if (exp_op == '=') {
6024 /* ${var=[word]} or ${var:=[word]} */
6025 if (isdigit(var[0]) || var[0] == '#') {
6026 /* mimic bash message */
6027 msg_and_die_if_script("$%s: cannot assign in this way", var);
6030 char *new_var = xasprintf("%s=%s", var, val);
6031 set_local_var(new_var, /*flag:*/ 0);
6035 } /* one of "-=+?" */
6037 *exp_saveptr = exp_save;
6043 *to_be_freed_pp = to_be_freed;
6047 /* Expand all variable references in given string, adding words to list[]
6048 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6049 * to be filled). This routine is extremely tricky: has to deal with
6050 * variables/parameters with whitespace, $* and $@, and constructs like
6051 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
6052 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
6054 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
6055 * expansion of right-hand side of assignment == 1-element expand.
6057 char cant_be_null = 0; /* only bit 0x80 matters */
6058 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
6061 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6062 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
6063 debug_print_list("expand_vars_to_list", output, n);
6064 n = o_save_ptr(output, n);
6065 debug_print_list("expand_vars_to_list[0]", output, n);
6067 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6069 char *to_be_freed = NULL;
6070 const char *val = NULL;
6071 #if ENABLE_HUSH_TICK
6072 o_string subst_result = NULL_O_STRING;
6074 #if ENABLE_FEATURE_SH_MATH
6075 char arith_buf[sizeof(arith_t)*3 + 2];
6079 o_addchr(output, '\0');
6080 n = o_save_ptr(output, n);
6084 o_addblock(output, arg, p - arg);
6085 debug_print_list("expand_vars_to_list[1]", output, n);
6087 p = strchr(p, SPECIAL_VAR_SYMBOL);
6089 /* Fetch special var name (if it is indeed one of them)
6090 * and quote bit, force the bit on if singleword expansion -
6091 * important for not getting v=$@ expand to many words. */
6092 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6094 /* Is this variable quoted and thus expansion can't be null?
6095 * "$@" is special. Even if quoted, it can still
6096 * expand to nothing (not even an empty string),
6097 * thus it is excluded. */
6098 if ((first_ch & 0x7f) != '@')
6099 cant_be_null |= first_ch;
6101 switch (first_ch & 0x7f) {
6102 /* Highest bit in first_ch indicates that var is double-quoted */
6106 if (!G.global_argv[1])
6109 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6110 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6111 while (G.global_argv[i]) {
6112 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
6113 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6114 if (G.global_argv[i++][0] && G.global_argv[i]) {
6115 /* this argv[] is not empty and not last:
6116 * put terminating NUL, start new word */
6117 o_addchr(output, '\0');
6118 debug_print_list("expand_vars_to_list[2]", output, n);
6119 n = o_save_ptr(output, n);
6120 debug_print_list("expand_vars_to_list[3]", output, n);
6124 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6125 * and in this case should treat it like '$*' - see 'else...' below */
6126 if (first_ch == ('@'|0x80) /* quoted $@ */
6127 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6130 o_addQstr(output, G.global_argv[i]);
6131 if (++i >= G.global_argc)
6133 o_addchr(output, '\0');
6134 debug_print_list("expand_vars_to_list[4]", output, n);
6135 n = o_save_ptr(output, n);
6137 } else { /* quoted $* (or v="$@" case): add as one word */
6139 o_addQstr(output, G.global_argv[i]);
6140 if (!G.global_argv[++i])
6143 o_addchr(output, G.ifs[0]);
6145 output->has_quoted_part = 1;
6149 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6150 /* "Empty variable", used to make "" etc to not disappear */
6151 output->has_quoted_part = 1;
6153 cant_be_null = 0x80;
6155 case SPECIAL_VAR_QUOTED_SVS:
6156 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6158 val = SPECIAL_VAR_SYMBOL_STR;
6160 #if ENABLE_HUSH_TICK
6161 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6162 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6164 /* Can't just stuff it into output o_string,
6165 * expanded result may need to be globbed
6167 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6168 G.last_exitcode = process_command_subs(&subst_result, arg);
6169 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6170 val = subst_result.data;
6173 #if ENABLE_FEATURE_SH_MATH
6174 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6177 arg++; /* skip '+' */
6178 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6179 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6180 res = expand_and_evaluate_arith(arg, NULL);
6181 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6182 sprintf(arith_buf, ARITH_FMT, res);
6188 val = expand_one_var(&to_be_freed, arg, &p);
6189 IF_HUSH_TICK(store_val:)
6190 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6191 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6192 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6193 if (val && val[0]) {
6194 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6197 } else { /* quoted $VAR, val will be appended below */
6198 output->has_quoted_part = 1;
6199 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6200 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6203 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6205 if (val && val[0]) {
6206 o_addQstr(output, val);
6210 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6211 * Do the check to avoid writing to a const string. */
6212 if (*p != SPECIAL_VAR_SYMBOL)
6213 *p = SPECIAL_VAR_SYMBOL;
6215 #if ENABLE_HUSH_TICK
6216 o_free(&subst_result);
6219 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6223 o_addchr(output, '\0');
6224 n = o_save_ptr(output, n);
6226 debug_print_list("expand_vars_to_list[a]", output, n);
6227 /* this part is literal, and it was already pre-quoted
6228 * if needed (much earlier), do not use o_addQstr here! */
6229 o_addstr_with_NUL(output, arg);
6230 debug_print_list("expand_vars_to_list[b]", output, n);
6231 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6232 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6235 /* allow to reuse list[n] later without re-growth */
6236 output->has_empty_slot = 1;
6238 o_addchr(output, '\0');
6244 static char **expand_variables(char **argv, unsigned expflags)
6248 o_string output = NULL_O_STRING;
6250 output.o_expflags = expflags;
6254 n = expand_vars_to_list(&output, n, *argv);
6257 debug_print_list("expand_variables", &output, n);
6259 /* output.data (malloced in one block) gets returned in "list" */
6260 list = o_finalize_list(&output, n);
6261 debug_print_strings("expand_variables[1]", list);
6265 static char **expand_strvec_to_strvec(char **argv)
6267 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6271 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6273 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6277 /* Used for expansion of right hand of assignments,
6278 * $((...)), heredocs, variable espansion parts.
6280 * NB: should NOT do globbing!
6281 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6283 static char *expand_string_to_string(const char *str, int do_unbackslash)
6285 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6286 const int do_unbackslash = 1;
6288 char *argv[2], **list;
6290 debug_printf_expand("string_to_string<='%s'\n", str);
6291 /* This is generally an optimization, but it also
6292 * handles "", which otherwise trips over !list[0] check below.
6293 * (is this ever happens that we actually get str="" here?)
6295 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6296 //TODO: Can use on strings with \ too, just unbackslash() them?
6297 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6298 return xstrdup(str);
6301 argv[0] = (char*)str;
6303 list = expand_variables(argv, do_unbackslash
6304 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6305 : EXP_FLAG_SINGLEWORD
6308 if (!list[0] || list[1])
6309 bb_error_msg_and_die("BUG in varexp2");
6310 /* actually, just move string 2*sizeof(char*) bytes back */
6311 overlapping_strcpy((char*)list, list[0]);
6313 unbackslash((char*)list);
6314 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6318 #if ENABLE_HUSH_CASE
6319 static char* expand_strvec_to_string(char **argv)
6323 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6324 /* Convert all NULs to spaces */
6329 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6330 bb_error_msg_and_die("BUG in varexp3");
6331 /* bash uses ' ' regardless of $IFS contents */
6336 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6337 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6342 static char **expand_assignments(char **argv, int count)
6347 G.expanded_assignments = p = NULL;
6348 /* Expand assignments into one string each */
6349 for (i = 0; i < count; i++) {
6350 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6352 G.expanded_assignments = NULL;
6357 static void switch_off_special_sigs(unsigned mask)
6360 while ((mask >>= 1) != 0) {
6364 #if ENABLE_HUSH_TRAP
6366 if (G_traps[sig] && !G_traps[sig][0])
6367 /* trap is '', has to remain SIG_IGN */
6370 G_traps[sig] = NULL;
6373 /* We are here only if no trap or trap was not '' */
6374 install_sighandler(sig, SIG_DFL);
6380 void re_execute_shell(char ***to_free, const char *s,
6381 char *g_argv0, char **g_argv,
6382 char **builtin_argv) NORETURN;
6384 static void reset_traps_to_defaults(void)
6386 /* This function is always called in a child shell
6387 * after fork (not vfork, NOMMU doesn't use this function).
6389 IF_HUSH_TRAP(unsigned sig;)
6392 /* Child shells are not interactive.
6393 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6394 * Testcase: (while :; do :; done) + ^Z should background.
6395 * Same goes for SIGTERM, SIGHUP, SIGINT.
6397 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6398 if (!G_traps && !mask)
6399 return; /* already no traps and no special sigs */
6401 /* Switch off special sigs */
6402 switch_off_special_sigs(mask);
6403 # if ENABLE_HUSH_JOB
6404 G_fatal_sig_mask = 0;
6406 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6407 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6408 * remain set in G.special_sig_mask */
6410 # if ENABLE_HUSH_TRAP
6414 /* Reset all sigs to default except ones with empty traps */
6415 for (sig = 0; sig < NSIG; sig++) {
6417 continue; /* no trap: nothing to do */
6418 if (!G_traps[sig][0])
6419 continue; /* empty trap: has to remain SIG_IGN */
6420 /* sig has non-empty trap, reset it: */
6422 G_traps[sig] = NULL;
6423 /* There is no signal for trap 0 (EXIT) */
6426 install_sighandler(sig, pick_sighandler(sig));
6433 static void re_execute_shell(char ***to_free, const char *s,
6434 char *g_argv0, char **g_argv,
6435 char **builtin_argv) NORETURN;
6436 static void re_execute_shell(char ***to_free, const char *s,
6437 char *g_argv0, char **g_argv,
6438 char **builtin_argv)
6440 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6441 /* delims + 2 * (number of bytes in printed hex numbers) */
6442 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6443 char *heredoc_argv[4];
6444 struct variable *cur;
6445 # if ENABLE_HUSH_FUNCTIONS
6446 struct function *funcp;
6450 unsigned long long empty_trap_mask;
6452 if (!g_argv0) { /* heredoc */
6453 argv = heredoc_argv;
6454 argv[0] = (char *) G.argv0_for_re_execing;
6455 argv[1] = (char *) "-<";
6456 argv[2] = (char *) s;
6458 pp = &argv[3]; /* used as pointer to empty environment */
6464 if (pp) while (*pp++)
6467 empty_trap_mask = 0;
6470 for (sig = 1; sig < NSIG; sig++) {
6471 if (G_traps[sig] && !G_traps[sig][0])
6472 empty_trap_mask |= 1LL << sig;
6476 sprintf(param_buf, NOMMU_HACK_FMT
6477 , (unsigned) G.root_pid
6478 , (unsigned) G.root_ppid
6479 , (unsigned) G.last_bg_pid
6480 , (unsigned) G.last_exitcode
6483 IF_HUSH_LOOPS(, G.depth_of_loop)
6485 # undef NOMMU_HACK_FMT
6486 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6487 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6490 for (cur = G.top_var; cur; cur = cur->next) {
6491 if (!cur->flg_export || cur->flg_read_only)
6494 # if ENABLE_HUSH_FUNCTIONS
6495 for (funcp = G.top_func; funcp; funcp = funcp->next)
6501 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6502 *pp++ = (char *) G.argv0_for_re_execing;
6504 for (cur = G.top_var; cur; cur = cur->next) {
6505 if (strcmp(cur->varstr, hush_version_str) == 0)
6507 if (cur->flg_read_only) {
6508 *pp++ = (char *) "-R";
6509 *pp++ = cur->varstr;
6510 } else if (!cur->flg_export) {
6511 *pp++ = (char *) "-V";
6512 *pp++ = cur->varstr;
6515 # if ENABLE_HUSH_FUNCTIONS
6516 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6517 *pp++ = (char *) "-F";
6518 *pp++ = funcp->name;
6519 *pp++ = funcp->body_as_string;
6522 /* We can pass activated traps here. Say, -Tnn:trap_string
6524 * However, POSIX says that subshells reset signals with traps
6526 * I tested bash-3.2 and it not only does that with true subshells
6527 * of the form ( list ), but with any forked children shells.
6528 * I set trap "echo W" WINCH; and then tried:
6530 * { echo 1; sleep 20; echo 2; } &
6531 * while true; do echo 1; sleep 20; echo 2; break; done &
6532 * true | { echo 1; sleep 20; echo 2; } | cat
6534 * In all these cases sending SIGWINCH to the child shell
6535 * did not run the trap. If I add trap "echo V" WINCH;
6536 * _inside_ group (just before echo 1), it works.
6538 * I conclude it means we don't need to pass active traps here.
6540 *pp++ = (char *) "-c";
6543 while (*++builtin_argv)
6544 *pp++ = *builtin_argv;
6545 *pp++ = (char *) "";
6550 /* *pp = NULL; - is already there */
6554 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6555 /* Don't propagate SIG_IGN to the child */
6556 if (SPECIAL_JOBSTOP_SIGS != 0)
6557 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6558 execve(bb_busybox_exec_path, argv, pp);
6559 /* Fallback. Useful for init=/bin/hush usage etc */
6560 if (argv[0][0] == '/')
6561 execve(argv[0], argv, pp);
6562 xfunc_error_retval = 127;
6563 bb_error_msg_and_die("can't re-execute the shell");
6565 #endif /* !BB_MMU */
6568 static int run_and_free_list(struct pipe *pi);
6570 /* Executing from string: eval, sh -c '...'
6571 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6572 * end_trigger controls how often we stop parsing
6573 * NUL: parse all, execute, return
6574 * ';': parse till ';' or newline, execute, repeat till EOF
6576 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6578 /* Why we need empty flag?
6579 * An obscure corner case "false; ``; echo $?":
6580 * empty command in `` should still set $? to 0.
6581 * But we can't just set $? to 0 at the start,
6582 * this breaks "false; echo `echo $?`" case.
6586 struct pipe *pipe_list;
6588 #if ENABLE_HUSH_INTERACTIVE
6589 if (end_trigger == ';')
6590 inp->promptmode = 0; /* PS1 */
6592 pipe_list = parse_stream(NULL, inp, end_trigger);
6593 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6594 /* If we are in "big" script
6595 * (not in `cmd` or something similar)...
6597 if (pipe_list == ERR_PTR && end_trigger == ';') {
6598 /* Discard cached input (rest of line) */
6599 int ch = inp->last_char;
6600 while (ch != EOF && ch != '\n') {
6601 //bb_error_msg("Discarded:'%c'", ch);
6606 /* This stream isn't empty */
6610 if (!pipe_list && empty)
6611 G.last_exitcode = 0;
6614 debug_print_tree(pipe_list, 0);
6615 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6616 run_and_free_list(pipe_list);
6618 if (G_flag_return_in_progress == 1)
6623 static void parse_and_run_string(const char *s)
6625 struct in_str input;
6626 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6628 setup_string_in_str(&input, s);
6629 parse_and_run_stream(&input, '\0');
6630 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
6633 static void parse_and_run_file(FILE *f)
6635 struct in_str input;
6636 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6638 IF_HUSH_LINENO_VAR(G.lineno = 1;)
6639 setup_file_in_str(&input, f);
6640 parse_and_run_stream(&input, ';');
6641 IF_HUSH_LINENO_VAR(G.lineno = sv;)
6644 #if ENABLE_HUSH_TICK
6645 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6650 char **to_free = NULL;
6654 pid = BB_MMU ? xfork() : xvfork();
6655 if (pid == 0) { /* child */
6656 disable_restore_tty_pgrp_on_exit();
6657 /* Process substitution is not considered to be usual
6658 * 'command execution'.
6659 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6666 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6667 close(channel[0]); /* NB: close _first_, then move fd! */
6668 xmove_fd(channel[1], 1);
6669 /* Prevent it from trying to handle ctrl-z etc */
6670 IF_HUSH_JOB(G.run_list_level = 1;)
6671 # if ENABLE_HUSH_TRAP
6672 /* Awful hack for `trap` or $(trap).
6674 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6675 * contains an example where "trap" is executed in a subshell:
6677 * save_traps=$(trap)
6679 * eval "$save_traps"
6681 * Standard does not say that "trap" in subshell shall print
6682 * parent shell's traps. It only says that its output
6683 * must have suitable form, but then, in the above example
6684 * (which is not supposed to be normative), it implies that.
6686 * bash (and probably other shell) does implement it
6687 * (traps are reset to defaults, but "trap" still shows them),
6688 * but as a result, "trap" logic is hopelessly messed up:
6691 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6692 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6693 * # true | trap <--- trap is in subshell - no output (ditto)
6694 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6695 * trap -- 'echo Ho' SIGWINCH
6696 * # echo `(trap)` <--- in subshell in subshell - output
6697 * trap -- 'echo Ho' SIGWINCH
6698 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6699 * trap -- 'echo Ho' SIGWINCH
6701 * The rules when to forget and when to not forget traps
6702 * get really complex and nonsensical.
6704 * Our solution: ONLY bare $(trap) or `trap` is special.
6706 s = skip_whitespace(s);
6707 if (is_prefixed_with(s, "trap")
6708 && skip_whitespace(s + 4)[0] == '\0'
6710 static const char *const argv[] = { NULL, NULL };
6711 builtin_trap((char**)argv);
6712 fflush_all(); /* important */
6717 reset_traps_to_defaults();
6718 parse_and_run_string(s);
6719 _exit(G.last_exitcode);
6721 /* We re-execute after vfork on NOMMU. This makes this script safe:
6722 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6723 * huge=`cat BIG` # was blocking here forever
6726 re_execute_shell(&to_free,
6736 # if ENABLE_HUSH_FAST
6738 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6739 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6740 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6742 enable_restore_tty_pgrp_on_exit();
6747 return remember_FILE(xfdopen_for_read(channel[0]));
6750 /* Return code is exit status of the process that is run. */
6751 static int process_command_subs(o_string *dest, const char *s)
6755 int status, ch, eol_cnt;
6757 fp = generate_stream_from_string(s, &pid);
6759 /* Now send results of command back into original context */
6761 while ((ch = getc(fp)) != EOF) {
6769 o_addchr(dest, '\n');
6772 o_addQchr(dest, ch);
6775 debug_printf("done reading from `cmd` pipe, closing it\n");
6776 fclose_and_forget(fp);
6777 /* We need to extract exitcode. Test case
6778 * "true; echo `sleep 1; false` $?"
6780 safe_waitpid(pid, &status, 0);
6781 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6782 return WEXITSTATUS(status);
6784 #endif /* ENABLE_HUSH_TICK */
6787 static void setup_heredoc(struct redir_struct *redir)
6789 struct fd_pair pair;
6792 /* the _body_ of heredoc (misleading field name) */
6793 const char *heredoc = redir->rd_filename;
6800 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6801 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6805 len = strlen(heredoc);
6807 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6809 xmove_fd(pair.rd, redir->rd_fd);
6811 /* Try writing without forking. Newer kernels have
6812 * dynamically growing pipes. Must use non-blocking write! */
6815 written = write(pair.wr, heredoc, len);
6826 ndelay_off(pair.wr);
6828 /* Okay, pipe buffer was not big enough */
6829 /* Note: we must not create a stray child (bastard? :)
6830 * for the unsuspecting parent process. Child creates a grandchild
6831 * and exits before parent execs the process which consumes heredoc
6832 * (that exec happens after we return from this function) */
6839 disable_restore_tty_pgrp_on_exit();
6840 pid = BB_MMU ? xfork() : xvfork();
6844 close(redir->rd_fd); /* read side of the pipe */
6846 full_write(pair.wr, heredoc, len); /* may loop or block */
6849 /* Delegate blocking writes to another process */
6850 xmove_fd(pair.wr, STDOUT_FILENO);
6851 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6855 #if ENABLE_HUSH_FAST
6857 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6859 enable_restore_tty_pgrp_on_exit();
6865 wait(NULL); /* wait till child has died */
6871 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6872 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6875 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6877 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6878 sq[i].orig_fd = orig;
6879 sq[i].moved_to = moved;
6880 sq[i+1].orig_fd = -1; /* end marker */
6884 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6890 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6891 /* If we collide with an already moved fd... */
6892 if (fd == sq[i].moved_to) {
6893 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6894 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6895 if (sq[i].moved_to < 0) /* what? */
6899 if (fd == sq[i].orig_fd) {
6900 /* Example: echo Hello >/dev/null 1>&2 */
6901 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6906 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6907 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6908 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6909 if (moved_to < 0 && errno != EBADF)
6911 return append_squirrel(sq, i, fd, moved_to);
6914 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6919 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6920 /* If we collide with an already moved fd... */
6921 if (fd == sq[i].orig_fd) {
6923 * "echo 3>FILE 3>&- 3>FILE"
6924 * "echo 3>&- 3>FILE"
6925 * No need for last redirect to insert
6926 * another "need to close 3" indicator.
6928 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6933 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6934 return append_squirrel(sq, i, fd, -1);
6937 /* fd: redirect wants this fd to be used (e.g. 3>file).
6938 * Move all conflicting internally used fds,
6939 * and remember them so that we can restore them later.
6941 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6943 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6946 #if ENABLE_HUSH_INTERACTIVE
6947 if (fd == G.interactive_fd) {
6948 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6949 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6950 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6951 return 1; /* "we closed fd" */
6954 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6955 * (1) Redirect in a forked child. No need to save FILEs' fds,
6956 * we aren't going to use them anymore, ok to trash.
6957 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6958 * but how are we doing to restore them?
6959 * "fileno(fd) = new_fd" can't be done.
6964 /* If this one of script's fds? */
6965 if (save_FILEs_on_redirect(fd, avoid_fd))
6966 return 1; /* yes. "we closed fd" */
6968 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6969 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6970 return 0; /* "we did not close fd" */
6973 static void restore_redirects(struct squirrel *sq)
6977 for (i = 0; sq[i].orig_fd >= 0; i++) {
6978 if (sq[i].moved_to >= 0) {
6979 /* We simply die on error */
6980 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6981 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6983 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6984 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6985 close(sq[i].orig_fd);
6991 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6993 restore_redirected_FILEs();
6996 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6997 static void close_saved_fds_and_FILE_fds(void)
6999 if (G_interactive_fd)
7000 close(G_interactive_fd);
7001 close_all_FILE_list();
7005 static int internally_opened_fd(int fd, struct squirrel *sq)
7009 #if ENABLE_HUSH_INTERACTIVE
7010 if (fd == G.interactive_fd)
7013 /* If this one of script's fds? */
7014 if (fd_in_FILEs(fd))
7017 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7018 if (fd == sq[i].moved_to)
7024 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
7025 * and stderr if they are redirected. */
7026 static int setup_redirects(struct command *prog, struct squirrel **sqp)
7028 struct redir_struct *redir;
7030 for (redir = prog->redirects; redir; redir = redir->next) {
7034 if (redir->rd_type == REDIRECT_HEREDOC2) {
7035 /* "rd_fd<<HERE" case */
7036 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
7037 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7039 debug_printf_parse("set heredoc '%s'\n",
7040 redir->rd_filename);
7041 setup_heredoc(redir);
7045 if (redir->rd_dup == REDIRFD_TO_FILE) {
7046 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
7050 if (redir->rd_filename == NULL) {
7053 * "cmd >" (no filename)
7054 * "cmd > <file" (2nd redirect starts too early)
7056 syntax_error("invalid redirect");
7059 mode = redir_table[redir->rd_type].mode;
7060 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
7061 newfd = open_or_warn(p, mode);
7064 /* Error message from open_or_warn can be lost
7065 * if stderr has been redirected, but bash
7066 * and ash both lose it as well
7067 * (though zsh doesn't!)
7071 if (newfd == redir->rd_fd && sqp) {
7072 /* open() gave us precisely the fd we wanted.
7073 * This means that this fd was not busy
7074 * (not opened to anywhere).
7075 * Remember to close it on restore:
7077 *sqp = add_squirrel_closed(*sqp, newfd);
7078 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7081 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7082 newfd = redir->rd_dup;
7085 if (newfd == redir->rd_fd)
7088 /* if "N>FILE": move newfd to redir->rd_fd */
7089 /* if "N>&M": dup newfd to redir->rd_fd */
7090 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7092 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7093 if (newfd == REDIRFD_CLOSE) {
7094 /* "N>&-" means "close me" */
7096 /* ^^^ optimization: saving may already
7097 * have closed it. If not... */
7098 close(redir->rd_fd);
7100 /* Sometimes we do another close on restore, getting EBADF.
7101 * Consider "echo 3>FILE 3>&-"
7102 * first redirect remembers "need to close 3",
7103 * and second redirect closes 3! Restore code then closes 3 again.
7106 /* if newfd is a script fd or saved fd, simulate EBADF */
7107 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7109 //bb_perror_msg_and_die("can't duplicate file descriptor");
7110 newfd = -1; /* same effect as code above */
7112 xdup2(newfd, redir->rd_fd);
7113 if (redir->rd_dup == REDIRFD_TO_FILE)
7114 /* "rd_fd > FILE" */
7116 /* else: "rd_fd > rd_dup" */
7122 static char *find_in_path(const char *arg)
7125 const char *PATH = get_local_var_value("PATH");
7131 const char *end = strchrnul(PATH, ':');
7132 int sz = end - PATH; /* must be int! */
7136 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7138 /* We have xxx::yyyy in $PATH,
7139 * it means "use current dir" */
7142 if (access(ret, F_OK) == 0)
7155 static const struct built_in_command *find_builtin_helper(const char *name,
7156 const struct built_in_command *x,
7157 const struct built_in_command *end)
7160 if (strcmp(name, x->b_cmd) != 0) {
7164 debug_printf_exec("found builtin '%s'\n", name);
7169 static const struct built_in_command *find_builtin1(const char *name)
7171 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7173 static const struct built_in_command *find_builtin(const char *name)
7175 const struct built_in_command *x = find_builtin1(name);
7178 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7181 #if ENABLE_HUSH_FUNCTIONS
7182 static struct function **find_function_slot(const char *name)
7184 struct function *funcp;
7185 struct function **funcpp = &G.top_func;
7187 while ((funcp = *funcpp) != NULL) {
7188 if (strcmp(name, funcp->name) == 0) {
7189 debug_printf_exec("found function '%s'\n", name);
7192 funcpp = &funcp->next;
7197 static ALWAYS_INLINE const struct function *find_function(const char *name)
7199 const struct function *funcp = *find_function_slot(name);
7203 /* Note: takes ownership on name ptr */
7204 static struct function *new_function(char *name)
7206 struct function **funcpp = find_function_slot(name);
7207 struct function *funcp = *funcpp;
7209 if (funcp != NULL) {
7210 struct command *cmd = funcp->parent_cmd;
7211 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7213 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7215 /* Note: if !funcp->body, do not free body_as_string!
7216 * This is a special case of "-F name body" function:
7217 * body_as_string was not malloced! */
7219 free_pipe_list(funcp->body);
7221 free(funcp->body_as_string);
7225 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7226 cmd->argv[0] = funcp->name;
7227 cmd->group = funcp->body;
7229 cmd->group_as_string = funcp->body_as_string;
7233 debug_printf_exec("remembering new function '%s'\n", name);
7234 funcp = *funcpp = xzalloc(sizeof(*funcp));
7235 /*funcp->next = NULL;*/
7242 # if ENABLE_HUSH_UNSET
7243 static void unset_func(const char *name)
7245 struct function **funcpp = find_function_slot(name);
7246 struct function *funcp = *funcpp;
7248 if (funcp != NULL) {
7249 debug_printf_exec("freeing function '%s'\n", funcp->name);
7250 *funcpp = funcp->next;
7251 /* funcp is unlinked now, deleting it.
7252 * Note: if !funcp->body, the function was created by
7253 * "-F name body", do not free ->body_as_string
7254 * and ->name as they were not malloced. */
7256 free_pipe_list(funcp->body);
7259 free(funcp->body_as_string);
7268 #define exec_function(to_free, funcp, argv) \
7269 exec_function(funcp, argv)
7271 static void exec_function(char ***to_free,
7272 const struct function *funcp,
7273 char **argv) NORETURN;
7274 static void exec_function(char ***to_free,
7275 const struct function *funcp,
7281 argv[0] = G.global_argv[0];
7282 G.global_argv = argv;
7283 G.global_argc = n = 1 + string_array_len(argv + 1);
7285 // Example when we are here: "cmd | func"
7286 // func will run with saved-redirect fds open.
7287 // $ f() { echo /proc/self/fd/*; }
7289 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7290 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7293 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7294 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7295 // They are CLOEXEC so external programs won't see them, but
7296 // for "more correctness" we might want to close those extra fds here:
7297 //? close_saved_fds_and_FILE_fds();
7299 /* "we are in function, ok to use return" */
7300 G_flag_return_in_progress = -1;
7301 IF_HUSH_LOCAL(G.func_nest_level++;)
7303 /* On MMU, funcp->body is always non-NULL */
7304 n = run_list(funcp->body);
7308 //? close_saved_fds_and_FILE_fds();
7310 //TODO: check whether "true | func_with_return" works
7312 re_execute_shell(to_free,
7313 funcp->body_as_string,
7320 static int run_function(const struct function *funcp, char **argv)
7326 save_and_replace_G_args(&sv, argv);
7328 /* "we are in function, ok to use return" */
7329 sv_flg = G_flag_return_in_progress;
7330 G_flag_return_in_progress = -1;
7331 IF_HUSH_LOCAL(G.func_nest_level++;)
7333 /* On MMU, funcp->body is always non-NULL */
7336 /* Function defined by -F */
7337 parse_and_run_string(funcp->body_as_string);
7338 rc = G.last_exitcode;
7342 rc = run_list(funcp->body);
7345 # if ENABLE_HUSH_LOCAL
7347 struct variable *var;
7348 struct variable **var_pp;
7350 var_pp = &G.top_var;
7351 while ((var = *var_pp) != NULL) {
7352 if (var->func_nest_level < G.func_nest_level) {
7353 var_pp = &var->next;
7357 if (var->flg_export)
7358 bb_unsetenv(var->varstr);
7359 /* Remove from global list */
7360 *var_pp = var->next;
7366 G.func_nest_level--;
7369 G_flag_return_in_progress = sv_flg;
7371 restore_G_args(&sv, argv);
7375 #endif /* ENABLE_HUSH_FUNCTIONS */
7379 #define exec_builtin(to_free, x, argv) \
7380 exec_builtin(x, argv)
7382 #define exec_builtin(to_free, x, argv) \
7383 exec_builtin(to_free, argv)
7385 static void exec_builtin(char ***to_free,
7386 const struct built_in_command *x,
7387 char **argv) NORETURN;
7388 static void exec_builtin(char ***to_free,
7389 const struct built_in_command *x,
7395 //? close_saved_fds_and_FILE_fds();
7396 rcode = x->b_function(argv);
7401 /* On NOMMU, we must never block!
7402 * Example: { sleep 99 | read line; } & echo Ok
7404 re_execute_shell(to_free,
7413 static void execvp_or_die(char **argv) NORETURN;
7414 static void execvp_or_die(char **argv)
7417 debug_printf_exec("execing '%s'\n", argv[0]);
7418 /* Don't propagate SIG_IGN to the child */
7419 if (SPECIAL_JOBSTOP_SIGS != 0)
7420 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7421 execvp(argv[0], argv);
7423 if (errno == EACCES) e = 126;
7424 if (errno == ENOENT) e = 127;
7425 bb_perror_msg("can't execute '%s'", argv[0]);
7429 #if ENABLE_HUSH_MODE_X
7430 static void dump_cmd_in_x_mode(char **argv)
7432 if (G_x_mode && argv) {
7433 /* We want to output the line in one write op */
7441 len += strlen(argv[n++]) + 1;
7447 p += sprintf(p, " %s", argv[n++]);
7455 # define dump_cmd_in_x_mode(argv) ((void)0)
7458 #if ENABLE_HUSH_COMMAND
7459 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7468 char *path = getenv("PATH");
7469 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
7471 _exit(1); /* PROG was not found */
7473 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7475 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
7481 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
7485 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7486 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7487 #define pseudo_exec(nommu_save, command, argv_expanded) \
7488 pseudo_exec(command, argv_expanded)
7491 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7493 * Don't exit() here. If you don't exec, use _exit instead.
7494 * The at_exit handlers apparently confuse the calling process,
7495 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7497 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7498 char **argv, int assignment_cnt,
7499 char **argv_expanded) NORETURN;
7500 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7501 char **argv, int assignment_cnt,
7502 char **argv_expanded)
7504 const struct built_in_command *x;
7506 #if ENABLE_HUSH_COMMAND
7510 new_env = expand_assignments(argv, assignment_cnt);
7511 dump_cmd_in_x_mode(new_env);
7513 if (!argv[assignment_cnt]) {
7514 /* Case when we are here: ... | var=val | ...
7515 * (note that we do not exit early, i.e., do not optimize out
7516 * expand_assignments(): think about ... | var=`sleep 1` | ...
7518 free_strings(new_env);
7519 _exit(EXIT_SUCCESS);
7523 set_vars_and_save_old(new_env);
7524 free(new_env); /* optional */
7525 /* we can also destroy set_vars_and_save_old's return value,
7528 nommu_save->new_env = new_env;
7529 nommu_save->old_vars = set_vars_and_save_old(new_env);
7532 if (argv_expanded) {
7533 argv = argv_expanded;
7535 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7537 nommu_save->argv = argv;
7540 dump_cmd_in_x_mode(argv);
7542 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7543 if (strchr(argv[0], '/') != NULL)
7547 #if ENABLE_HUSH_FUNCTIONS
7548 /* Check if the command matches any functions (this goes before bltins) */
7550 const struct function *funcp = find_function(argv[0]);
7552 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7557 #if ENABLE_HUSH_COMMAND
7558 /* "command BAR": run BAR without looking it up among functions
7559 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7560 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7562 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7567 if (p[0] != '-' || !p[1])
7568 continue; /* bash allows "command command command [-OPT] BAR" */
7576 if (p[0] != '-' || !p[1])
7578 continue; /* next arg is also -opts, process it too */
7584 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7589 # if ENABLE_HUSH_FUNCTIONS
7590 if (opt_vV && find_function(argv[0]))
7591 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7595 /* Check if the command matches any of the builtins.
7596 * Depending on context, this might be redundant. But it's
7597 * easier to waste a few CPU cycles than it is to figure out
7598 * if this is one of those cases.
7600 /* Why "BB_MMU ? :" difference in logic? -
7601 * On NOMMU, it is more expensive to re-execute shell
7602 * just in order to run echo or test builtin.
7603 * It's better to skip it here and run corresponding
7604 * non-builtin later. */
7605 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7607 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7608 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7611 #if ENABLE_FEATURE_SH_STANDALONE
7612 /* Check if the command matches any busybox applets */
7614 int a = find_applet_by_name(argv[0]);
7616 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
7617 # if BB_MMU /* see above why on NOMMU it is not allowed */
7618 if (APPLET_IS_NOEXEC(a)) {
7619 /* Do not leak open fds from opened script files etc.
7620 * Testcase: interactive "ls -l /proc/self/fd"
7621 * should not show tty fd open.
7623 close_saved_fds_and_FILE_fds();
7624 //FIXME: should also close saved redir fds
7625 /* Without this, "rm -i FILE" can't be ^C'ed: */
7626 switch_off_special_sigs(G.special_sig_mask);
7627 debug_printf_exec("running applet '%s'\n", argv[0]);
7628 run_noexec_applet_and_exit(a, argv[0], argv);
7631 /* Re-exec ourselves */
7632 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7633 /* Don't propagate SIG_IGN to the child */
7634 if (SPECIAL_JOBSTOP_SIGS != 0)
7635 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7636 execv(bb_busybox_exec_path, argv);
7637 /* If they called chroot or otherwise made the binary no longer
7638 * executable, fall through */
7643 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7646 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
7647 execvp_or_die(argv);
7650 /* Called after [v]fork() in run_pipe
7652 static void pseudo_exec(nommu_save_t *nommu_save,
7653 struct command *command,
7654 char **argv_expanded) NORETURN;
7655 static void pseudo_exec(nommu_save_t *nommu_save,
7656 struct command *command,
7657 char **argv_expanded)
7659 if (command->argv) {
7660 pseudo_exec_argv(nommu_save, command->argv,
7661 command->assignment_cnt, argv_expanded);
7664 if (command->group) {
7665 /* Cases when we are here:
7668 * ... | ( list ) | ...
7669 * ... | { list } | ...
7673 debug_printf_exec("pseudo_exec: run_list\n");
7674 reset_traps_to_defaults();
7675 rcode = run_list(command->group);
7676 /* OK to leak memory by not calling free_pipe_list,
7677 * since this process is about to exit */
7680 re_execute_shell(&nommu_save->argv_from_re_execing,
7681 command->group_as_string,
7688 /* Case when we are here: ... | >file */
7689 debug_printf_exec("pseudo_exec'ed null command\n");
7690 _exit(EXIT_SUCCESS);
7694 static const char *get_cmdtext(struct pipe *pi)
7700 /* This is subtle. ->cmdtext is created only on first backgrounding.
7701 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7702 * On subsequent bg argv is trashed, but we won't use it */
7706 argv = pi->cmds[0].argv;
7708 pi->cmdtext = xzalloc(1);
7713 len += strlen(*argv) + 1;
7717 argv = pi->cmds[0].argv;
7719 p = stpcpy(p, *argv);
7726 static void remove_job_from_table(struct pipe *pi)
7728 struct pipe *prev_pipe;
7730 if (pi == G.job_list) {
7731 G.job_list = pi->next;
7733 prev_pipe = G.job_list;
7734 while (prev_pipe->next != pi)
7735 prev_pipe = prev_pipe->next;
7736 prev_pipe->next = pi->next;
7740 G.last_jobid = G.job_list->jobid;
7743 static void delete_finished_job(struct pipe *pi)
7745 remove_job_from_table(pi);
7749 static void clean_up_last_dead_job(void)
7751 if (G.job_list && !G.job_list->alive_cmds)
7752 delete_finished_job(G.job_list);
7755 static void insert_job_into_table(struct pipe *pi)
7757 struct pipe *job, **jobp;
7760 clean_up_last_dead_job();
7762 /* Find the end of the list, and find next job ID to use */
7765 while ((job = *jobp) != NULL) {
7772 /* Create a new job struct at the end */
7773 job = *jobp = xmemdup(pi, sizeof(*pi));
7775 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7776 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7777 for (i = 0; i < pi->num_cmds; i++) {
7778 job->cmds[i].pid = pi->cmds[i].pid;
7779 /* all other fields are not used and stay zero */
7781 job->cmdtext = xstrdup(get_cmdtext(pi));
7783 if (G_interactive_fd)
7784 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7785 G.last_jobid = job->jobid;
7789 static int job_exited_or_stopped(struct pipe *pi)
7793 if (pi->alive_cmds != pi->stopped_cmds)
7796 /* All processes in fg pipe have exited or stopped */
7800 rcode = pi->cmds[i].cmd_exitcode;
7801 /* usually last process gives overall exitstatus,
7802 * but with "set -o pipefail", last *failed* process does */
7803 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7806 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7810 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7817 dead = WIFEXITED(status) || WIFSIGNALED(status);
7820 if (WIFSTOPPED(status))
7821 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7822 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7823 if (WIFSIGNALED(status))
7824 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7825 childpid, WTERMSIG(status), WEXITSTATUS(status));
7826 if (WIFEXITED(status))
7827 debug_printf_jobs("pid %d exited, exitcode %d\n",
7828 childpid, WEXITSTATUS(status));
7830 /* Were we asked to wait for a fg pipe? */
7832 i = fg_pipe->num_cmds;
7837 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7838 if (fg_pipe->cmds[i].pid != childpid)
7842 fg_pipe->cmds[i].pid = 0;
7843 fg_pipe->alive_cmds--;
7844 ex = WEXITSTATUS(status);
7845 /* bash prints killer signal's name for *last*
7846 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7847 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7849 if (WIFSIGNALED(status)) {
7850 int sig = WTERMSIG(status);
7851 if (i == fg_pipe->num_cmds-1)
7852 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7853 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7854 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7855 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7856 * Maybe we need to use sig | 128? */
7859 fg_pipe->cmds[i].cmd_exitcode = ex;
7861 fg_pipe->stopped_cmds++;
7863 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7864 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7865 rcode = job_exited_or_stopped(fg_pipe);
7867 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7868 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7869 * and "killall -STOP cat" */
7870 if (G_interactive_fd) {
7872 if (fg_pipe->alive_cmds != 0)
7873 insert_job_into_table(fg_pipe);
7877 if (fg_pipe->alive_cmds == 0)
7880 /* There are still running processes in the fg_pipe */
7883 /* It wasn't in fg_pipe, look for process in bg pipes */
7887 /* We were asked to wait for bg or orphaned children */
7888 /* No need to remember exitcode in this case */
7889 for (pi = G.job_list; pi; pi = pi->next) {
7890 for (i = 0; i < pi->num_cmds; i++) {
7891 if (pi->cmds[i].pid == childpid)
7892 goto found_pi_and_prognum;
7895 /* Happens when shell is used as init process (init=/bin/sh) */
7896 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7897 return -1; /* this wasn't a process from fg_pipe */
7899 found_pi_and_prognum:
7902 int rcode = WEXITSTATUS(status);
7903 if (WIFSIGNALED(status))
7904 rcode = 128 + WTERMSIG(status);
7905 pi->cmds[i].cmd_exitcode = rcode;
7906 if (G.last_bg_pid == pi->cmds[i].pid)
7907 G.last_bg_pid_exitcode = rcode;
7908 pi->cmds[i].pid = 0;
7910 if (!pi->alive_cmds) {
7911 if (G_interactive_fd) {
7912 printf(JOB_STATUS_FORMAT, pi->jobid,
7913 "Done", pi->cmdtext);
7914 delete_finished_job(pi);
7917 * bash deletes finished jobs from job table only in interactive mode,
7918 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7919 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7920 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7921 * We only retain one "dead" job, if it's the single job on the list.
7922 * This covers most of real-world scenarios where this is useful.
7924 if (pi != G.job_list)
7925 delete_finished_job(pi);
7933 return -1; /* this wasn't a process from fg_pipe */
7936 /* Check to see if any processes have exited -- if they have,
7937 * figure out why and see if a job has completed.
7939 * If non-NULL fg_pipe: wait for its completion or stop.
7940 * Return its exitcode or zero if stopped.
7942 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7943 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7944 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7945 * or 0 if no children changed status.
7947 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7948 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7949 * or 0 if no children changed status.
7951 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7957 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7959 attributes = WUNTRACED;
7960 if (fg_pipe == NULL)
7961 attributes |= WNOHANG;
7964 #if ENABLE_HUSH_FAST
7965 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7966 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7967 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7968 /* There was neither fork nor SIGCHLD since last waitpid */
7969 /* Avoid doing waitpid syscall if possible */
7970 if (!G.we_have_children) {
7974 if (fg_pipe == NULL) { /* is WNOHANG set? */
7975 /* We have children, but they did not exit
7976 * or stop yet (we saw no SIGCHLD) */
7979 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7983 /* Do we do this right?
7984 * bash-3.00# sleep 20 | false
7986 * [3]+ Stopped sleep 20 | false
7987 * bash-3.00# echo $?
7988 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7989 * [hush 1.14.0: yes we do it right]
7993 #if ENABLE_HUSH_FAST
7995 i = G.count_SIGCHLD;
7997 childpid = waitpid(-1, &status, attributes);
7998 if (childpid <= 0) {
7999 if (childpid && errno != ECHILD)
8000 bb_perror_msg("waitpid");
8001 #if ENABLE_HUSH_FAST
8002 else { /* Until next SIGCHLD, waitpid's are useless */
8003 G.we_have_children = (childpid == 0);
8004 G.handled_SIGCHLD = i;
8005 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8008 /* ECHILD (no children), or 0 (no change in children status) */
8012 rcode = process_wait_result(fg_pipe, childpid, status);
8014 /* fg_pipe exited or stopped */
8017 if (childpid == waitfor_pid) {
8018 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
8019 rcode = WEXITSTATUS(status);
8020 if (WIFSIGNALED(status))
8021 rcode = 128 + WTERMSIG(status);
8022 if (WIFSTOPPED(status))
8023 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8024 rcode = 128 + WSTOPSIG(status);
8026 break; /* "wait PID" called us, give it exitcode+1 */
8028 /* This wasn't one of our processes, or */
8029 /* fg_pipe still has running processes, do waitpid again */
8030 } /* while (waitpid succeeds)... */
8036 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
8039 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
8040 if (G_saved_tty_pgrp) {
8041 /* Job finished, move the shell to the foreground */
8042 p = getpgrp(); /* our process group id */
8043 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8044 tcsetpgrp(G_interactive_fd, p);
8050 /* Start all the jobs, but don't wait for anything to finish.
8053 * Return code is normally -1, when the caller has to wait for children
8054 * to finish to determine the exit status of the pipe. If the pipe
8055 * is a simple builtin command, however, the action is done by the
8056 * time run_pipe returns, and the exit code is provided as the
8059 * Returns -1 only if started some children. IOW: we have to
8060 * mask out retvals of builtins etc with 0xff!
8062 * The only case when we do not need to [v]fork is when the pipe
8063 * is single, non-backgrounded, non-subshell command. Examples:
8064 * cmd ; ... { list } ; ...
8065 * cmd && ... { list } && ...
8066 * cmd || ... { list } || ...
8067 * If it is, then we can run cmd as a builtin, NOFORK,
8068 * or (if SH_STANDALONE) an applet, and we can run the { list }
8069 * with run_list. If it isn't one of these, we fork and exec cmd.
8071 * Cases when we must fork:
8072 * non-single: cmd | cmd
8073 * backgrounded: cmd & { list } &
8074 * subshell: ( list ) [&]
8076 #if !ENABLE_HUSH_MODE_X
8077 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
8078 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
8080 static int redirect_and_varexp_helper(char ***new_env_p,
8081 struct variable **old_vars_p,
8082 struct command *command,
8083 struct squirrel **sqp,
8084 char **argv_expanded)
8086 /* setup_redirects acts on file descriptors, not FILEs.
8087 * This is perfect for work that comes after exec().
8088 * Is it really safe for inline use? Experimentally,
8089 * things seem to work. */
8090 int rcode = setup_redirects(command, sqp);
8092 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8093 *new_env_p = new_env;
8094 dump_cmd_in_x_mode(new_env);
8095 dump_cmd_in_x_mode(argv_expanded);
8097 *old_vars_p = set_vars_and_save_old(new_env);
8101 static NOINLINE int run_pipe(struct pipe *pi)
8103 static const char *const null_ptr = NULL;
8107 struct command *command;
8108 char **argv_expanded;
8110 struct squirrel *squirrel = NULL;
8113 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8116 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8117 * Result should be 3 lines: q w e, qwe, q w e
8119 G.ifs = get_local_var_value("IFS");
8123 IF_HUSH_JOB(pi->pgrp = -1;)
8124 pi->stopped_cmds = 0;
8125 command = &pi->cmds[0];
8126 argv_expanded = NULL;
8128 if (pi->num_cmds != 1
8129 || pi->followup == PIPE_BG
8130 || command->cmd_type == CMD_SUBSHELL
8137 debug_printf_exec(": group:%p argv:'%s'\n",
8138 command->group, command->argv ? command->argv[0] : "NONE");
8140 if (command->group) {
8141 #if ENABLE_HUSH_FUNCTIONS
8142 if (command->cmd_type == CMD_FUNCDEF) {
8143 /* "executing" func () { list } */
8144 struct function *funcp;
8146 funcp = new_function(command->argv[0]);
8147 /* funcp->name is already set to argv[0] */
8148 funcp->body = command->group;
8150 funcp->body_as_string = command->group_as_string;
8151 command->group_as_string = NULL;
8153 command->group = NULL;
8154 command->argv[0] = NULL;
8155 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8156 funcp->parent_cmd = command;
8157 command->child_func = funcp;
8159 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8161 return EXIT_SUCCESS;
8165 debug_printf("non-subshell group\n");
8166 rcode = 1; /* exitcode if redir failed */
8167 if (setup_redirects(command, &squirrel) == 0) {
8168 debug_printf_exec(": run_list\n");
8169 rcode = run_list(command->group) & 0xff;
8171 restore_redirects(squirrel);
8172 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8174 debug_printf_exec("run_pipe: return %d\n", rcode);
8178 argv = command->argv ? command->argv : (char **) &null_ptr;
8180 const struct built_in_command *x;
8181 #if ENABLE_HUSH_FUNCTIONS
8182 const struct function *funcp;
8186 char **new_env = NULL;
8187 struct variable *old_vars = NULL;
8189 #if ENABLE_HUSH_LINENO_VAR
8191 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8194 if (argv[command->assignment_cnt] == NULL) {
8195 /* Assignments, but no command */
8196 /* Ensure redirects take effect (that is, create files).
8197 * Try "a=t >file" */
8198 #if 0 /* A few cases in testsuite fail with this code. FIXME */
8199 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
8200 /* Set shell variables */
8204 if (set_local_var(*argv, /*flag:*/ 0)) {
8205 /* assignment to readonly var / putenv error? */
8211 /* Redirect error sets $? to 1. Otherwise,
8212 * if evaluating assignment value set $?, retain it.
8213 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8215 rcode = G.last_exitcode;
8216 /* Exit, _skipping_ variable restoring code: */
8217 goto clean_up_and_ret0;
8219 #else /* Older, bigger, but more correct code */
8221 rcode = setup_redirects(command, &squirrel);
8222 restore_redirects(squirrel);
8223 /* Set shell variables */
8225 bb_putchar_stderr('+');
8227 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8229 fprintf(stderr, " %s", p);
8230 debug_printf_exec("set shell var:'%s'->'%s'\n",
8232 if (set_local_var(p, /*flag:*/ 0)) {
8233 /* assignment to readonly var / putenv error? */
8239 bb_putchar_stderr('\n');
8240 /* Redirect error sets $? to 1. Otherwise,
8241 * if evaluating assignment value set $?, retain it.
8242 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8244 rcode = G.last_exitcode;
8245 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8247 debug_printf_exec("run_pipe: return %d\n", rcode);
8252 /* Expand the rest into (possibly) many strings each */
8254 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8255 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8259 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8262 /* if someone gives us an empty string: `cmd with empty output` */
8263 if (!argv_expanded[0]) {
8264 free(argv_expanded);
8266 return G.last_exitcode;
8269 #if ENABLE_HUSH_FUNCTIONS
8270 /* Check if argv[0] matches any functions (this goes before bltins) */
8271 funcp = find_function(argv_expanded[0]);
8275 x = find_builtin(argv_expanded[0]);
8278 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8279 debug_printf("exec with redirects only\n");
8280 rcode = setup_redirects(command, NULL);
8281 /* rcode=1 can be if redir file can't be opened */
8282 goto clean_up_and_ret1;
8285 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8288 debug_printf_exec(": builtin '%s' '%s'...\n",
8289 x->b_cmd, argv_expanded[1]);
8291 rcode = x->b_function(argv_expanded) & 0xff;
8294 #if ENABLE_HUSH_FUNCTIONS
8296 # if ENABLE_HUSH_LOCAL
8297 struct variable **sv;
8298 sv = G.shadowed_vars_pp;
8299 G.shadowed_vars_pp = &old_vars;
8301 debug_printf_exec(": function '%s' '%s'...\n",
8302 funcp->name, argv_expanded[1]);
8303 rcode = run_function(funcp, argv_expanded) & 0xff;
8304 # if ENABLE_HUSH_LOCAL
8305 G.shadowed_vars_pp = sv;
8311 unset_vars(new_env);
8313 /* clean_up_and_ret0: */
8314 restore_redirects(squirrel);
8316 * Try "usleep 99999999" + ^C + "echo $?"
8317 * with FEATURE_SH_NOFORK=y.
8320 /* It was builtin or nofork.
8321 * if this would be a real fork/execed program,
8322 * it should have died if a fatal sig was received.
8323 * But OTOH, there was no separate process,
8324 * the sig was sent to _shell_, not to non-existing
8326 * Let's just handle ^C only, this one is obvious:
8327 * we aren't ok with exitcode 0 when ^C was pressed
8328 * during builtin/nofork.
8330 if (sigismember(&G.pending_set, SIGINT))
8331 rcode = 128 + SIGINT;
8334 free(argv_expanded);
8335 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8337 debug_printf_exec("run_pipe return %d\n", rcode);
8341 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
8342 int n = find_applet_by_name(argv_expanded[0]);
8343 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8344 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8346 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8347 argv_expanded[0], argv_expanded[1]);
8349 * Note: signals (^C) can't interrupt here.
8350 * We remember them and they will be acted upon
8351 * after applet returns.
8352 * This makes applets which can run for a long time
8353 * and/or wait for user input ineligible for NOFORK:
8354 * for example, "yes" or "rm" (rm -i waits for input).
8356 rcode = run_nofork_applet(n, argv_expanded);
8358 goto clean_up_and_ret;
8361 /* It is neither builtin nor applet. We must fork. */
8365 /* NB: argv_expanded may already be created, and that
8366 * might include `cmd` runs! Do not rerun it! We *must*
8367 * use argv_expanded if it's non-NULL */
8369 /* Going to fork a child per each pipe member */
8374 while (cmd_no < pi->num_cmds) {
8375 struct fd_pair pipefds;
8377 volatile nommu_save_t nommu_save;
8378 nommu_save.new_env = NULL;
8379 nommu_save.old_vars = NULL;
8380 nommu_save.argv = NULL;
8381 nommu_save.argv_from_re_execing = NULL;
8383 command = &pi->cmds[cmd_no];
8385 if (command->argv) {
8386 debug_printf_exec(": pipe member '%s' '%s'...\n",
8387 command->argv[0], command->argv[1]);
8389 debug_printf_exec(": pipe member with no argv\n");
8392 /* pipes are inserted between pairs of commands */
8395 if (cmd_no < pi->num_cmds)
8396 xpiped_pair(pipefds);
8398 #if ENABLE_HUSH_LINENO_VAR
8400 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8403 command->pid = BB_MMU ? fork() : vfork();
8404 if (!command->pid) { /* child */
8406 disable_restore_tty_pgrp_on_exit();
8407 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8409 /* Every child adds itself to new process group
8410 * with pgid == pid_of_first_child_in_pipe */
8411 if (G.run_list_level == 1 && G_interactive_fd) {
8414 if (pgrp < 0) /* true for 1st process only */
8416 if (setpgid(0, pgrp) == 0
8417 && pi->followup != PIPE_BG
8418 && G_saved_tty_pgrp /* we have ctty */
8420 /* We do it in *every* child, not just first,
8422 tcsetpgrp(G_interactive_fd, pgrp);
8426 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8427 /* 1st cmd in backgrounded pipe
8428 * should have its stdin /dev/null'ed */
8430 if (open(bb_dev_null, O_RDONLY))
8431 xopen("/", O_RDONLY);
8433 xmove_fd(next_infd, 0);
8435 xmove_fd(pipefds.wr, 1);
8438 /* Like bash, explicit redirects override pipes,
8439 * and the pipe fd (fd#1) is available for dup'ing:
8440 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8441 * of cmd1 goes into pipe.
8443 if (setup_redirects(command, NULL)) {
8444 /* Happens when redir file can't be opened:
8445 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8447 * hush: can't open '/qwe/rty': No such file or directory
8449 * (echo BAR is not executed, it hits _exit(1) below)
8454 /* Stores to nommu_save list of env vars putenv'ed
8455 * (NOMMU, on MMU we don't need that) */
8456 /* cast away volatility... */
8457 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8458 /* pseudo_exec() does not return */
8461 /* parent or error */
8462 #if ENABLE_HUSH_FAST
8464 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8466 enable_restore_tty_pgrp_on_exit();
8468 /* Clean up after vforked child */
8469 free(nommu_save.argv);
8470 free(nommu_save.argv_from_re_execing);
8471 unset_vars(nommu_save.new_env);
8472 add_vars(nommu_save.old_vars);
8474 free(argv_expanded);
8475 argv_expanded = NULL;
8476 if (command->pid < 0) { /* [v]fork failed */
8477 /* Clearly indicate, was it fork or vfork */
8478 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8482 /* Second and next children need to know pid of first one */
8484 pi->pgrp = command->pid;
8490 if (cmd_no < pi->num_cmds)
8492 /* Pass read (output) pipe end to next iteration */
8493 next_infd = pipefds.rd;
8496 if (!pi->alive_cmds) {
8498 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8503 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8507 /* NB: called by pseudo_exec, and therefore must not modify any
8508 * global data until exec/_exit (we can be a child after vfork!) */
8509 static int run_list(struct pipe *pi)
8511 #if ENABLE_HUSH_CASE
8512 char *case_word = NULL;
8514 #if ENABLE_HUSH_LOOPS
8515 struct pipe *loop_top = NULL;
8516 char **for_lcur = NULL;
8517 char **for_list = NULL;
8519 smallint last_followup;
8521 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8522 smalluint cond_code = 0;
8524 enum { cond_code = 0 };
8527 smallint rword; /* RES_foo */
8528 smallint last_rword; /* ditto */
8531 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8534 #if ENABLE_HUSH_LOOPS
8535 /* Check syntax for "for" */
8538 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8539 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8541 /* current word is FOR or IN (BOLD in comments below) */
8542 if (cpipe->next == NULL) {
8543 syntax_error("malformed for");
8545 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8548 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8549 if (cpipe->next->res_word == RES_DO)
8551 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8552 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8553 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8555 syntax_error("malformed for");
8557 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8564 /* Past this point, all code paths should jump to ret: label
8565 * in order to return, no direct "return" statements please.
8566 * This helps to ensure that no memory is leaked. */
8574 last_rword = RES_XXXX;
8576 last_followup = PIPE_SEQ;
8577 rcode = G.last_exitcode;
8579 /* Go through list of pipes, (maybe) executing them. */
8580 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8582 int sv_errexit_depth;
8586 if (G_flag_return_in_progress == 1)
8589 IF_HAS_KEYWORDS(rword = pi->res_word;)
8590 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8591 rword, cond_code, last_rword);
8593 sv_errexit_depth = G.errexit_depth;
8596 rword == RES_IF || rword == RES_ELIF ||
8598 pi->followup != PIPE_SEQ
8602 #if ENABLE_HUSH_LOOPS
8603 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8604 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8606 /* start of a loop: remember where loop starts */
8611 /* Still in the same "if...", "then..." or "do..." branch? */
8612 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8613 if ((rcode == 0 && last_followup == PIPE_OR)
8614 || (rcode != 0 && last_followup == PIPE_AND)
8616 /* It is "<true> || CMD" or "<false> && CMD"
8617 * and we should not execute CMD */
8618 debug_printf_exec("skipped cmd because of || or &&\n");
8619 last_followup = pi->followup;
8620 goto dont_check_jobs_but_continue;
8623 last_followup = pi->followup;
8624 IF_HAS_KEYWORDS(last_rword = rword;)
8627 if (rword == RES_THEN) {
8628 /* if false; then ... fi has exitcode 0! */
8629 G.last_exitcode = rcode = EXIT_SUCCESS;
8630 /* "if <false> THEN cmd": skip cmd */
8634 if (rword == RES_ELSE || rword == RES_ELIF) {
8635 /* "if <true> then ... ELSE/ELIF cmd":
8636 * skip cmd and all following ones */
8641 #if ENABLE_HUSH_LOOPS
8642 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8644 /* first loop through for */
8646 static const char encoded_dollar_at[] ALIGN1 = {
8647 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8648 }; /* encoded representation of "$@" */
8649 static const char *const encoded_dollar_at_argv[] = {
8650 encoded_dollar_at, NULL
8651 }; /* argv list with one element: "$@" */
8654 vals = (char**)encoded_dollar_at_argv;
8655 if (pi->next->res_word == RES_IN) {
8656 /* if no variable values after "in" we skip "for" */
8657 if (!pi->next->cmds[0].argv) {
8658 G.last_exitcode = rcode = EXIT_SUCCESS;
8659 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8662 vals = pi->next->cmds[0].argv;
8663 } /* else: "for var; do..." -> assume "$@" list */
8664 /* create list of variable values */
8665 debug_print_strings("for_list made from", vals);
8666 for_list = expand_strvec_to_strvec(vals);
8667 for_lcur = for_list;
8668 debug_print_strings("for_list", for_list);
8671 /* "for" loop is over, clean up */
8677 /* Insert next value from for_lcur */
8678 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8679 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8682 if (rword == RES_IN) {
8683 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8685 if (rword == RES_DONE) {
8686 continue; /* "done" has no cmds too */
8689 #if ENABLE_HUSH_CASE
8690 if (rword == RES_CASE) {
8691 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8692 case_word = expand_strvec_to_string(pi->cmds->argv);
8693 unbackslash(case_word);
8696 if (rword == RES_MATCH) {
8699 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8700 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8702 /* all prev words didn't match, does this one match? */
8703 argv = pi->cmds->argv;
8705 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8706 /* TODO: which FNM_xxx flags to use? */
8707 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8708 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8710 if (cond_code == 0) { /* match! we will execute this branch */
8712 case_word = NULL; /* make future "word)" stop */
8719 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8720 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8722 continue; /* not matched yet, skip this pipe */
8724 if (rword == RES_ESAC) {
8725 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8727 /* "case" did not match anything: still set $? (to 0) */
8728 G.last_exitcode = rcode = EXIT_SUCCESS;
8732 /* Just pressing <enter> in shell should check for jobs.
8733 * OTOH, in non-interactive shell this is useless
8734 * and only leads to extra job checks */
8735 if (pi->num_cmds == 0) {
8736 if (G_interactive_fd)
8737 goto check_jobs_and_continue;
8741 /* After analyzing all keywords and conditions, we decided
8742 * to execute this pipe. NB: have to do checkjobs(NULL)
8743 * after run_pipe to collect any background children,
8744 * even if list execution is to be stopped. */
8745 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8746 #if ENABLE_HUSH_LOOPS
8747 G.flag_break_continue = 0;
8749 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8751 /* We ran a builtin, function, or group.
8752 * rcode is already known
8753 * and we don't need to wait for anything. */
8754 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8755 G.last_exitcode = rcode;
8756 check_and_run_traps();
8757 #if ENABLE_HUSH_LOOPS
8758 /* Was it "break" or "continue"? */
8759 if (G.flag_break_continue) {
8760 smallint fbc = G.flag_break_continue;
8761 /* We might fall into outer *loop*,
8762 * don't want to break it too */
8764 G.depth_break_continue--;
8765 if (G.depth_break_continue == 0)
8766 G.flag_break_continue = 0;
8767 /* else: e.g. "continue 2" should *break* once, *then* continue */
8768 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8769 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8770 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8773 /* "continue": simulate end of loop */
8778 if (G_flag_return_in_progress == 1) {
8779 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8782 } else if (pi->followup == PIPE_BG) {
8783 /* What does bash do with attempts to background builtins? */
8784 /* even bash 3.2 doesn't do that well with nested bg:
8785 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8786 * I'm NOT treating inner &'s as jobs */
8788 if (G.run_list_level == 1)
8789 insert_job_into_table(pi);
8791 /* Last command's pid goes to $! */
8792 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8793 G.last_bg_pid_exitcode = 0;
8794 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8795 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8796 rcode = EXIT_SUCCESS;
8800 if (G.run_list_level == 1 && G_interactive_fd) {
8801 /* Waits for completion, then fg's main shell */
8802 rcode = checkjobs_and_fg_shell(pi);
8803 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8807 /* This one just waits for completion */
8808 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8809 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8811 G.last_exitcode = rcode;
8812 check_and_run_traps();
8815 /* Handle "set -e" */
8816 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8817 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8818 if (G.errexit_depth == 0)
8821 G.errexit_depth = sv_errexit_depth;
8823 /* Analyze how result affects subsequent commands */
8825 if (rword == RES_IF || rword == RES_ELIF)
8828 check_jobs_and_continue:
8829 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8830 dont_check_jobs_but_continue: ;
8831 #if ENABLE_HUSH_LOOPS
8832 /* Beware of "while false; true; do ..."! */
8834 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8835 /* check for RES_DONE is needed for "while ...; do \n done" case */
8837 if (rword == RES_WHILE) {
8839 /* "while false; do...done" - exitcode 0 */
8840 G.last_exitcode = rcode = EXIT_SUCCESS;
8841 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8845 if (rword == RES_UNTIL) {
8847 debug_printf_exec(": until expr is true: breaking\n");
8858 #if ENABLE_HUSH_LOOPS
8863 #if ENABLE_HUSH_CASE
8867 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8871 /* Select which version we will use */
8872 static int run_and_free_list(struct pipe *pi)
8875 debug_printf_exec("run_and_free_list entered\n");
8876 if (!G.o_opt[OPT_O_NOEXEC]) {
8877 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8878 rcode = run_list(pi);
8880 /* free_pipe_list has the side effect of clearing memory.
8881 * In the long run that function can be merged with run_list,
8882 * but doing that now would hobble the debugging effort. */
8884 debug_printf_exec("run_and_free_list return %d\n", rcode);
8889 static void install_sighandlers(unsigned mask)
8891 sighandler_t old_handler;
8893 while ((mask >>= 1) != 0) {
8897 old_handler = install_sighandler(sig, pick_sighandler(sig));
8898 /* POSIX allows shell to re-enable SIGCHLD
8899 * even if it was SIG_IGN on entry.
8900 * Therefore we skip IGN check for it:
8904 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8905 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8907 //if (sig == SIGHUP) continue; - TODO?
8908 if (old_handler == SIG_IGN) {
8909 /* oops... restore back to IGN, and record this fact */
8910 install_sighandler(sig, old_handler);
8911 #if ENABLE_HUSH_TRAP
8913 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8915 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8921 /* Called a few times only (or even once if "sh -c") */
8922 static void install_special_sighandlers(void)
8926 /* Which signals are shell-special? */
8927 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8928 if (G_interactive_fd) {
8929 mask |= SPECIAL_INTERACTIVE_SIGS;
8930 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8931 mask |= SPECIAL_JOBSTOP_SIGS;
8933 /* Careful, do not re-install handlers we already installed */
8934 if (G.special_sig_mask != mask) {
8935 unsigned diff = mask & ~G.special_sig_mask;
8936 G.special_sig_mask = mask;
8937 install_sighandlers(diff);
8943 /* Set handlers to restore tty pgrp and exit */
8944 static void install_fatal_sighandlers(void)
8948 /* We will restore tty pgrp on these signals */
8950 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8951 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8952 + (1 << SIGBUS ) * HUSH_DEBUG
8953 + (1 << SIGSEGV) * HUSH_DEBUG
8954 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8956 /* bash 3.2 seems to handle these just like 'fatal' ones */
8959 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8960 * if we aren't interactive... but in this case
8961 * we never want to restore pgrp on exit, and this fn is not called
8963 /*+ (1 << SIGHUP )*/
8964 /*+ (1 << SIGTERM)*/
8965 /*+ (1 << SIGINT )*/
8967 G_fatal_sig_mask = mask;
8969 install_sighandlers(mask);
8973 static int set_mode(int state, char mode, const char *o_opt)
8978 G.o_opt[OPT_O_NOEXEC] = state;
8981 IF_HUSH_MODE_X(G_x_mode = state;)
8985 /* "set -+o" without parameter.
8986 * in bash, set -o produces this output:
8990 * We always use the second form.
8992 const char *p = o_opt_strings;
8995 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9001 idx = index_in_strings(o_opt_strings, o_opt);
9003 G.o_opt[idx] = state;
9007 G.o_opt[OPT_O_ERREXIT] = state;
9010 return EXIT_FAILURE;
9012 return EXIT_SUCCESS;
9015 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
9016 int hush_main(int argc, char **argv)
9019 OPT_login = (1 << 0),
9023 unsigned builtin_argc;
9025 struct variable *cur_var;
9026 struct variable *shell_ver;
9029 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
9030 G.last_exitcode = EXIT_SUCCESS;
9032 #if ENABLE_HUSH_FAST
9033 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9036 G.argv0_for_re_execing = argv[0];
9039 /* Deal with HUSH_VERSION */
9040 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9041 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
9042 shell_ver = xzalloc(sizeof(*shell_ver));
9043 shell_ver->flg_export = 1;
9044 shell_ver->flg_read_only = 1;
9045 /* Code which handles ${var<op>...} needs writable values for all variables,
9046 * therefore we xstrdup: */
9047 shell_ver->varstr = xstrdup(hush_version_str);
9049 /* Create shell local variables from the values
9050 * currently living in the environment */
9051 G.top_var = shell_ver;
9052 cur_var = G.top_var;
9055 char *value = strchr(*e, '=');
9056 if (value) { /* paranoia */
9057 cur_var->next = xzalloc(sizeof(*cur_var));
9058 cur_var = cur_var->next;
9059 cur_var->varstr = *e;
9060 cur_var->max_len = strlen(*e);
9061 cur_var->flg_export = 1;
9065 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
9066 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9067 putenv(shell_ver->varstr);
9070 set_pwd_var(SETFLAG_EXPORT);
9072 #if BASH_HOSTNAME_VAR
9073 /* Set (but not export) HOSTNAME unless already set */
9074 if (!get_local_var_value("HOSTNAME")) {
9077 set_local_var_from_halves("HOSTNAME", uts.nodename);
9079 /* bash also exports SHLVL and _,
9080 * and sets (but doesn't export) the following variables:
9082 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9083 * BASH_VERSION='3.2.0(1)-release'
9085 * MACHTYPE=i386-pc-linux-gnu
9087 * PPID=<NNNNN> - we also do it elsewhere
9098 * PIPESTATUS=([0]="0")
9099 * HISTFILE=/<xxx>/.bash_history
9103 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9105 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9116 #if ENABLE_HUSH_LINENO_VAR
9117 if (ENABLE_HUSH_LINENO_VAR) {
9118 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9119 set_local_var(p, /*flags*/ 0);
9120 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9124 #if ENABLE_FEATURE_EDITING
9125 G.line_input_state = new_line_input_t(FOR_SHELL);
9128 /* Initialize some more globals to non-zero values */
9129 cmdedit_update_prompt();
9131 die_func = restore_ttypgrp_and__exit;
9133 /* Shell is non-interactive at first. We need to call
9134 * install_special_sighandlers() if we are going to execute "sh <script>",
9135 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9136 * If we later decide that we are interactive, we run install_special_sighandlers()
9137 * in order to intercept (more) signals.
9141 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9142 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9145 opt = getopt(argc, argv, "+c:exinsl"
9148 # if ENABLE_HUSH_FUNCTIONS
9158 * sh ... -c 'script'
9159 * sh ... -c 'script' ARG0 [ARG1...]
9160 * On NOMMU, if builtin_argc != 0,
9161 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9162 * "" needs to be replaced with NULL
9163 * and BARGV vector fed to builtin function.
9164 * Note: the form without ARG0 never happens:
9165 * sh ... -c 'builtin' BARGV... ""
9168 G.root_pid = getpid();
9169 G.root_ppid = getppid();
9171 G.global_argv = argv + optind;
9172 G.global_argc = argc - optind;
9174 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9175 const struct built_in_command *x;
9177 install_special_sighandlers();
9178 x = find_builtin(optarg);
9179 if (x) { /* paranoia */
9180 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9181 G.global_argv += builtin_argc;
9182 G.global_argv[-1] = NULL; /* replace "" */
9184 G.last_exitcode = x->b_function(argv + optind - 1);
9188 if (!G.global_argv[0]) {
9189 /* -c 'script' (no params): prevent empty $0 */
9190 G.global_argv--; /* points to argv[i] of 'script' */
9191 G.global_argv[0] = argv[0];
9193 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
9194 install_special_sighandlers();
9195 parse_and_run_string(optarg);
9198 /* Well, we cannot just declare interactiveness,
9199 * we have to have some stuff (ctty, etc) */
9200 /* G_interactive_fd++; */
9203 /* "-s" means "read from stdin", but this is how we always
9204 * operate, so simply do nothing here. */
9210 case '<': /* "big heredoc" support */
9211 full_write1_str(optarg);
9214 unsigned long long empty_trap_mask;
9216 G.root_pid = bb_strtou(optarg, &optarg, 16);
9218 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9220 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9222 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
9224 builtin_argc = bb_strtou(optarg, &optarg, 16);
9226 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9227 if (empty_trap_mask != 0) {
9228 IF_HUSH_TRAP(int sig;)
9229 install_special_sighandlers();
9230 # if ENABLE_HUSH_TRAP
9231 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9232 for (sig = 1; sig < NSIG; sig++) {
9233 if (empty_trap_mask & (1LL << sig)) {
9234 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9235 install_sighandler(sig, SIG_IGN);
9240 # if ENABLE_HUSH_LOOPS
9242 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
9248 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9250 # if ENABLE_HUSH_FUNCTIONS
9252 struct function *funcp = new_function(optarg);
9253 /* funcp->name is already set to optarg */
9254 /* funcp->body is set to NULL. It's a special case. */
9255 funcp->body_as_string = argv[optind];
9264 if (set_mode(1, opt, NULL) == 0) /* no error */
9268 fprintf(stderr, "Usage: sh [FILE]...\n"
9269 " or: sh -c command [args]...\n\n");
9275 } /* option parsing loop */
9277 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9278 G.global_argc = argc - (optind - 1);
9279 G.global_argv = argv + (optind - 1);
9280 G.global_argv[0] = argv[0];
9283 G.root_pid = getpid();
9284 G.root_ppid = getppid();
9287 /* If we are login shell... */
9288 if (flags & OPT_login) {
9290 debug_printf("sourcing /etc/profile\n");
9291 input = fopen_for_read("/etc/profile");
9292 if (input != NULL) {
9293 remember_FILE(input);
9294 install_special_sighandlers();
9295 parse_and_run_file(input);
9296 fclose_and_forget(input);
9298 /* bash: after sourcing /etc/profile,
9299 * tries to source (in the given order):
9300 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9301 * stopping on first found. --noprofile turns this off.
9302 * bash also sources ~/.bash_logout on exit.
9303 * If called as sh, skips .bash_XXX files.
9307 if (G.global_argv[1]) {
9310 * "bash <script>" (which is never interactive (unless -i?))
9311 * sources $BASH_ENV here (without scanning $PATH).
9312 * If called as sh, does the same but with $ENV.
9313 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9317 debug_printf("running script '%s'\n", G.global_argv[0]);
9318 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9319 input = xfopen_for_read(G.global_argv[0]);
9320 xfunc_error_retval = 1;
9321 remember_FILE(input);
9322 install_special_sighandlers();
9323 parse_and_run_file(input);
9324 #if ENABLE_FEATURE_CLEAN_UP
9325 fclose_and_forget(input);
9330 /* Up to here, shell was non-interactive. Now it may become one.
9331 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9334 /* A shell is interactive if the '-i' flag was given,
9335 * or if all of the following conditions are met:
9337 * no arguments remaining or the -s flag given
9338 * standard input is a terminal
9339 * standard output is a terminal
9340 * Refer to Posix.2, the description of the 'sh' utility.
9343 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9344 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9345 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9346 if (G_saved_tty_pgrp < 0)
9347 G_saved_tty_pgrp = 0;
9349 /* try to dup stdin to high fd#, >= 255 */
9350 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9351 if (G_interactive_fd < 0) {
9352 /* try to dup to any fd */
9353 G_interactive_fd = dup(STDIN_FILENO);
9354 if (G_interactive_fd < 0) {
9356 G_interactive_fd = 0;
9357 G_saved_tty_pgrp = 0;
9360 // TODO: track & disallow any attempts of user
9361 // to (inadvertently) close/redirect G_interactive_fd
9363 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9364 if (G_interactive_fd) {
9365 close_on_exec_on(G_interactive_fd);
9367 if (G_saved_tty_pgrp) {
9368 /* If we were run as 'hush &', sleep until we are
9369 * in the foreground (tty pgrp == our pgrp).
9370 * If we get started under a job aware app (like bash),
9371 * make sure we are now in charge so we don't fight over
9372 * who gets the foreground */
9374 pid_t shell_pgrp = getpgrp();
9375 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9376 if (G_saved_tty_pgrp == shell_pgrp)
9378 /* send TTIN to ourself (should stop us) */
9379 kill(- shell_pgrp, SIGTTIN);
9383 /* Install more signal handlers */
9384 install_special_sighandlers();
9386 if (G_saved_tty_pgrp) {
9387 /* Set other signals to restore saved_tty_pgrp */
9388 install_fatal_sighandlers();
9389 /* Put ourselves in our own process group
9390 * (bash, too, does this only if ctty is available) */
9391 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9392 /* Grab control of the terminal */
9393 tcsetpgrp(G_interactive_fd, getpid());
9395 enable_restore_tty_pgrp_on_exit();
9397 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9399 const char *hp = get_local_var_value("HISTFILE");
9401 hp = get_local_var_value("HOME");
9403 hp = concat_path_file(hp, ".hush_history");
9408 G.line_input_state->hist_file = hp;
9409 //set_local_var(xasprintf("HISTFILE=%s", ...));
9411 # if ENABLE_FEATURE_SH_HISTFILESIZE
9412 hp = get_local_var_value("HISTFILESIZE");
9413 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9418 install_special_sighandlers();
9420 #elif ENABLE_HUSH_INTERACTIVE
9421 /* No job control compiled in, only prompt/line editing */
9422 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9423 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9424 if (G_interactive_fd < 0) {
9425 /* try to dup to any fd */
9426 G_interactive_fd = dup(STDIN_FILENO);
9427 if (G_interactive_fd < 0)
9429 G_interactive_fd = 0;
9432 if (G_interactive_fd) {
9433 close_on_exec_on(G_interactive_fd);
9435 install_special_sighandlers();
9437 /* We have interactiveness code disabled */
9438 install_special_sighandlers();
9441 * if interactive but not a login shell, sources ~/.bashrc
9442 * (--norc turns this off, --rcfile <file> overrides)
9445 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9446 /* note: ash and hush share this string */
9447 printf("\n\n%s %s\n"
9448 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9451 "hush - the humble shell"
9455 parse_and_run_file(stdin);
9458 hush_exit(G.last_exitcode);
9465 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9470 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9471 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9473 int argc = string_array_len(argv);
9474 return applet_main_func(argc, argv);
9477 #if ENABLE_HUSH_TEST || BASH_TEST2
9478 static int FAST_FUNC builtin_test(char **argv)
9480 return run_applet_main(argv, test_main);
9483 #if ENABLE_HUSH_ECHO
9484 static int FAST_FUNC builtin_echo(char **argv)
9486 return run_applet_main(argv, echo_main);
9489 #if ENABLE_HUSH_PRINTF
9490 static int FAST_FUNC builtin_printf(char **argv)
9492 return run_applet_main(argv, printf_main);
9496 #if ENABLE_HUSH_HELP
9497 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9499 const struct built_in_command *x;
9502 "Built-in commands:\n"
9503 "------------------\n");
9504 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9506 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9508 return EXIT_SUCCESS;
9512 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9513 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9515 show_history(G.line_input_state);
9516 return EXIT_SUCCESS;
9520 static char **skip_dash_dash(char **argv)
9523 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9528 static int FAST_FUNC builtin_cd(char **argv)
9532 argv = skip_dash_dash(argv);
9534 if (newdir == NULL) {
9535 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9536 * bash says "bash: cd: HOME not set" and does nothing
9539 const char *home = get_local_var_value("HOME");
9540 newdir = home ? home : "/";
9542 if (chdir(newdir)) {
9543 /* Mimic bash message exactly */
9544 bb_perror_msg("cd: %s", newdir);
9545 return EXIT_FAILURE;
9547 /* Read current dir (get_cwd(1) is inside) and set PWD.
9548 * Note: do not enforce exporting. If PWD was unset or unexported,
9549 * set it again, but do not export. bash does the same.
9551 set_pwd_var(/*flag:*/ 0);
9552 return EXIT_SUCCESS;
9555 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9558 return EXIT_SUCCESS;
9561 static int FAST_FUNC builtin_eval(char **argv)
9563 int rcode = EXIT_SUCCESS;
9565 argv = skip_dash_dash(argv);
9570 /* "The eval utility shall construct a command by
9571 * concatenating arguments together, separating
9572 * each with a <space> character."
9578 len += strlen(*pp) + 1;
9580 str = p = xmalloc(len);
9590 * eval "echo Hi; done" ("done" is syntax error):
9591 * "echo Hi" will not execute too.
9593 parse_and_run_string(str ? str : argv[0]);
9595 rcode = G.last_exitcode;
9600 static int FAST_FUNC builtin_exec(char **argv)
9602 argv = skip_dash_dash(argv);
9603 if (argv[0] == NULL)
9604 return EXIT_SUCCESS; /* bash does this */
9606 /* Careful: we can end up here after [v]fork. Do not restore
9607 * tty pgrp then, only top-level shell process does that */
9608 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9609 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9611 /* Saved-redirect fds, script fds and G_interactive_fd are still
9612 * open here. However, they are all CLOEXEC, and execv below
9613 * closes them. Try interactive "exec ls -l /proc/self/fd",
9614 * it should show no extra open fds in the "ls" process.
9615 * If we'd try to run builtins/NOEXECs, this would need improving.
9617 //close_saved_fds_and_FILE_fds();
9619 /* TODO: if exec fails, bash does NOT exit! We do.
9620 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9621 * and tcsetpgrp, and this is inherently racy.
9623 execvp_or_die(argv);
9626 static int FAST_FUNC builtin_exit(char **argv)
9628 debug_printf_exec("%s()\n", __func__);
9630 /* interactive bash:
9631 * # trap "echo EEE" EXIT
9634 * There are stopped jobs.
9635 * (if there are _stopped_ jobs, running ones don't count)
9638 * EEE (then bash exits)
9640 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9643 /* note: EXIT trap is run by hush_exit */
9644 argv = skip_dash_dash(argv);
9645 if (argv[0] == NULL)
9646 hush_exit(G.last_exitcode);
9647 /* mimic bash: exit 123abc == exit 255 + error msg */
9648 xfunc_error_retval = 255;
9649 /* bash: exit -2 == exit 254, no error msg */
9650 hush_exit(xatoi(argv[0]) & 0xff);
9653 #if ENABLE_HUSH_TYPE
9654 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9655 static int FAST_FUNC builtin_type(char **argv)
9657 int ret = EXIT_SUCCESS;
9663 if (0) {} /* make conditional compile easier below */
9664 /*else if (find_alias(*argv))
9665 type = "an alias";*/
9666 #if ENABLE_HUSH_FUNCTIONS
9667 else if (find_function(*argv))
9668 type = "a function";
9670 else if (find_builtin(*argv))
9671 type = "a shell builtin";
9672 else if ((path = find_in_path(*argv)) != NULL)
9675 bb_error_msg("type: %s: not found", *argv);
9680 printf("%s is %s\n", *argv, type);
9688 #if ENABLE_HUSH_READ
9689 /* Interruptibility of read builtin in bash
9690 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9692 * Empty trap makes read ignore corresponding signal, for any signal.
9695 * - terminates non-interactive shell;
9696 * - interrupts read in interactive shell;
9697 * if it has non-empty trap:
9698 * - executes trap and returns to command prompt in interactive shell;
9699 * - executes trap and returns to read in non-interactive shell;
9701 * - is ignored (does not interrupt) read in interactive shell;
9702 * - terminates non-interactive shell;
9703 * if it has non-empty trap:
9704 * - executes trap and returns to read;
9706 * - terminates shell (regardless of interactivity);
9707 * if it has non-empty trap:
9708 * - executes trap and returns to read;
9709 * SIGCHLD from children:
9710 * - does not interrupt read regardless of interactivity:
9711 * try: sleep 1 & read x; echo $x
9713 static int FAST_FUNC builtin_read(char **argv)
9720 char *opt_d = NULL; /* optimized out if !BASH */
9724 /* "!": do not abort on errors.
9725 * Option string must start with "sr" to match BUILTIN_READ_xxx
9727 read_flags = getopt32(argv,
9729 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9731 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9734 if (read_flags == (uint32_t)-1)
9735 return EXIT_FAILURE;
9737 ifs = get_local_var_value("IFS"); /* can be NULL */
9740 r = shell_builtin_read(set_local_var_from_halves,
9751 if ((uintptr_t)r == 1 && errno == EINTR) {
9752 unsigned sig = check_and_run_traps();
9757 if ((uintptr_t)r > 1) {
9758 bb_error_msg("%s", r);
9759 r = (char*)(uintptr_t)1;
9762 return (uintptr_t)r;
9766 #if ENABLE_HUSH_UMASK
9767 static int FAST_FUNC builtin_umask(char **argv)
9774 argv = skip_dash_dash(argv);
9776 mode_t old_mask = mask;
9778 /* numeric umasks are taken as-is */
9779 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9780 if (!isdigit(argv[0][0]))
9782 mask = bb_parse_mode(argv[0], mask);
9783 if (!isdigit(argv[0][0]))
9785 if ((unsigned)mask > 0777) {
9788 * bash: umask: 'q': invalid symbolic mode operator
9789 * bash: umask: 999: octal number out of range
9791 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9796 printf("%04o\n", (unsigned) mask);
9797 /* fall through and restore mask which we set to 0 */
9801 return !rc; /* rc != 0 - success */
9805 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9806 static void print_escaped(const char *s)
9811 const char *p = strchrnul(s, '\'');
9812 /* print 'xxxx', possibly just '' */
9813 printf("'%.*s'", (int)(p - s), s);
9818 /* s points to '; print "'''...'''" */
9820 do putchar('\''); while (*++s == '\'');
9826 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9827 static int helper_export_local(char **argv, unsigned flags)
9831 char *name_end = strchrnul(name, '=');
9833 /* So far we do not check that name is valid (TODO?) */
9835 if (*name_end == '\0') {
9836 struct variable *var, **vpp;
9838 vpp = get_ptr_to_local_var(name, name_end - name);
9839 var = vpp ? *vpp : NULL;
9841 if (flags & SETFLAG_UNEXPORT) {
9842 /* export -n NAME (without =VALUE) */
9844 var->flg_export = 0;
9845 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9847 } /* else: export -n NOT_EXISTING_VAR: no-op */
9850 if (flags & SETFLAG_EXPORT) {
9851 /* export NAME (without =VALUE) */
9853 var->flg_export = 1;
9854 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9855 putenv(var->varstr);
9859 if (flags & SETFLAG_MAKE_RO) {
9860 /* readonly NAME (without =VALUE) */
9862 var->flg_read_only = 1;
9866 # if ENABLE_HUSH_LOCAL
9867 /* Is this "local" bltin? */
9868 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9869 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9870 if (var && var->func_nest_level == lvl) {
9871 /* "local x=abc; ...; local x" - ignore second local decl */
9876 /* Exporting non-existing variable.
9877 * bash does not put it in environment,
9878 * but remembers that it is exported,
9879 * and does put it in env when it is set later.
9880 * We just set it to "" and export.
9882 /* Or, it's "local NAME" (without =VALUE).
9883 * bash sets the value to "".
9885 /* Or, it's "readonly NAME" (without =VALUE).
9886 * bash remembers NAME and disallows its creation
9889 name = xasprintf("%s=", name);
9891 /* (Un)exporting/making local NAME=VALUE */
9892 name = xstrdup(name);
9894 if (set_local_var(name, flags))
9895 return EXIT_FAILURE;
9897 return EXIT_SUCCESS;
9901 #if ENABLE_HUSH_EXPORT
9902 static int FAST_FUNC builtin_export(char **argv)
9904 unsigned opt_unexport;
9906 #if ENABLE_HUSH_EXPORT_N
9907 /* "!": do not abort on errors */
9908 opt_unexport = getopt32(argv, "!n");
9909 if (opt_unexport == (uint32_t)-1)
9910 return EXIT_FAILURE;
9917 if (argv[0] == NULL) {
9924 /* ash emits: export VAR='VAL'
9925 * bash: declare -x VAR="VAL"
9926 * we follow ash example */
9927 const char *s = *e++;
9928 const char *p = strchr(s, '=');
9930 if (!p) /* wtf? take next variable */
9933 printf("export %.*s", (int)(p - s) + 1, s);
9934 print_escaped(p + 1);
9938 /*fflush_all(); - done after each builtin anyway */
9940 return EXIT_SUCCESS;
9943 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9947 #if ENABLE_HUSH_LOCAL
9948 static int FAST_FUNC builtin_local(char **argv)
9950 if (G.func_nest_level == 0) {
9951 bb_error_msg("%s: not in a function", argv[0]);
9952 return EXIT_FAILURE; /* bash compat */
9955 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9959 #if ENABLE_HUSH_READONLY
9960 static int FAST_FUNC builtin_readonly(char **argv)
9963 if (*argv == NULL) {
9964 /* bash: readonly [-p]: list all readonly VARs
9965 * (-p has no effect in bash)
9968 for (e = G.top_var; e; e = e->next) {
9969 if (e->flg_read_only) {
9970 //TODO: quote value: readonly VAR='VAL'
9971 printf("readonly %s\n", e->varstr);
9974 return EXIT_SUCCESS;
9976 return helper_export_local(argv, SETFLAG_MAKE_RO);
9980 #if ENABLE_HUSH_UNSET
9981 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9982 static int FAST_FUNC builtin_unset(char **argv)
9987 /* "!": do not abort on errors */
9988 /* "+": stop at 1st non-option */
9989 opts = getopt32(argv, "!+vf");
9990 if (opts == (unsigned)-1)
9991 return EXIT_FAILURE;
9993 bb_error_msg("unset: -v and -f are exclusive");
9994 return EXIT_FAILURE;
10000 if (!(opts & 2)) { /* not -f */
10001 if (unset_local_var(*argv)) {
10002 /* unset <nonexistent_var> doesn't fail.
10003 * Error is when one tries to unset RO var.
10004 * Message was printed by unset_local_var. */
10005 ret = EXIT_FAILURE;
10008 # if ENABLE_HUSH_FUNCTIONS
10019 #if ENABLE_HUSH_SET
10020 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10021 * built-in 'set' handler
10023 * set [-abCefhmnuvx] [-o option] [argument...]
10024 * set [+abCefhmnuvx] [+o option] [argument...]
10025 * set -- [argument...]
10028 * Implementations shall support the options in both their hyphen and
10029 * plus-sign forms. These options can also be specified as options to sh.
10031 * Write out all variables and their values: set
10032 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10033 * Turn on the -x and -v options: set -xv
10034 * Unset all positional parameters: set --
10035 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10036 * Set the positional parameters to the expansion of x, even if x expands
10037 * with a leading '-' or '+': set -- $x
10039 * So far, we only support "set -- [argument...]" and some of the short names.
10041 static int FAST_FUNC builtin_set(char **argv)
10044 char **pp, **g_argv;
10045 char *arg = *++argv;
10048 struct variable *e;
10049 for (e = G.top_var; e; e = e->next)
10051 return EXIT_SUCCESS;
10055 if (strcmp(arg, "--") == 0) {
10059 if (arg[0] != '+' && arg[0] != '-')
10061 for (n = 1; arg[n]; ++n) {
10062 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10064 if (arg[n] == 'o' && argv[1])
10067 } while ((arg = *++argv) != NULL);
10068 /* Now argv[0] is 1st argument */
10071 return EXIT_SUCCESS;
10074 /* NB: G.global_argv[0] ($0) is never freed/changed */
10075 g_argv = G.global_argv;
10076 if (G.global_args_malloced) {
10082 G.global_args_malloced = 1;
10083 pp = xzalloc(sizeof(pp[0]) * 2);
10084 pp[0] = g_argv[0]; /* retain $0 */
10087 /* This realloc's G.global_argv */
10088 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10090 G.global_argc = 1 + string_array_len(pp + 1);
10092 return EXIT_SUCCESS;
10094 /* Nothing known, so abort */
10096 bb_error_msg("%s: %s: invalid option", "set", arg);
10097 return EXIT_FAILURE;
10101 static int FAST_FUNC builtin_shift(char **argv)
10104 argv = skip_dash_dash(argv);
10106 n = bb_strtou(argv[0], NULL, 10);
10107 if (errno || n < 0) {
10108 /* shared string with ash.c */
10109 bb_error_msg("Illegal number: %s", argv[0]);
10111 * ash aborts in this case.
10112 * bash prints error message and set $? to 1.
10113 * Interestingly, for "shift 99999" bash does not
10114 * print error message, but does set $? to 1
10115 * (and does no shifting at all).
10119 if (n >= 0 && n < G.global_argc) {
10120 if (G_global_args_malloced) {
10123 free(G.global_argv[m++]);
10125 G.global_argc -= n;
10126 memmove(&G.global_argv[1], &G.global_argv[n+1],
10127 G.global_argc * sizeof(G.global_argv[0]));
10128 return EXIT_SUCCESS;
10130 return EXIT_FAILURE;
10133 #if ENABLE_HUSH_GETOPTS
10134 static int FAST_FUNC builtin_getopts(char **argv)
10136 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10139 If a required argument is not found, and getopts is not silent,
10140 a question mark (?) is placed in VAR, OPTARG is unset, and a
10141 diagnostic message is printed. If getopts is silent, then a
10142 colon (:) is placed in VAR and OPTARG is set to the option
10145 Test that VAR is a valid variable name?
10147 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10150 const char *cp, *optstring, *var;
10151 int c, n, exitcode, my_opterr;
10154 optstring = *++argv;
10155 if (!optstring || !(var = *++argv)) {
10156 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10157 return EXIT_FAILURE;
10161 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10163 argv = G.global_argv;
10167 if (optstring[0] != ':') {
10168 cp = get_local_var_value("OPTERR");
10169 /* 0 if "OPTERR=0", 1 otherwise */
10170 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
10173 /* getopts stops on first non-option. Add "+" to force that */
10174 /*if (optstring[0] != '+')*/ {
10175 char *s = alloca(strlen(optstring) + 2);
10176 sprintf(s, "+%s", optstring);
10180 /* Naively, now we should just
10181 * cp = get_local_var_value("OPTIND");
10182 * optind = cp ? atoi(cp) : 0;
10184 * opterr = my_opterr;
10185 * c = getopt(string_array_len(argv), argv, optstring);
10186 * and be done? Not so fast...
10187 * Unlike normal getopt() usage in C programs, here
10188 * each successive call will (usually) have the same argv[] CONTENTS,
10189 * but not the ADDRESSES. Worse yet, it's possible that between
10190 * invocations of "getopts", there will be calls to shell builtins
10191 * which use getopt() internally. Example:
10192 * while getopts "abc" RES -a -bc -abc de; do
10195 * This would not work correctly: getopt() call inside "unset"
10196 * modifies internal libc state which is tracking position in
10197 * multi-option strings ("-abc"). At best, it can skip options
10198 * or return the same option infinitely. With glibc implementation
10199 * of getopt(), it would use outright invalid pointers and return
10200 * garbage even _without_ "unset" mangling internal state.
10202 * We resort to resetting getopt() state and calling it N times,
10203 * until we get Nth result (or failure).
10204 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10208 n = string_array_len(argv);
10211 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10212 c = getopt(n, argv, optstring);
10216 } while (count <= G.getopt_count);
10218 /* Set OPTIND. Prevent resetting of the magic counter! */
10219 set_local_var_from_halves("OPTIND", utoa(optind));
10220 G.getopt_count = count; /* "next time, give me N+1'th result" */
10221 GETOPT_RESET(); /* just in case */
10224 /* Always set or unset, never left as-is, even on exit/error:
10225 * "If no option was found, or if the option that was found
10226 * does not have an option-argument, OPTARG shall be unset."
10230 /* If ":optstring" and unknown option is seen,
10231 * it is stored to OPTARG.
10233 if (optstring[1] == ':') {
10239 set_local_var_from_halves("OPTARG", cp);
10241 unset_local_var("OPTARG");
10243 /* Convert -1 to "?" */
10244 exitcode = EXIT_SUCCESS;
10245 if (c < 0) { /* -1: end of options */
10246 exitcode = EXIT_FAILURE;
10252 set_local_var_from_halves(var, cbuf);
10258 static int FAST_FUNC builtin_source(char **argv)
10260 char *arg_path, *filename;
10263 char *args_need_save;
10264 #if ENABLE_HUSH_FUNCTIONS
10268 argv = skip_dash_dash(argv);
10269 filename = argv[0];
10271 /* bash says: "bash: .: filename argument required" */
10272 return 2; /* bash compat */
10275 if (!strchr(filename, '/')) {
10276 arg_path = find_in_path(filename);
10278 filename = arg_path;
10279 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
10281 bb_simple_perror_msg(filename);
10282 return EXIT_FAILURE;
10285 input = remember_FILE(fopen_or_warn(filename, "r"));
10288 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10289 /* POSIX: non-interactive shell should abort here,
10290 * not merely fail. So far no one complained :)
10292 return EXIT_FAILURE;
10295 #if ENABLE_HUSH_FUNCTIONS
10296 sv_flg = G_flag_return_in_progress;
10297 /* "we are inside sourced file, ok to use return" */
10298 G_flag_return_in_progress = -1;
10300 args_need_save = argv[1]; /* used as a boolean variable */
10301 if (args_need_save)
10302 save_and_replace_G_args(&sv, argv);
10304 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10305 G.last_exitcode = 0;
10306 parse_and_run_file(input);
10307 fclose_and_forget(input);
10309 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10310 restore_G_args(&sv, argv);
10311 #if ENABLE_HUSH_FUNCTIONS
10312 G_flag_return_in_progress = sv_flg;
10315 return G.last_exitcode;
10318 #if ENABLE_HUSH_TRAP
10319 static int FAST_FUNC builtin_trap(char **argv)
10325 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10330 /* No args: print all trapped */
10331 for (i = 0; i < NSIG; ++i) {
10333 printf("trap -- ");
10334 print_escaped(G_traps[i]);
10335 /* note: bash adds "SIG", but only if invoked
10336 * as "bash". If called as "sh", or if set -o posix,
10337 * then it prints short signal names.
10338 * We are printing short names: */
10339 printf(" %s\n", get_signame(i));
10342 /*fflush_all(); - done after each builtin anyway */
10343 return EXIT_SUCCESS;
10347 /* If first arg is a number: reset all specified signals */
10348 sig = bb_strtou(*argv, NULL, 10);
10352 ret = EXIT_SUCCESS;
10354 sighandler_t handler;
10356 sig = get_signum(*argv++);
10358 ret = EXIT_FAILURE;
10359 /* Mimic bash message exactly */
10360 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
10364 free(G_traps[sig]);
10365 G_traps[sig] = xstrdup(new_cmd);
10367 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
10368 get_signame(sig), sig, G_traps[sig]);
10370 /* There is no signal for 0 (EXIT) */
10375 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10377 /* We are removing trap handler */
10378 handler = pick_sighandler(sig);
10379 install_sighandler(sig, handler);
10384 if (!argv[1]) { /* no second arg */
10385 bb_error_msg("trap: invalid arguments");
10386 return EXIT_FAILURE;
10389 /* First arg is "-": reset all specified to default */
10390 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10391 /* Everything else: set arg as signal handler
10392 * (includes "" case, which ignores signal) */
10393 if (argv[0][0] == '-') {
10394 if (argv[0][1] == '\0') { /* "-" */
10395 /* new_cmd remains NULL: "reset these sigs" */
10398 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10401 /* else: "-something", no special meaning */
10406 goto process_sig_list;
10410 #if ENABLE_HUSH_JOB
10411 static struct pipe *parse_jobspec(const char *str)
10416 if (sscanf(str, "%%%u", &jobnum) != 1) {
10418 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10420 bb_error_msg("bad argument '%s'", str);
10423 /* It is "%%", "%+" or "%" - current job */
10424 jobnum = G.last_jobid;
10426 bb_error_msg("no current job");
10430 for (pi = G.job_list; pi; pi = pi->next) {
10431 if (pi->jobid == jobnum) {
10435 bb_error_msg("%u: no such job", jobnum);
10439 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10442 const char *status_string;
10444 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10445 for (job = G.job_list; job; job = job->next) {
10446 if (job->alive_cmds == job->stopped_cmds)
10447 status_string = "Stopped";
10449 status_string = "Running";
10451 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10454 clean_up_last_dead_job();
10456 return EXIT_SUCCESS;
10459 /* built-in 'fg' and 'bg' handler */
10460 static int FAST_FUNC builtin_fg_bg(char **argv)
10465 if (!G_interactive_fd)
10466 return EXIT_FAILURE;
10468 /* If they gave us no args, assume they want the last backgrounded task */
10470 for (pi = G.job_list; pi; pi = pi->next) {
10471 if (pi->jobid == G.last_jobid) {
10475 bb_error_msg("%s: no current job", argv[0]);
10476 return EXIT_FAILURE;
10479 pi = parse_jobspec(argv[1]);
10481 return EXIT_FAILURE;
10483 /* TODO: bash prints a string representation
10484 * of job being foregrounded (like "sleep 1 | cat") */
10485 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10486 /* Put the job into the foreground. */
10487 tcsetpgrp(G_interactive_fd, pi->pgrp);
10490 /* Restart the processes in the job */
10491 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10492 for (i = 0; i < pi->num_cmds; i++) {
10493 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10495 pi->stopped_cmds = 0;
10497 i = kill(- pi->pgrp, SIGCONT);
10499 if (errno == ESRCH) {
10500 delete_finished_job(pi);
10501 return EXIT_SUCCESS;
10503 bb_perror_msg("kill (SIGCONT)");
10506 if (argv[0][0] == 'f') {
10507 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10508 return checkjobs_and_fg_shell(pi);
10510 return EXIT_SUCCESS;
10514 #if ENABLE_HUSH_KILL
10515 static int FAST_FUNC builtin_kill(char **argv)
10519 # if ENABLE_HUSH_JOB
10520 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10528 if (argv[i][0] != '%')
10531 * "kill %N" - job kill
10532 * Converting to pgrp / pid kill
10534 pi = parse_jobspec(argv[i]);
10536 /* Eat bad jobspec */
10540 argv[j - 1] = argv[j];
10547 * In jobs started under job control, we signal
10548 * entire process group by kill -PGRP_ID.
10549 * This happens, f.e., in interactive shell.
10551 * Otherwise, we signal each child via
10552 * kill PID1 PID2 PID3.
10554 * sh -c 'sleep 1|sleep 1 & kill %1'
10555 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10556 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10558 n = G_interactive_fd ? 1 : pi->num_cmds;
10559 dst = alloca(n * sizeof(int)*4);
10561 if (G_interactive_fd)
10562 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10563 else for (j = 0; j < n; j++) {
10564 struct command *cmd = &pi->cmds[j];
10565 /* Skip exited members of the job */
10569 * kill_main has matching code to expect
10570 * leading space. Needed to not confuse
10571 * negative pids with "kill -SIGNAL_NO" syntax
10573 dst += sprintf(dst, " %u", (int)cmd->pid);
10576 } while (argv[++i]);
10580 if (argv[1] || ret == 0) {
10581 ret = run_applet_main(argv, kill_main);
10583 /* else: ret = 1, "kill %bad_jobspec" case */
10588 #if ENABLE_HUSH_WAIT
10589 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10590 #if !ENABLE_HUSH_JOB
10591 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10593 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10600 if (!sigisemptyset(&G.pending_set))
10603 /* waitpid is not interruptible by SA_RESTARTed
10604 * signals which we use. Thus, this ugly dance:
10607 /* Make sure possible SIGCHLD is stored in kernel's
10608 * pending signal mask before we call waitpid.
10609 * Or else we may race with SIGCHLD, lose it,
10610 * and get stuck in sigsuspend...
10612 sigfillset(&oldset); /* block all signals, remember old set */
10613 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10615 if (!sigisemptyset(&G.pending_set)) {
10616 /* Crap! we raced with some signal! */
10620 /*errno = 0; - checkjobs does this */
10621 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10622 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10623 debug_printf_exec("checkjobs:%d\n", ret);
10624 #if ENABLE_HUSH_JOB
10625 if (waitfor_pipe) {
10626 int rcode = job_exited_or_stopped(waitfor_pipe);
10627 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10630 sigprocmask(SIG_SETMASK, &oldset, NULL);
10635 /* if ECHILD, there are no children (ret is -1 or 0) */
10636 /* if ret == 0, no children changed state */
10637 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10638 if (errno == ECHILD || ret) {
10640 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10642 sigprocmask(SIG_SETMASK, &oldset, NULL);
10645 /* Wait for SIGCHLD or any other signal */
10646 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10647 /* Note: sigsuspend invokes signal handler */
10648 sigsuspend(&oldset);
10650 sigprocmask(SIG_SETMASK, &oldset, NULL);
10652 /* So, did we get a signal? */
10653 sig = check_and_run_traps();
10654 if (sig /*&& sig != SIGCHLD - always true */) {
10655 /* Do this for any (non-ignored) signal, not only for ^C */
10659 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10664 static int FAST_FUNC builtin_wait(char **argv)
10669 argv = skip_dash_dash(argv);
10670 if (argv[0] == NULL) {
10671 /* Don't care about wait results */
10672 /* Note 1: must wait until there are no more children */
10673 /* Note 2: must be interruptible */
10675 * $ sleep 3 & sleep 6 & wait
10676 * [1] 30934 sleep 3
10677 * [2] 30935 sleep 6
10680 * $ sleep 3 & sleep 6 & wait
10681 * [1] 30936 sleep 3
10682 * [2] 30937 sleep 6
10684 * ^C <-- after ~4 sec from keyboard
10687 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10691 pid_t pid = bb_strtou(*argv, NULL, 10);
10692 if (errno || pid <= 0) {
10693 #if ENABLE_HUSH_JOB
10694 if (argv[0][0] == '%') {
10695 struct pipe *wait_pipe;
10696 ret = 127; /* bash compat for bad jobspecs */
10697 wait_pipe = parse_jobspec(*argv);
10699 ret = job_exited_or_stopped(wait_pipe);
10701 ret = wait_for_child_or_signal(wait_pipe, 0);
10703 /* waiting on "last dead job" removes it */
10704 clean_up_last_dead_job();
10707 /* else: parse_jobspec() already emitted error msg */
10711 /* mimic bash message */
10712 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10713 ret = EXIT_FAILURE;
10714 continue; /* bash checks all argv[] */
10717 /* Do we have such child? */
10718 ret = waitpid(pid, &status, WNOHANG);
10722 if (errno == ECHILD) {
10723 if (pid == G.last_bg_pid) {
10724 /* "wait $!" but last bg task has already exited. Try:
10725 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10726 * In bash it prints exitcode 0, then 3.
10727 * In dash, it is 127.
10729 ret = G.last_bg_pid_exitcode;
10731 /* Example: "wait 1". mimic bash message */
10732 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10736 bb_perror_msg("wait %s", *argv);
10738 continue; /* bash checks all argv[] */
10741 /* Yes, and it still runs */
10742 ret = wait_for_child_or_signal(NULL, pid);
10744 /* Yes, and it just exited */
10745 process_wait_result(NULL, pid, status);
10746 ret = WEXITSTATUS(status);
10747 if (WIFSIGNALED(status))
10748 ret = 128 + WTERMSIG(status);
10756 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10757 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10760 def = bb_strtou(argv[1], NULL, 10);
10761 if (errno || def < def_min || argv[2]) {
10762 bb_error_msg("%s: bad arguments", argv[0]);
10770 #if ENABLE_HUSH_LOOPS
10771 static int FAST_FUNC builtin_break(char **argv)
10774 if (G.depth_of_loop == 0) {
10775 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10776 /* if we came from builtin_continue(), need to undo "= 1" */
10777 G.flag_break_continue = 0;
10778 return EXIT_SUCCESS; /* bash compat */
10780 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10782 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10783 if (depth == UINT_MAX)
10784 G.flag_break_continue = BC_BREAK;
10785 if (G.depth_of_loop < depth)
10786 G.depth_break_continue = G.depth_of_loop;
10788 return EXIT_SUCCESS;
10791 static int FAST_FUNC builtin_continue(char **argv)
10793 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10794 return builtin_break(argv);
10798 #if ENABLE_HUSH_FUNCTIONS
10799 static int FAST_FUNC builtin_return(char **argv)
10803 if (G_flag_return_in_progress != -1) {
10804 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10805 return EXIT_FAILURE; /* bash compat */
10808 G_flag_return_in_progress = 1;
10811 * out of range: wraps around at 256, does not error out
10812 * non-numeric param:
10813 * f() { false; return qwe; }; f; echo $?
10814 * bash: return: qwe: numeric argument required <== we do this
10815 * 255 <== we also do this
10817 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10822 #if ENABLE_HUSH_TIMES
10823 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10825 static const uint8_t times_tbl[] ALIGN1 = {
10826 ' ', offsetof(struct tms, tms_utime),
10827 '\n', offsetof(struct tms, tms_stime),
10828 ' ', offsetof(struct tms, tms_cutime),
10829 '\n', offsetof(struct tms, tms_cstime),
10836 clk_tck = bb_clk_tck();
10841 unsigned sec, frac;
10843 t = *(clock_t *)(((char *) &buf) + p[1]);
10845 frac = t % clk_tck;
10846 printf("%um%u.%03us%c",
10847 sec / 60, sec % 60,
10848 (frac * 1000) / clk_tck,
10853 return EXIT_SUCCESS;
10857 #if ENABLE_HUSH_MEMLEAK
10858 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10863 # ifdef M_TRIM_THRESHOLD
10864 /* Optional. Reduces probability of false positives */
10867 /* Crude attempt to find where "free memory" starts,
10868 * sans fragmentation. */
10870 l = (unsigned long)p;
10873 if (l < (unsigned long)p) l = (unsigned long)p;
10879 struct mallinfo mi = mallinfo();
10880 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10881 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10885 if (!G.memleak_value)
10886 G.memleak_value = l;
10888 l -= G.memleak_value;
10895 /* Exitcode is "how many kilobytes we leaked since 1st call" */