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_INTERACTIVE
124 //config: bool "Interactive mode"
126 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
128 //config: Enable interactive mode (prompt and command editing).
129 //config: Without this, hush simply reads and executes commands
130 //config: from stdin just like a shell script from a file.
131 //config: No prompt, no PS1/PS2 magic shell variables.
133 //config:config HUSH_SAVEHISTORY
134 //config: bool "Save command history to .hush_history"
136 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
138 //config:config HUSH_JOB
139 //config: bool "Job control"
141 //config: depends on HUSH_INTERACTIVE
143 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
144 //config: command (not entire shell), fg/bg builtins work. Without this option,
145 //config: "cmd &" still works by simply spawning a process and immediately
146 //config: prompting for next command (or executing next command in a script),
147 //config: but no separate process group is formed.
149 //config:config HUSH_TICK
150 //config: bool "Support process substitution"
152 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
154 //config: Enable `command` and $(command).
156 //config:config HUSH_IF
157 //config: bool "Support if/then/elif/else/fi"
159 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
161 //config:config HUSH_LOOPS
162 //config: bool "Support for, while and until loops"
164 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
166 //config:config HUSH_CASE
167 //config: bool "Support case ... esac statement"
169 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
171 //config: Enable case ... esac statement. +400 bytes.
173 //config:config HUSH_FUNCTIONS
174 //config: bool "Support funcname() { commands; } syntax"
176 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
178 //config: Enable support for shell functions. +800 bytes.
180 //config:config HUSH_LOCAL
181 //config: bool "local builtin"
183 //config: depends on HUSH_FUNCTIONS
185 //config: Enable support for local variables in functions.
187 //config:config HUSH_RANDOM_SUPPORT
188 //config: bool "Pseudorandom generator and $RANDOM variable"
190 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
192 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
193 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
195 //config:config HUSH_MODE_X
196 //config: bool "Support 'hush -x' option and 'set -x' command"
198 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
200 //config: This instructs hush to print commands before execution.
201 //config: Adds ~300 bytes.
203 //config:config HUSH_ECHO
204 //config: bool "echo builtin"
206 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
208 //config:config HUSH_PRINTF
209 //config: bool "printf builtin"
211 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
213 //config:config HUSH_TEST
214 //config: bool "test builtin"
216 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
218 //config:config HUSH_HELP
219 //config: bool "help builtin"
221 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
223 //config:config HUSH_EXPORT
224 //config: bool "export builtin"
226 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
228 //config:config HUSH_EXPORT_N
229 //config: bool "Support 'export -n' option"
231 //config: depends on HUSH_EXPORT
233 //config: export -n unexports variables. It is a bash extension.
235 //config:config HUSH_READONLY
236 //config: bool "readonly builtin"
238 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
240 //config: Enable support for read-only variables.
242 //config:config HUSH_KILL
243 //config: bool "kill builtin (supports kill %jobspec)"
245 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
247 //config:config HUSH_WAIT
248 //config: bool "wait builtin"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config:config HUSH_COMMAND
253 //config: bool "command builtin"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_TRAP
258 //config: bool "trap builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_TYPE
263 //config: bool "type builtin"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
267 //config:config HUSH_TIMES
268 //config: bool "times builtin"
270 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272 //config:config HUSH_READ
273 //config: bool "read builtin"
275 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
277 //config:config HUSH_SET
278 //config: bool "set builtin"
280 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
282 //config:config HUSH_UNSET
283 //config: bool "unset builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config:config HUSH_ULIMIT
288 //config: bool "ulimit builtin"
290 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
292 //config:config HUSH_UMASK
293 //config: bool "umask builtin"
295 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
297 //config:config HUSH_GETOPTS
298 //config: bool "getopts builtin"
300 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
302 //config:config HUSH_MEMLEAK
303 //config: bool "memleak builtin (debugging)"
305 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
307 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
308 // APPLET_ODDNAME:name main location suid_type help
309 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
310 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
312 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
313 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
314 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
315 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
317 /* -i (interactive) and -s (read stdin) are also accepted,
318 * but currently do nothing, therefore aren't shown in help.
319 * NOMMU-specific options are not meant to be used by users,
320 * therefore we don't show them either.
322 //usage:#define hush_trivial_usage
323 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
324 //usage:#define hush_full_usage "\n\n"
325 //usage: "Unix shell interpreter"
327 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
328 || defined(__APPLE__) \
330 # include <malloc.h> /* for malloc_trim */
333 /* #include <dmalloc.h> */
335 # include <fnmatch.h>
337 #include <sys/times.h>
338 #include <sys/utsname.h> /* for setting $HOSTNAME */
340 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
342 #include "shell_common.h"
345 #if ENABLE_HUSH_RANDOM_SUPPORT
348 # define CLEAR_RANDOM_T(rnd) ((void)0)
350 #ifndef F_DUPFD_CLOEXEC
351 # define F_DUPFD_CLOEXEC F_DUPFD
354 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
358 /* So far, all bash compat is controlled by one config option */
359 /* Separate defines document which part of code implements what */
360 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
361 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
362 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
363 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
364 #define BASH_LINENO_VAR ENABLE_HUSH_BASH_COMPAT
365 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
366 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
370 #define LEAK_HUNTING 0
371 #define BUILD_AS_NOMMU 0
372 /* Enable/disable sanity checks. Ok to enable in production,
373 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
374 * Keeping 1 for now even in released versions.
377 /* Slightly bigger (+200 bytes), but faster hush.
378 * So far it only enables a trick with counting SIGCHLDs and forks,
379 * which allows us to do fewer waitpid's.
380 * (we can detect a case where neither forks were done nor SIGCHLDs happened
381 * and therefore waitpid will return the same result as last time)
383 #define ENABLE_HUSH_FAST 0
384 /* TODO: implement simplified code for users which do not need ${var%...} ops
385 * So far ${var%...} ops are always enabled:
387 #define ENABLE_HUSH_DOLLAR_OPS 1
392 # undef USE_FOR_NOMMU
395 # define USE_FOR_NOMMU(...) __VA_ARGS__
396 # define USE_FOR_MMU(...)
399 #include "NUM_APPLETS.h"
401 /* STANDALONE does not make sense, and won't compile */
402 # undef CONFIG_FEATURE_SH_STANDALONE
403 # undef ENABLE_FEATURE_SH_STANDALONE
404 # undef IF_FEATURE_SH_STANDALONE
405 # undef IF_NOT_FEATURE_SH_STANDALONE
406 # define ENABLE_FEATURE_SH_STANDALONE 0
407 # define IF_FEATURE_SH_STANDALONE(...)
408 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
411 #if !ENABLE_HUSH_INTERACTIVE
412 # undef ENABLE_FEATURE_EDITING
413 # define ENABLE_FEATURE_EDITING 0
414 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
415 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
416 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
417 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
420 /* Do we support ANY keywords? */
421 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
422 # define HAS_KEYWORDS 1
423 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
424 # define IF_HAS_NO_KEYWORDS(...)
426 # define HAS_KEYWORDS 0
427 # define IF_HAS_KEYWORDS(...)
428 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
431 /* If you comment out one of these below, it will be #defined later
432 * to perform debug printfs to stderr: */
433 #define debug_printf(...) do {} while (0)
434 /* Finer-grained debug switches */
435 #define debug_printf_parse(...) do {} while (0)
436 #define debug_print_tree(a, b) do {} while (0)
437 #define debug_printf_exec(...) do {} while (0)
438 #define debug_printf_env(...) do {} while (0)
439 #define debug_printf_jobs(...) do {} while (0)
440 #define debug_printf_expand(...) do {} while (0)
441 #define debug_printf_varexp(...) do {} while (0)
442 #define debug_printf_glob(...) do {} while (0)
443 #define debug_printf_redir(...) do {} while (0)
444 #define debug_printf_list(...) do {} while (0)
445 #define debug_printf_subst(...) do {} while (0)
446 #define debug_printf_clean(...) do {} while (0)
448 #define ERR_PTR ((void*)(long)1)
450 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
452 #define _SPECIAL_VARS_STR "_*@$!?#"
453 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
454 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
455 #if BASH_PATTERN_SUBST
456 /* Support / and // replace ops */
457 /* Note that // is stored as \ in "encoded" string representation */
458 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
459 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
460 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
462 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
463 # define VAR_SUBST_OPS "%#:-=+?"
464 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
467 #define SPECIAL_VAR_SYMBOL_STR "\3"
468 #define SPECIAL_VAR_SYMBOL 3
469 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
470 #define SPECIAL_VAR_QUOTED_SVS 1
474 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
476 /* This supports saving pointers malloced in vfork child,
477 * to be freed in the parent.
480 typedef struct nommu_save_t {
482 struct variable *old_vars;
484 char **argv_from_re_execing;
497 #if ENABLE_HUSH_LOOPS
504 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
509 /* three pseudo-keywords support contrived "case" syntax: */
510 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
511 RES_MATCH , /* "word)" */
512 RES_CASE_BODY, /* "this command is inside CASE" */
519 typedef struct o_string {
521 int length; /* position where data is appended */
524 /* At least some part of the string was inside '' or "",
525 * possibly empty one: word"", wo''rd etc. */
526 smallint has_quoted_part;
527 smallint has_empty_slot;
528 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
531 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
533 /* Protect newly added chars against globbing
534 * by prepending \ to *, ?, [, \ */
535 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
538 MAYBE_ASSIGNMENT = 0,
539 DEFINITELY_ASSIGNMENT = 1,
541 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
544 /* Used for initialization: o_string foo = NULL_O_STRING; */
545 #define NULL_O_STRING { NULL }
547 #ifndef debug_printf_parse
548 static const char *const assignment_flag[] = {
550 "DEFINITELY_ASSIGNMENT",
556 typedef struct in_str {
558 #if ENABLE_HUSH_INTERACTIVE
559 smallint promptmode; /* 0: PS1, 1: PS2 */
566 /* The descrip member of this structure is only used to make
567 * debugging output pretty */
568 static const struct {
570 signed char default_fd;
573 { O_RDONLY, 0, "<" },
574 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
575 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
576 { O_CREAT|O_RDWR, 1, "<>" },
577 { O_RDONLY, 0, "<<" },
578 /* Should not be needed. Bogus default_fd helps in debugging */
579 /* { O_RDONLY, 77, "<<" }, */
582 struct redir_struct {
583 struct redir_struct *next;
584 char *rd_filename; /* filename */
585 int rd_fd; /* fd to redirect */
586 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
588 smallint rd_type; /* (enum redir_type) */
589 /* note: for heredocs, rd_filename contains heredoc delimiter,
590 * and subsequently heredoc itself; and rd_dup is a bitmask:
591 * bit 0: do we need to trim leading tabs?
592 * bit 1: is heredoc quoted (<<'delim' syntax) ?
595 typedef enum redir_type {
597 REDIRECT_OVERWRITE = 1,
600 REDIRECT_HEREDOC = 4,
601 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
604 REDIRFD_SYNTAX_ERR = -2,
605 REDIRFD_TO_FILE = -1,
606 /* otherwise, rd_fd is redirected to rd_dup */
608 HEREDOC_SKIPTABS = 1,
614 pid_t pid; /* 0 if exited */
615 int assignment_cnt; /* how many argv[i] are assignments? */
619 smallint cmd_type; /* CMD_xxx */
621 #define CMD_SUBSHELL 1
623 /* used for "[[ EXPR ]]" */
624 # define CMD_SINGLEWORD_NOGLOB 2
626 #if ENABLE_HUSH_FUNCTIONS
627 # define CMD_FUNCDEF 3
630 smalluint cmd_exitcode;
631 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
634 char *group_as_string;
636 #if ENABLE_HUSH_FUNCTIONS
637 struct function *child_func;
638 /* This field is used to prevent a bug here:
639 * while...do f1() {a;}; f1; f1() {b;}; f1; done
640 * When we execute "f1() {a;}" cmd, we create new function and clear
641 * cmd->group, cmd->group_as_string, cmd->argv[0].
642 * When we execute "f1() {b;}", we notice that f1 exists,
643 * and that its "parent cmd" struct is still "alive",
644 * we put those fields back into cmd->xxx
645 * (struct function has ->parent_cmd ptr to facilitate that).
646 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
647 * Without this trick, loop would execute a;b;b;b;...
648 * instead of correct sequence a;b;a;b;...
649 * When command is freed, it severs the link
650 * (sets ->child_func->parent_cmd to NULL).
653 char **argv; /* command name and arguments */
654 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
655 * and on execution these are substituted with their values.
656 * Substitution can make _several_ words out of one argv[n]!
657 * Example: argv[0]=='.^C*^C.' here: echo .$*.
658 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
660 struct redir_struct *redirects; /* I/O redirections */
662 /* Is there anything in this command at all? */
663 #define IS_NULL_CMD(cmd) \
664 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
668 int num_cmds; /* total number of commands in pipe */
669 int alive_cmds; /* number of commands running (not exited) */
670 int stopped_cmds; /* number of commands alive, but stopped */
672 unsigned jobid; /* job number */
673 pid_t pgrp; /* process group ID for the job */
674 char *cmdtext; /* name of job */
676 struct command *cmds; /* array of commands in pipe */
677 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
678 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
679 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
681 typedef enum pipe_style {
687 /* Is there anything in this pipe at all? */
688 #define IS_NULL_PIPE(pi) \
689 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
691 /* This holds pointers to the various results of parsing */
692 struct parse_context {
693 /* linked list of pipes */
694 struct pipe *list_head;
695 /* last pipe (being constructed right now) */
697 /* last command in pipe (being constructed right now) */
698 struct command *command;
699 /* last redirect in command->redirects list */
700 struct redir_struct *pending_redirect;
706 smallint ctx_inverted; /* "! cmd | cmd" */
708 smallint ctx_dsemicolon; /* ";;" seen */
710 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
712 /* group we are enclosed in:
713 * example: "if pipe1; pipe2; then pipe3; fi"
714 * when we see "if" or "then", we malloc and copy current context,
715 * and make ->stack point to it. then we parse pipeN.
716 * when closing "then" / fi" / whatever is found,
717 * we move list_head into ->stack->command->group,
718 * copy ->stack into current context, and delete ->stack.
719 * (parsing of { list } and ( list ) doesn't use this method)
721 struct parse_context *stack;
725 /* On program start, environ points to initial environment.
726 * putenv adds new pointers into it, unsetenv removes them.
727 * Neither of these (de)allocates the strings.
728 * setenv allocates new strings in malloc space and does putenv,
729 * and thus setenv is unusable (leaky) for shell's purposes */
730 #define setenv(...) setenv_is_leaky_dont_use()
732 struct variable *next;
733 char *varstr; /* points to "name=" portion */
734 #if ENABLE_HUSH_LOCAL
735 unsigned func_nest_level;
737 int max_len; /* if > 0, name is part of initial env; else name is malloced */
738 smallint flg_export; /* putenv should be done on this var */
739 smallint flg_read_only;
747 #if ENABLE_HUSH_FUNCTIONS
749 struct function *next;
751 struct command *parent_cmd;
754 char *body_as_string;
760 /* set -/+o OPT support. (TODO: make it optional)
761 * bash supports the following opts:
772 * interactive-comments on
790 static const char o_opt_strings[] ALIGN1 =
794 #if ENABLE_HUSH_MODE_X
802 #if ENABLE_HUSH_MODE_X
810 struct FILE_list *next;
816 /* "Globals" within this file */
817 /* Sorted roughly by size (smaller offsets == smaller code) */
819 /* interactive_fd != 0 means we are an interactive shell.
820 * If we are, then saved_tty_pgrp can also be != 0, meaning
821 * that controlling tty is available. With saved_tty_pgrp == 0,
822 * job control still works, but terminal signals
823 * (^C, ^Z, ^Y, ^\) won't work at all, and background
824 * process groups can only be created with "cmd &".
825 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
826 * to give tty to the foreground process group,
827 * and will take it back when the group is stopped (^Z)
830 #if ENABLE_HUSH_INTERACTIVE
831 /* 'interactive_fd' is a fd# open to ctty, if we have one
832 * _AND_ if we decided to act interactively */
836 # define G_interactive_fd (G.interactive_fd)
838 # define G_interactive_fd 0
840 #if ENABLE_FEATURE_EDITING
841 line_input_t *line_input_state;
846 #if ENABLE_HUSH_RANDOM_SUPPORT
852 pid_t saved_tty_pgrp;
853 struct pipe *job_list;
854 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
856 # define G_saved_tty_pgrp 0
858 /* How deeply are we in context where "set -e" is ignored */
860 /* "set -e" rules (do we follow them correctly?):
861 * Exit if pipe, list, or compound command exits with a non-zero status.
862 * Shell does not exit if failed command is part of condition in
863 * if/while, part of && or || list except the last command, any command
864 * in a pipe but the last, or if the command's return value is being
865 * inverted with !. If a compound command other than a subshell returns a
866 * non-zero status because a command failed while -e was being ignored, the
867 * shell does not exit. A trap on ERR, if set, is executed before the shell
868 * exits [ERR is a bashism].
870 * If a compound command or function executes in a context where -e is
871 * ignored, none of the commands executed within are affected by the -e
872 * setting. If a compound command or function sets -e while executing in a
873 * context where -e is ignored, that setting does not have any effect until
874 * the compound command or the command containing the function call completes.
877 char o_opt[NUM_OPT_O];
878 #if ENABLE_HUSH_MODE_X
879 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
883 smallint flag_SIGINT;
884 #if ENABLE_HUSH_LOOPS
885 smallint flag_break_continue;
887 #if ENABLE_HUSH_FUNCTIONS
888 /* 0: outside of a function (or sourced file)
889 * -1: inside of a function, ok to use return builtin
890 * 1: return is invoked, skip all till end of func
892 smallint flag_return_in_progress;
893 # define G_flag_return_in_progress (G.flag_return_in_progress)
895 # define G_flag_return_in_progress 0
897 smallint exiting; /* used to prevent EXIT trap recursion */
898 /* These four support $?, $#, and $1 */
899 smalluint last_exitcode;
900 smalluint last_bg_pid_exitcode;
902 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
903 smalluint global_args_malloced;
904 # define G_global_args_malloced (G.global_args_malloced)
906 # define G_global_args_malloced 0
908 /* how many non-NULL argv's we have. NB: $# + 1 */
912 char *argv0_for_re_execing;
914 #if ENABLE_HUSH_LOOPS
915 unsigned depth_break_continue;
916 unsigned depth_of_loop;
918 #if ENABLE_HUSH_GETOPTS
919 unsigned getopt_count;
923 struct variable *top_var;
924 char **expanded_assignments;
925 #if ENABLE_HUSH_FUNCTIONS
926 struct function *top_func;
927 # if ENABLE_HUSH_LOCAL
928 struct variable **shadowed_vars_pp;
929 unsigned func_nest_level;
932 /* Signal and trap handling */
934 unsigned count_SIGCHLD;
935 unsigned handled_SIGCHLD;
936 smallint we_have_children;
941 # define G_lineno_var G.lineno_var
943 # define G_lineno_var ((char*)NULL)
945 struct FILE_list *FILE_list;
946 /* Which signals have non-DFL handler (even with no traps set)?
947 * Set at the start to:
948 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
949 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
950 * The rest is cleared right before execv syscalls.
951 * Other than these two times, never modified.
953 unsigned special_sig_mask;
955 unsigned fatal_sig_mask;
956 # define G_fatal_sig_mask (G.fatal_sig_mask)
958 # define G_fatal_sig_mask 0
961 char **traps; /* char *traps[NSIG] */
962 # define G_traps G.traps
964 # define G_traps ((char**)NULL)
966 sigset_t pending_set;
967 #if ENABLE_HUSH_MEMLEAK
968 unsigned long memleak_value;
974 #if ENABLE_FEATURE_EDITING
975 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
978 #define G (*ptr_to_globals)
979 /* Not #defining name to G.name - this quickly gets unwieldy
980 * (too many defines). Also, I actually prefer to see when a variable
981 * is global, thus "G." prefix is a useful hint */
982 #define INIT_G() do { \
983 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
984 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
985 sigfillset(&G.sa.sa_mask); \
986 G.sa.sa_flags = SA_RESTART; \
990 /* Function prototypes for builtins */
991 static int builtin_cd(char **argv) FAST_FUNC;
993 static int builtin_echo(char **argv) FAST_FUNC;
995 static int builtin_eval(char **argv) FAST_FUNC;
996 static int builtin_exec(char **argv) FAST_FUNC;
997 static int builtin_exit(char **argv) FAST_FUNC;
998 #if ENABLE_HUSH_EXPORT
999 static int builtin_export(char **argv) FAST_FUNC;
1001 #if ENABLE_HUSH_READONLY
1002 static int builtin_readonly(char **argv) FAST_FUNC;
1005 static int builtin_fg_bg(char **argv) FAST_FUNC;
1006 static int builtin_jobs(char **argv) FAST_FUNC;
1008 #if ENABLE_HUSH_GETOPTS
1009 static int builtin_getopts(char **argv) FAST_FUNC;
1011 #if ENABLE_HUSH_HELP
1012 static int builtin_help(char **argv) FAST_FUNC;
1014 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1015 static int builtin_history(char **argv) FAST_FUNC;
1017 #if ENABLE_HUSH_LOCAL
1018 static int builtin_local(char **argv) FAST_FUNC;
1020 #if ENABLE_HUSH_MEMLEAK
1021 static int builtin_memleak(char **argv) FAST_FUNC;
1023 #if ENABLE_HUSH_PRINTF
1024 static int builtin_printf(char **argv) FAST_FUNC;
1026 static int builtin_pwd(char **argv) FAST_FUNC;
1027 #if ENABLE_HUSH_READ
1028 static int builtin_read(char **argv) FAST_FUNC;
1031 static int builtin_set(char **argv) FAST_FUNC;
1033 static int builtin_shift(char **argv) FAST_FUNC;
1034 static int builtin_source(char **argv) FAST_FUNC;
1035 #if ENABLE_HUSH_TEST || BASH_TEST2
1036 static int builtin_test(char **argv) FAST_FUNC;
1038 #if ENABLE_HUSH_TRAP
1039 static int builtin_trap(char **argv) FAST_FUNC;
1041 #if ENABLE_HUSH_TYPE
1042 static int builtin_type(char **argv) FAST_FUNC;
1044 #if ENABLE_HUSH_TIMES
1045 static int builtin_times(char **argv) FAST_FUNC;
1047 static int builtin_true(char **argv) FAST_FUNC;
1048 #if ENABLE_HUSH_UMASK
1049 static int builtin_umask(char **argv) FAST_FUNC;
1051 #if ENABLE_HUSH_UNSET
1052 static int builtin_unset(char **argv) FAST_FUNC;
1054 #if ENABLE_HUSH_KILL
1055 static int builtin_kill(char **argv) FAST_FUNC;
1057 #if ENABLE_HUSH_WAIT
1058 static int builtin_wait(char **argv) FAST_FUNC;
1060 #if ENABLE_HUSH_LOOPS
1061 static int builtin_break(char **argv) FAST_FUNC;
1062 static int builtin_continue(char **argv) FAST_FUNC;
1064 #if ENABLE_HUSH_FUNCTIONS
1065 static int builtin_return(char **argv) FAST_FUNC;
1068 /* Table of built-in functions. They can be forked or not, depending on
1069 * context: within pipes, they fork. As simple commands, they do not.
1070 * When used in non-forking context, they can change global variables
1071 * in the parent shell process. If forked, of course they cannot.
1072 * For example, 'unset foo | whatever' will parse and run, but foo will
1073 * still be set at the end. */
1074 struct built_in_command {
1076 int (*b_function)(char **argv) FAST_FUNC;
1077 #if ENABLE_HUSH_HELP
1078 const char *b_descr;
1079 # define BLTIN(cmd, func, help) { cmd, func, help }
1081 # define BLTIN(cmd, func, help) { cmd, func }
1085 static const struct built_in_command bltins1[] = {
1086 BLTIN("." , builtin_source , "Run commands in file"),
1087 BLTIN(":" , builtin_true , NULL),
1089 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1091 #if ENABLE_HUSH_LOOPS
1092 BLTIN("break" , builtin_break , "Exit loop"),
1094 BLTIN("cd" , builtin_cd , "Change directory"),
1095 #if ENABLE_HUSH_LOOPS
1096 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1098 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1099 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1100 BLTIN("exit" , builtin_exit , NULL),
1101 #if ENABLE_HUSH_EXPORT
1102 BLTIN("export" , builtin_export , "Set environment variables"),
1105 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1107 #if ENABLE_HUSH_GETOPTS
1108 BLTIN("getopts" , builtin_getopts , NULL),
1110 #if ENABLE_HUSH_HELP
1111 BLTIN("help" , builtin_help , NULL),
1113 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1114 BLTIN("history" , builtin_history , "Show history"),
1117 BLTIN("jobs" , builtin_jobs , "List jobs"),
1119 #if ENABLE_HUSH_KILL
1120 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1122 #if ENABLE_HUSH_LOCAL
1123 BLTIN("local" , builtin_local , "Set local variables"),
1125 #if ENABLE_HUSH_MEMLEAK
1126 BLTIN("memleak" , builtin_memleak , NULL),
1128 #if ENABLE_HUSH_READ
1129 BLTIN("read" , builtin_read , "Input into variable"),
1131 #if ENABLE_HUSH_READONLY
1132 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1134 #if ENABLE_HUSH_FUNCTIONS
1135 BLTIN("return" , builtin_return , "Return from function"),
1138 BLTIN("set" , builtin_set , "Set positional parameters"),
1140 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1142 BLTIN("source" , builtin_source , NULL),
1144 #if ENABLE_HUSH_TIMES
1145 BLTIN("times" , builtin_times , NULL),
1147 #if ENABLE_HUSH_TRAP
1148 BLTIN("trap" , builtin_trap , "Trap signals"),
1150 BLTIN("true" , builtin_true , NULL),
1151 #if ENABLE_HUSH_TYPE
1152 BLTIN("type" , builtin_type , "Show command type"),
1154 #if ENABLE_HUSH_ULIMIT
1155 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1157 #if ENABLE_HUSH_UMASK
1158 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1160 #if ENABLE_HUSH_UNSET
1161 BLTIN("unset" , builtin_unset , "Unset variables"),
1163 #if ENABLE_HUSH_WAIT
1164 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1167 /* These builtins won't be used if we are on NOMMU and need to re-exec
1168 * (it's cheaper to run an external program in this case):
1170 static const struct built_in_command bltins2[] = {
1171 #if ENABLE_HUSH_TEST
1172 BLTIN("[" , builtin_test , NULL),
1175 BLTIN("[[" , builtin_test , NULL),
1177 #if ENABLE_HUSH_ECHO
1178 BLTIN("echo" , builtin_echo , NULL),
1180 #if ENABLE_HUSH_PRINTF
1181 BLTIN("printf" , builtin_printf , NULL),
1183 BLTIN("pwd" , builtin_pwd , NULL),
1184 #if ENABLE_HUSH_TEST
1185 BLTIN("test" , builtin_test , NULL),
1193 /* prevent disasters with G.debug_indent < 0 */
1194 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1195 # define debug_enter() (G.debug_indent++)
1196 # define debug_leave() (G.debug_indent--)
1198 # define indent() ((void)0)
1199 # define debug_enter() ((void)0)
1200 # define debug_leave() ((void)0)
1203 #ifndef debug_printf
1204 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1207 #ifndef debug_printf_parse
1208 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1211 #ifndef debug_printf_exec
1212 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1215 #ifndef debug_printf_env
1216 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1219 #ifndef debug_printf_jobs
1220 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1221 # define DEBUG_JOBS 1
1223 # define DEBUG_JOBS 0
1226 #ifndef debug_printf_expand
1227 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1228 # define DEBUG_EXPAND 1
1230 # define DEBUG_EXPAND 0
1233 #ifndef debug_printf_varexp
1234 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1237 #ifndef debug_printf_glob
1238 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1239 # define DEBUG_GLOB 1
1241 # define DEBUG_GLOB 0
1244 #ifndef debug_printf_redir
1245 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1248 #ifndef debug_printf_list
1249 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1252 #ifndef debug_printf_subst
1253 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1256 #ifndef debug_printf_clean
1257 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1258 # define DEBUG_CLEAN 1
1260 # define DEBUG_CLEAN 0
1264 static void debug_print_strings(const char *prefix, char **vv)
1267 fdprintf(2, "%s:\n", prefix);
1269 fdprintf(2, " '%s'\n", *vv++);
1272 # define debug_print_strings(prefix, vv) ((void)0)
1276 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1279 static void *xxmalloc(int lineno, size_t size)
1281 void *ptr = xmalloc((size + 0xff) & ~0xff);
1282 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1285 static void *xxrealloc(int lineno, void *ptr, size_t size)
1287 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1288 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1291 static char *xxstrdup(int lineno, const char *str)
1293 char *ptr = xstrdup(str);
1294 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1297 static void xxfree(void *ptr)
1299 fdprintf(2, "free %p\n", ptr);
1302 # define xmalloc(s) xxmalloc(__LINE__, s)
1303 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1304 # define xstrdup(s) xxstrdup(__LINE__, s)
1305 # define free(p) xxfree(p)
1309 /* Syntax and runtime errors. They always abort scripts.
1310 * In interactive use they usually discard unparsed and/or unexecuted commands
1311 * and return to the prompt.
1312 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1315 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1316 # define syntax_error(lineno, msg) syntax_error(msg)
1317 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1318 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1319 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1320 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1323 static void die_if_script(void)
1325 if (!G_interactive_fd) {
1326 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1327 xfunc_error_retval = G.last_exitcode;
1332 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1337 bb_error_msg("hush.c:%u", lineno);
1340 bb_verror_msg(fmt, p, NULL);
1345 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1348 bb_error_msg("syntax error: %s", msg);
1350 bb_error_msg("syntax error");
1354 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1356 bb_error_msg("syntax error at '%s'", msg);
1360 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1362 bb_error_msg("syntax error: unterminated %s", s);
1363 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1367 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1369 char msg[2] = { ch, '\0' };
1370 syntax_error_unterm_str(lineno, msg);
1373 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1379 bb_error_msg("hush.c:%u", lineno);
1381 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1386 # undef msg_and_die_if_script
1387 # undef syntax_error
1388 # undef syntax_error_at
1389 # undef syntax_error_unterm_ch
1390 # undef syntax_error_unterm_str
1391 # undef syntax_error_unexpected_ch
1393 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1394 # define syntax_error(msg) syntax_error(__LINE__, msg)
1395 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1396 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1397 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1398 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1402 #if ENABLE_HUSH_INTERACTIVE
1403 static void cmdedit_update_prompt(void);
1405 # define cmdedit_update_prompt() ((void)0)
1409 /* Utility functions
1411 /* Replace each \x with x in place, return ptr past NUL. */
1412 static char *unbackslash(char *src)
1414 char *dst = src = strchrnul(src, '\\');
1418 if ((*dst++ = *src++) == '\0')
1424 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1445 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1446 v[count1 + count2] = NULL;
1449 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1453 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1455 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1456 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1459 #define add_strings_to_strings(strings, add, need_to_dup) \
1460 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1463 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1464 static char **add_string_to_strings(char **strings, char *add)
1469 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1472 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1474 char **ptr = add_string_to_strings(strings, add);
1475 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1478 #define add_string_to_strings(strings, add) \
1479 xx_add_string_to_strings(__LINE__, strings, add)
1482 static void free_strings(char **strings)
1496 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1500 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1510 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1514 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1520 /* fd was not open? */
1525 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1526 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1532 /* Manipulating the list of open FILEs */
1533 static FILE *remember_FILE(FILE *fp)
1536 struct FILE_list *n = xmalloc(sizeof(*n));
1537 n->next = G.FILE_list;
1541 close_on_exec_on(n->fd);
1545 static void fclose_and_forget(FILE *fp)
1547 struct FILE_list **pp = &G.FILE_list;
1549 struct FILE_list *cur = *pp;
1550 if (cur->fp == fp) {
1559 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1561 struct FILE_list *fl = G.FILE_list;
1564 /* We use it only on script files, they are all CLOEXEC */
1565 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1566 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1573 static void restore_redirected_FILEs(void)
1575 struct FILE_list *fl = G.FILE_list;
1577 int should_be = fileno(fl->fp);
1578 if (fl->fd != should_be) {
1579 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1580 xmove_fd(fl->fd, should_be);
1586 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1587 static void close_all_FILE_list(void)
1589 struct FILE_list *fl = G.FILE_list;
1591 /* fclose would also free FILE object.
1592 * It is disastrous if we share memory with a vforked parent.
1593 * I'm not sure we never come here after vfork.
1594 * Therefore just close fd, nothing more.
1596 /*fclose(fl->fp); - unsafe */
1602 static int fd_in_FILEs(int fd)
1604 struct FILE_list *fl = G.FILE_list;
1614 /* Helpers for setting new $n and restoring them back
1616 typedef struct save_arg_t {
1620 IF_HUSH_SET(smallint sv_g_malloced;)
1623 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1625 sv->sv_argv0 = argv[0];
1626 sv->sv_g_argv = G.global_argv;
1627 sv->sv_g_argc = G.global_argc;
1628 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1630 argv[0] = G.global_argv[0]; /* retain $0 */
1631 G.global_argv = argv;
1632 IF_HUSH_SET(G.global_args_malloced = 0;)
1634 G.global_argc = 1 + string_array_len(argv + 1);
1637 static void restore_G_args(save_arg_t *sv, char **argv)
1640 if (G.global_args_malloced) {
1641 /* someone ran "set -- arg1 arg2 ...", undo */
1642 char **pp = G.global_argv;
1643 while (*++pp) /* note: does not free $0 */
1645 free(G.global_argv);
1648 argv[0] = sv->sv_argv0;
1649 G.global_argv = sv->sv_g_argv;
1650 G.global_argc = sv->sv_g_argc;
1651 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1655 /* Basic theory of signal handling in shell
1656 * ========================================
1657 * This does not describe what hush does, rather, it is current understanding
1658 * what it _should_ do. If it doesn't, it's a bug.
1659 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1661 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1662 * is finished or backgrounded. It is the same in interactive and
1663 * non-interactive shells, and is the same regardless of whether
1664 * a user trap handler is installed or a shell special one is in effect.
1665 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1666 * backgrounds (i.e. stops) or kills all members of currently running
1669 * Wait builtin is interruptible by signals for which user trap is set
1670 * or by SIGINT in interactive shell.
1672 * Trap handlers will execute even within trap handlers. (right?)
1674 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1675 * except for handlers set to '' (empty string).
1677 * If job control is off, backgrounded commands ("cmd &")
1678 * have SIGINT, SIGQUIT set to SIG_IGN.
1680 * Commands which are run in command substitution ("`cmd`")
1681 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1683 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1684 * by the shell from its parent.
1686 * Signals which differ from SIG_DFL action
1687 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1690 * SIGTERM (interactive): ignore
1691 * SIGHUP (interactive):
1692 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1693 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1694 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1695 * that all pipe members are stopped. Try this in bash:
1696 * while :; do :; done - ^Z does not background it
1697 * (while :; do :; done) - ^Z backgrounds it
1698 * SIGINT (interactive): wait for last pipe, ignore the rest
1699 * of the command line, show prompt. NB: ^C does not send SIGINT
1700 * to interactive shell while shell is waiting for a pipe,
1701 * since shell is bg'ed (is not in foreground process group).
1702 * Example 1: this waits 5 sec, but does not execute ls:
1703 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1704 * Example 2: this does not wait and does not execute ls:
1705 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1706 * Example 3: this does not wait 5 sec, but executes ls:
1707 * "sleep 5; ls -l" + press ^C
1708 * Example 4: this does not wait and does not execute ls:
1709 * "sleep 5 & wait; ls -l" + press ^C
1711 * (What happens to signals which are IGN on shell start?)
1712 * (What happens with signal mask on shell start?)
1714 * Old implementation
1715 * ==================
1716 * We use in-kernel pending signal mask to determine which signals were sent.
1717 * We block all signals which we don't want to take action immediately,
1718 * i.e. we block all signals which need to have special handling as described
1719 * above, and all signals which have traps set.
1720 * After each pipe execution, we extract any pending signals via sigtimedwait()
1723 * unsigned special_sig_mask: a mask of such "special" signals
1724 * sigset_t blocked_set: current blocked signal set
1727 * clear bit in blocked_set unless it is also in special_sig_mask
1728 * "trap 'cmd' SIGxxx":
1729 * set bit in blocked_set (even if 'cmd' is '')
1730 * after [v]fork, if we plan to be a shell:
1731 * unblock signals with special interactive handling
1732 * (child shell is not interactive),
1733 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1734 * after [v]fork, if we plan to exec:
1735 * POSIX says fork clears pending signal mask in child - no need to clear it.
1736 * Restore blocked signal set to one inherited by shell just prior to exec.
1738 * Note: as a result, we do not use signal handlers much. The only uses
1739 * are to count SIGCHLDs
1740 * and to restore tty pgrp on signal-induced exit.
1743 * Standard says "When a subshell is entered, traps that are not being ignored
1744 * are set to the default actions". bash interprets it so that traps which
1745 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1747 * Problem: the above approach makes it unwieldy to catch signals while
1748 * we are in read builtin, or while we read commands from stdin:
1749 * masked signals are not visible!
1751 * New implementation
1752 * ==================
1753 * We record each signal we are interested in by installing signal handler
1754 * for them - a bit like emulating kernel pending signal mask in userspace.
1755 * We are interested in: signals which need to have special handling
1756 * as described above, and all signals which have traps set.
1757 * Signals are recorded in pending_set.
1758 * After each pipe execution, we extract any pending signals
1761 * unsigned special_sig_mask: a mask of shell-special signals.
1762 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1763 * char *traps[sig] if trap for sig is set (even if it's '').
1764 * sigset_t pending_set: set of sigs we received.
1767 * if sig is in special_sig_mask, set handler back to:
1768 * record_pending_signo, or to IGN if it's a tty stop signal
1769 * if sig is in fatal_sig_mask, set handler back to sigexit.
1770 * else: set handler back to SIG_DFL
1771 * "trap 'cmd' SIGxxx":
1772 * set handler to record_pending_signo.
1774 * set handler to SIG_IGN.
1775 * after [v]fork, if we plan to be a shell:
1776 * set signals with special interactive handling to SIG_DFL
1777 * (because child shell is not interactive),
1778 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1779 * after [v]fork, if we plan to exec:
1780 * POSIX says fork clears pending signal mask in child - no need to clear it.
1782 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1783 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1786 * Standard says "When a subshell is entered, traps that are not being ignored
1787 * are set to the default actions". bash interprets it so that traps which
1788 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1791 SPECIAL_INTERACTIVE_SIGS = 0
1796 SPECIAL_JOBSTOP_SIGS = 0
1805 static void record_pending_signo(int sig)
1807 sigaddset(&G.pending_set, sig);
1808 #if ENABLE_HUSH_FAST
1809 if (sig == SIGCHLD) {
1811 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1816 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1818 struct sigaction old_sa;
1820 /* We could use signal() to install handlers... almost:
1821 * except that we need to mask ALL signals while handlers run.
1822 * I saw signal nesting in strace, race window isn't small.
1823 * SA_RESTART is also needed, but in Linux, signal()
1824 * sets SA_RESTART too.
1826 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1827 /* sigfillset(&G.sa.sa_mask); - already done */
1828 /* G.sa.sa_flags = SA_RESTART; - already done */
1829 G.sa.sa_handler = handler;
1830 sigaction(sig, &G.sa, &old_sa);
1831 return old_sa.sa_handler;
1834 static void hush_exit(int exitcode) NORETURN;
1836 static void restore_ttypgrp_and__exit(void) NORETURN;
1837 static void restore_ttypgrp_and__exit(void)
1839 /* xfunc has failed! die die die */
1840 /* no EXIT traps, this is an escape hatch! */
1842 hush_exit(xfunc_error_retval);
1847 /* Needed only on some libc:
1848 * It was observed that on exit(), fgetc'ed buffered data
1849 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1850 * With the net effect that even after fork(), not vfork(),
1851 * exit() in NOEXECed applet in "sh SCRIPT":
1852 * noexec_applet_here
1853 * echo END_OF_SCRIPT
1854 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1855 * This makes "echo END_OF_SCRIPT" executed twice.
1856 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1857 * and in `cmd` handling.
1858 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1860 static void fflush_and__exit(void) NORETURN;
1861 static void fflush_and__exit(void)
1864 _exit(xfunc_error_retval);
1867 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1868 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1869 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1870 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1872 /* Restores tty foreground process group, and exits.
1873 * May be called as signal handler for fatal signal
1874 * (will resend signal to itself, producing correct exit state)
1875 * or called directly with -EXITCODE.
1876 * We also call it if xfunc is exiting.
1878 static void sigexit(int sig) NORETURN;
1879 static void sigexit(int sig)
1881 /* Careful: we can end up here after [v]fork. Do not restore
1882 * tty pgrp then, only top-level shell process does that */
1883 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1884 /* Disable all signals: job control, SIGPIPE, etc.
1885 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1887 sigprocmask_allsigs(SIG_BLOCK);
1888 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1891 /* Not a signal, just exit */
1895 kill_myself_with_sig(sig); /* does not return */
1899 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1900 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1904 static sighandler_t pick_sighandler(unsigned sig)
1906 sighandler_t handler = SIG_DFL;
1907 if (sig < sizeof(unsigned)*8) {
1908 unsigned sigmask = (1 << sig);
1912 if (G_fatal_sig_mask & sigmask)
1916 /* sig has special handling? */
1917 if (G.special_sig_mask & sigmask) {
1918 handler = record_pending_signo;
1919 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1920 * in order to ignore them: they will be raised
1921 * in an endless loop when we try to do some
1922 * terminal ioctls! We do have to _ignore_ these.
1924 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1931 /* Restores tty foreground process group, and exits. */
1932 static void hush_exit(int exitcode)
1934 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1935 save_history(G.line_input_state);
1939 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1941 /* argv[0] is unused */
1942 argv[1] = G_traps[0];
1944 G.exiting = 1; /* prevent EXIT trap recursion */
1945 /* Note: G_traps[0] is not cleared!
1946 * "trap" will still show it, if executed
1951 #if ENABLE_FEATURE_CLEAN_UP
1953 struct variable *cur_var;
1954 if (G.cwd != bb_msg_unknown)
1956 cur_var = G.top_var;
1958 struct variable *tmp = cur_var;
1959 if (!cur_var->max_len)
1960 free(cur_var->varstr);
1961 cur_var = cur_var->next;
1969 sigexit(- (exitcode & 0xff));
1976 //TODO: return a mask of ALL handled sigs?
1977 static int check_and_run_traps(void)
1984 if (sigisemptyset(&G.pending_set))
1989 if (sigismember(&G.pending_set, sig)) {
1990 sigdelset(&G.pending_set, sig);
1993 } while (sig < NSIG);
1996 if (G_traps && G_traps[sig]) {
1997 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1998 if (G_traps[sig][0]) {
1999 /* We have user-defined handler */
2000 smalluint save_rcode;
2002 /* argv[0] is unused */
2003 argv[1] = G_traps[sig];
2005 save_rcode = G.last_exitcode;
2007 //FIXME: shouldn't it be set to 128 + sig instead?
2008 G.last_exitcode = save_rcode;
2010 } /* else: "" trap, ignoring signal */
2013 /* not a trap: special action */
2016 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2022 //TODO: why are we doing this? ash and dash don't do this,
2023 //they have no handler for SIGHUP at all,
2024 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2026 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2027 /* bash is observed to signal whole process groups,
2028 * not individual processes */
2029 for (job = G.job_list; job; job = job->next) {
2032 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2033 if (kill(- job->pgrp, SIGHUP) == 0)
2034 kill(- job->pgrp, SIGCONT);
2039 #if ENABLE_HUSH_FAST
2041 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2043 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2045 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2046 * This simplifies wait builtin a bit.
2050 default: /* ignored: */
2051 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2052 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2054 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2055 * Example: wait is not interrupted by TERM
2056 * in interactive shell, because TERM is ignored.
2065 static const char *get_cwd(int force)
2067 if (force || G.cwd == NULL) {
2068 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2069 * we must not try to free(bb_msg_unknown) */
2070 if (G.cwd == bb_msg_unknown)
2072 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2074 G.cwd = bb_msg_unknown;
2081 * Shell and environment variable support
2083 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2085 struct variable **pp;
2086 struct variable *cur;
2089 while ((cur = *pp) != NULL) {
2090 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2097 static const char* FAST_FUNC get_local_var_value(const char *name)
2099 struct variable **vpp;
2100 unsigned len = strlen(name);
2102 if (G.expanded_assignments) {
2103 char **cpp = G.expanded_assignments;
2106 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2107 return cp + len + 1;
2112 vpp = get_ptr_to_local_var(name, len);
2114 return (*vpp)->varstr + len + 1;
2116 if (strcmp(name, "PPID") == 0)
2117 return utoa(G.root_ppid);
2118 // bash compat: UID? EUID?
2119 #if ENABLE_HUSH_RANDOM_SUPPORT
2120 if (strcmp(name, "RANDOM") == 0)
2121 return utoa(next_random(&G.random_gen));
2126 /* str holds "NAME=VAL" and is expected to be malloced.
2127 * We take ownership of it.
2129 #define SETFLAG_EXPORT (1 << 0)
2130 #define SETFLAG_UNEXPORT (1 << 1)
2131 #define SETFLAG_MAKE_RO (1 << 2)
2132 #define SETFLAG_LOCAL_SHIFT 3
2133 static int set_local_var(char *str, unsigned flags)
2135 struct variable **var_pp;
2136 struct variable *cur;
2137 char *free_me = NULL;
2140 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2142 eq_sign = strchr(str, '=');
2143 if (!eq_sign) { /* not expected to ever happen? */
2148 name_len = eq_sign - str + 1; /* including '=' */
2151 if (name_len == 7 && strncmp("LINENO", str, 6) == 0)
2152 G.lineno_var = NULL;
2156 var_pp = &G.top_var;
2157 while ((cur = *var_pp) != NULL) {
2158 if (strncmp(cur->varstr, str, name_len) != 0) {
2159 var_pp = &cur->next;
2163 /* We found an existing var with this name */
2164 if (cur->flg_read_only) {
2165 bb_error_msg("%s: readonly variable", str);
2167 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2168 //but export per se succeeds (does put the var in env). We don't mimic that.
2171 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2172 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2177 #if ENABLE_HUSH_LOCAL
2178 if (cur->func_nest_level < local_lvl) {
2179 /* New variable is declared as local,
2180 * and existing one is global, or local
2181 * from enclosing function.
2182 * Remove and save old one: */
2183 *var_pp = cur->next;
2184 cur->next = *G.shadowed_vars_pp;
2185 *G.shadowed_vars_pp = cur;
2186 /* bash 3.2.33(1) and exported vars:
2188 * # f() { local z=a; env | grep ^z; }
2194 if (cur->flg_export)
2195 flags |= SETFLAG_EXPORT;
2199 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2204 if (cur->max_len != 0) {
2205 if (cur->max_len >= strlen(str)) {
2206 /* This one is from startup env, reuse space */
2207 strcpy(cur->varstr, str);
2212 goto set_str_and_exp;
2214 /* max_len == 0 signifies "malloced" var, which we can
2215 * (and have to) free. But we can't free(cur->varstr) here:
2216 * if cur->flg_export is 1, it is in the environment.
2217 * We should either unsetenv+free, or wait until putenv,
2218 * then putenv(new)+free(old).
2220 free_me = cur->varstr;
2221 goto set_str_and_exp;
2224 /* Not found - create new variable struct */
2225 cur = xzalloc(sizeof(*cur));
2226 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2227 cur->next = *var_pp;
2233 #if !BB_MMU || ENABLE_HUSH_READONLY
2234 if (flags & SETFLAG_MAKE_RO) {
2235 cur->flg_read_only = 1;
2238 if (flags & SETFLAG_EXPORT)
2239 cur->flg_export = 1;
2240 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2241 cmdedit_update_prompt();
2242 #if ENABLE_HUSH_GETOPTS
2243 /* defoptindvar is a "OPTIND=..." constant string */
2244 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
2247 if (cur->flg_export) {
2248 if (flags & SETFLAG_UNEXPORT) {
2249 cur->flg_export = 0;
2250 /* unsetenv was already done */
2253 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2254 i = putenv(cur->varstr);
2255 /* only now we can free old exported malloced string */
2264 /* Used at startup and after each cd */
2265 static void set_pwd_var(unsigned flag)
2267 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2270 static int unset_local_var_len(const char *name, int name_len)
2272 struct variable *cur;
2273 struct variable **var_pp;
2276 return EXIT_SUCCESS;
2278 #if ENABLE_HUSH_GETOPTS
2279 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2283 if (name_len == 6 && G.lineno_var && strncmp(name, "LINENO", 6) == 0)
2284 G.lineno_var = NULL;
2287 var_pp = &G.top_var;
2288 while ((cur = *var_pp) != NULL) {
2289 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2290 if (cur->flg_read_only) {
2291 bb_error_msg("%s: readonly variable", name);
2292 return EXIT_FAILURE;
2294 *var_pp = cur->next;
2295 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2296 bb_unsetenv(cur->varstr);
2297 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2298 cmdedit_update_prompt();
2302 return EXIT_SUCCESS;
2304 var_pp = &cur->next;
2306 return EXIT_SUCCESS;
2309 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2310 static int unset_local_var(const char *name)
2312 return unset_local_var_len(name, strlen(name));
2316 static void unset_vars(char **strings)
2324 const char *eq = strchrnul(*v, '=');
2325 unset_local_var_len(*v, (int)(eq - *v));
2331 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
2332 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2334 char *var = xasprintf("%s=%s", name, val);
2335 set_local_var(var, /*flag:*/ 0);
2341 * Helpers for "var1=val1 var2=val2 cmd" feature
2343 static void add_vars(struct variable *var)
2345 struct variable *next;
2349 var->next = G.top_var;
2351 if (var->flg_export) {
2352 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2353 putenv(var->varstr);
2355 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2361 static struct variable *set_vars_and_save_old(char **strings)
2364 struct variable *old = NULL;
2370 struct variable *var_p;
2371 struct variable **var_pp;
2374 eq = strchr(*s, '=');
2376 var_pp = get_ptr_to_local_var(*s, eq - *s);
2379 if (var_p->flg_read_only) {
2381 bb_error_msg("%s: readonly variable", *s);
2383 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2384 * If VAR is readonly, leaving it in the list
2385 * after asssignment error (msg above)
2386 * causes doubled error message later, on unset.
2388 debug_printf_env("removing/freeing '%s' element\n", *s);
2391 do { *p = p[1]; p++; } while (*p);
2394 /* Remove variable from global linked list */
2395 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2396 *var_pp = var_p->next;
2397 /* Add it to returned list */
2401 set_local_var(*s, SETFLAG_EXPORT);
2413 static void reinit_unicode_for_hush(void)
2415 /* Unicode support should be activated even if LANG is set
2416 * _during_ shell execution, not only if it was set when
2417 * shell was started. Therefore, re-check LANG every time:
2419 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2420 || ENABLE_UNICODE_USING_LOCALE
2422 const char *s = get_local_var_value("LC_ALL");
2423 if (!s) s = get_local_var_value("LC_CTYPE");
2424 if (!s) s = get_local_var_value("LANG");
2430 * in_str support (strings, and "strings" read from files).
2433 #if ENABLE_HUSH_INTERACTIVE
2434 /* To test correct lineedit/interactive behavior, type from command line:
2440 * It exercises a lot of corner cases.
2442 static void cmdedit_update_prompt(void)
2444 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2445 G.PS1 = get_local_var_value("PS1");
2448 G.PS2 = get_local_var_value("PS2");
2455 static const char *setup_prompt_string(int promptmode)
2457 const char *prompt_str;
2458 debug_printf("setup_prompt_string %d ", promptmode);
2459 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2460 /* Set up the prompt */
2461 if (promptmode == 0) { /* PS1 */
2463 /* bash uses $PWD value, even if it is set by user.
2464 * It uses current dir only if PWD is unset.
2465 * We always use current dir. */
2466 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2471 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2472 debug_printf("prompt_str '%s'\n", prompt_str);
2475 static int get_user_input(struct in_str *i)
2478 const char *prompt_str;
2480 prompt_str = setup_prompt_string(i->promptmode);
2481 # if ENABLE_FEATURE_EDITING
2483 reinit_unicode_for_hush();
2484 if (G.flag_SIGINT) {
2485 /* There was ^C'ed, make it look prettier: */
2489 /* buglet: SIGINT will not make new prompt to appear _at once_,
2490 * only after <Enter>. (^C works immediately) */
2491 r = read_line_input(G.line_input_state, prompt_str,
2492 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2494 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2497 check_and_run_traps();
2498 if (r != 0 && !G.flag_SIGINT)
2500 /* ^C or SIGINT: repeat */
2501 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2502 write(STDOUT_FILENO, "^C", 2);
2503 G.last_exitcode = 128 + SIGINT;
2506 /* EOF/error detected */
2508 i->peek_buf[0] = r = EOF;
2511 i->p = G.user_input_buf;
2512 return (unsigned char)*i->p++;
2516 if (i->last_char == '\0' || i->last_char == '\n') {
2517 /* Why check_and_run_traps here? Try this interactively:
2518 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2519 * $ <[enter], repeatedly...>
2520 * Without check_and_run_traps, handler never runs.
2522 check_and_run_traps();
2523 fputs(prompt_str, stdout);
2526 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2528 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2529 * no ^C masking happens during fgetc, no special code for ^C:
2530 * it generates SIGINT as usual.
2532 check_and_run_traps();
2534 G.last_exitcode = 128 + SIGINT;
2541 /* This is the magic location that prints prompts
2542 * and gets data back from the user */
2543 static int fgetc_interactive(struct in_str *i)
2546 /* If it's interactive stdin, get new line. */
2547 if (G_interactive_fd && i->file == stdin) {
2548 /* Returns first char (or EOF), the rest is in i->p[] */
2549 ch = get_user_input(i);
2550 i->promptmode = 1; /* PS2 */
2552 /* Not stdin: script file, sourced file, etc */
2553 do ch = fgetc(i->file); while (ch == '\0');
2558 static inline int fgetc_interactive(struct in_str *i)
2561 do ch = fgetc(i->file); while (ch == '\0');
2564 #endif /* INTERACTIVE */
2566 static int i_getch(struct in_str *i)
2571 /* string-based in_str */
2572 ch = (unsigned char)*i->p;
2581 /* FILE-based in_str */
2583 #if ENABLE_FEATURE_EDITING
2584 /* This can be stdin, check line editing char[] buffer */
2585 if (i->p && *i->p != '\0') {
2586 ch = (unsigned char)*i->p++;
2590 /* peek_buf[] is an int array, not char. Can contain EOF. */
2591 ch = i->peek_buf[0];
2593 int ch2 = i->peek_buf[1];
2594 i->peek_buf[0] = ch2;
2595 if (ch2 == 0) /* very likely, avoid redundant write */
2601 ch = fgetc_interactive(i);
2603 debug_printf("file_get: got '%c' %d\n", ch, ch);
2612 static int i_peek(struct in_str *i)
2617 /* string-based in_str */
2618 /* Doesn't report EOF on NUL. None of the callers care. */
2619 return (unsigned char)*i->p;
2622 /* FILE-based in_str */
2624 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2625 /* This can be stdin, check line editing char[] buffer */
2626 if (i->p && *i->p != '\0')
2627 return (unsigned char)*i->p;
2629 /* peek_buf[] is an int array, not char. Can contain EOF. */
2630 ch = i->peek_buf[0];
2634 /* Need to get a new char */
2635 ch = fgetc_interactive(i);
2636 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2638 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2639 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2645 i->peek_buf[0] = ch;
2646 /*i->peek_buf[1] = 0; - already is */
2650 /* Only ever called if i_peek() was called, and did not return EOF.
2651 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2652 * not end-of-line. Therefore we never need to read a new editing line here.
2654 static int i_peek2(struct in_str *i)
2658 /* There are two cases when i->p[] buffer exists.
2659 * (1) it's a string in_str.
2660 * (2) It's a file, and we have a saved line editing buffer.
2661 * In both cases, we know that i->p[0] exists and not NUL, and
2662 * the peek2 result is in i->p[1].
2665 return (unsigned char)i->p[1];
2667 /* Now we know it is a file-based in_str. */
2669 /* peek_buf[] is an int array, not char. Can contain EOF. */
2670 /* Is there 2nd char? */
2671 ch = i->peek_buf[1];
2673 /* We did not read it yet, get it now */
2674 do ch = fgetc(i->file); while (ch == '\0');
2675 i->peek_buf[1] = ch;
2678 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2682 static void setup_file_in_str(struct in_str *i, FILE *f)
2684 memset(i, 0, sizeof(*i));
2685 /* i->promptmode = 0; - PS1 (memset did it) */
2690 static void setup_string_in_str(struct in_str *i, const char *s)
2692 memset(i, 0, sizeof(*i));
2693 /* i->promptmode = 0; - PS1 (memset did it) */
2694 /*i->file = NULL */;
2702 #define B_CHUNK (32 * sizeof(char*))
2704 static void o_reset_to_empty_unquoted(o_string *o)
2707 o->has_quoted_part = 0;
2712 static void o_free(o_string *o)
2715 memset(o, 0, sizeof(*o));
2718 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2723 static void o_grow_by(o_string *o, int len)
2725 if (o->length + len > o->maxlen) {
2726 o->maxlen += (2 * len) | (B_CHUNK-1);
2727 o->data = xrealloc(o->data, 1 + o->maxlen);
2731 static void o_addchr(o_string *o, int ch)
2733 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2734 if (o->length < o->maxlen) {
2735 /* likely. avoid o_grow_by() call */
2737 o->data[o->length] = ch;
2739 o->data[o->length] = '\0';
2747 /* Valid only if we know o_string is not empty */
2748 static void o_delchr(o_string *o)
2751 o->data[o->length] = '\0';
2755 static void o_addblock(o_string *o, const char *str, int len)
2758 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2762 static void o_addstr(o_string *o, const char *str)
2764 o_addblock(o, str, strlen(str));
2768 static void nommu_addchr(o_string *o, int ch)
2774 # define nommu_addchr(o, str) ((void)0)
2777 static void o_addstr_with_NUL(o_string *o, const char *str)
2779 o_addblock(o, str, strlen(str) + 1);
2783 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2784 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2785 * Apparently, on unquoted $v bash still does globbing
2786 * ("v='*.txt'; echo $v" prints all .txt files),
2787 * but NOT brace expansion! Thus, there should be TWO independent
2788 * quoting mechanisms on $v expansion side: one protects
2789 * $v from brace expansion, and other additionally protects "$v" against globbing.
2790 * We have only second one.
2793 #if ENABLE_HUSH_BRACE_EXPANSION
2794 # define MAYBE_BRACES "{}"
2796 # define MAYBE_BRACES ""
2799 /* My analysis of quoting semantics tells me that state information
2800 * is associated with a destination, not a source.
2802 static void o_addqchr(o_string *o, int ch)
2805 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2810 o->data[o->length] = '\\';
2813 o->data[o->length] = ch;
2815 o->data[o->length] = '\0';
2818 static void o_addQchr(o_string *o, int ch)
2821 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2822 && strchr("*?[\\" MAYBE_BRACES, ch)
2825 o->data[o->length] = '\\';
2829 o->data[o->length] = ch;
2831 o->data[o->length] = '\0';
2834 static void o_addqblock(o_string *o, const char *str, int len)
2839 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2840 if (ordinary_cnt > len) /* paranoia */
2842 o_addblock(o, str, ordinary_cnt);
2843 if (ordinary_cnt == len)
2844 return; /* NUL is already added by o_addblock */
2845 str += ordinary_cnt;
2846 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2850 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2852 o->data[o->length] = '\\';
2856 o->data[o->length] = ch;
2859 o->data[o->length] = '\0';
2862 static void o_addQblock(o_string *o, const char *str, int len)
2864 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2865 o_addblock(o, str, len);
2868 o_addqblock(o, str, len);
2871 static void o_addQstr(o_string *o, const char *str)
2873 o_addQblock(o, str, strlen(str));
2876 /* A special kind of o_string for $VAR and `cmd` expansion.
2877 * It contains char* list[] at the beginning, which is grown in 16 element
2878 * increments. Actual string data starts at the next multiple of 16 * (char*).
2879 * list[i] contains an INDEX (int!) into this string data.
2880 * It means that if list[] needs to grow, data needs to be moved higher up
2881 * but list[i]'s need not be modified.
2882 * NB: remembering how many list[i]'s you have there is crucial.
2883 * o_finalize_list() operation post-processes this structure - calculates
2884 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2886 #if DEBUG_EXPAND || DEBUG_GLOB
2887 static void debug_print_list(const char *prefix, o_string *o, int n)
2889 char **list = (char**)o->data;
2890 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2894 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2895 prefix, list, n, string_start, o->length, o->maxlen,
2896 !!(o->o_expflags & EXP_FLAG_GLOB),
2898 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2901 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2902 o->data + (int)(uintptr_t)list[i] + string_start,
2903 o->data + (int)(uintptr_t)list[i] + string_start);
2907 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2909 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2913 # define debug_print_list(prefix, o, n) ((void)0)
2916 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2917 * in list[n] so that it points past last stored byte so far.
2918 * It returns n+1. */
2919 static int o_save_ptr_helper(o_string *o, int n)
2921 char **list = (char**)o->data;
2925 if (!o->has_empty_slot) {
2926 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2927 string_len = o->length - string_start;
2928 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2929 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2930 /* list[n] points to string_start, make space for 16 more pointers */
2931 o->maxlen += 0x10 * sizeof(list[0]);
2932 o->data = xrealloc(o->data, o->maxlen + 1);
2933 list = (char**)o->data;
2934 memmove(list + n + 0x10, list + n, string_len);
2935 o->length += 0x10 * sizeof(list[0]);
2937 debug_printf_list("list[%d]=%d string_start=%d\n",
2938 n, string_len, string_start);
2941 /* We have empty slot at list[n], reuse without growth */
2942 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2943 string_len = o->length - string_start;
2944 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2945 n, string_len, string_start);
2946 o->has_empty_slot = 0;
2948 o->has_quoted_part = 0;
2949 list[n] = (char*)(uintptr_t)string_len;
2953 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2954 static int o_get_last_ptr(o_string *o, int n)
2956 char **list = (char**)o->data;
2957 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2959 return ((int)(uintptr_t)list[n-1]) + string_start;
2962 #if ENABLE_HUSH_BRACE_EXPANSION
2963 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2964 * first, it processes even {a} (no commas), second,
2965 * I didn't manage to make it return strings when they don't match
2966 * existing files. Need to re-implement it.
2970 static int glob_needed(const char *s)
2979 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2985 /* Return pointer to next closing brace or to comma */
2986 static const char *next_brace_sub(const char *cp)
2990 while (*cp != '\0') {
2997 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3003 return *cp != '\0' ? cp : NULL;
3005 /* Recursive brace globber. Note: may garble pattern[]. */
3006 static int glob_brace(char *pattern, o_string *o, int n)
3008 char *new_pattern_buf;
3015 debug_printf_glob("glob_brace('%s')\n", pattern);
3021 if (*begin == '{') {
3022 /* Find the first sub-pattern and at the same time
3023 * find the rest after the closing brace */
3024 next = next_brace_sub(begin);
3026 /* An illegal expression */
3030 /* "{abc}" with no commas - illegal
3031 * brace expr, disregard and skip it */
3037 if (*begin == '\\' && begin[1] != '\0')
3041 debug_printf_glob("begin:%s\n", begin);
3042 debug_printf_glob("next:%s\n", next);
3044 /* Now find the end of the whole brace expression */
3046 while (*rest != '}') {
3047 rest = next_brace_sub(rest);
3049 /* An illegal expression */
3052 debug_printf_glob("rest:%s\n", rest);
3054 rest_len = strlen(++rest) + 1;
3056 /* We are sure the brace expression is well-formed */
3058 /* Allocate working buffer large enough for our work */
3059 new_pattern_buf = xmalloc(strlen(pattern));
3061 /* We have a brace expression. BEGIN points to the opening {,
3062 * NEXT points past the terminator of the first element, and REST
3063 * points past the final }. We will accumulate result names from
3064 * recursive runs for each brace alternative in the buffer using
3069 /* Construct the new glob expression */
3072 mempcpy(new_pattern_buf,
3073 /* We know the prefix for all sub-patterns */
3074 pattern, begin - pattern),
3078 /* Note: glob_brace() may garble new_pattern_buf[].
3079 * That's why we re-copy prefix every time (1st memcpy above).
3081 n = glob_brace(new_pattern_buf, o, n);
3083 /* We saw the last entry */
3087 next = next_brace_sub(next);
3089 free(new_pattern_buf);
3097 memset(&globdata, 0, sizeof(globdata));
3098 gr = glob(pattern, 0, NULL, &globdata);
3099 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3101 if (gr == GLOB_NOMATCH) {
3102 globfree(&globdata);
3103 /* NB: garbles parameter */
3104 unbackslash(pattern);
3105 o_addstr_with_NUL(o, pattern);
3106 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3107 return o_save_ptr_helper(o, n);
3109 if (gr == GLOB_NOSPACE)
3110 bb_error_msg_and_die(bb_msg_memory_exhausted);
3111 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3112 * but we didn't specify it. Paranoia again. */
3113 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3115 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3116 char **argv = globdata.gl_pathv;
3118 o_addstr_with_NUL(o, *argv);
3119 n = o_save_ptr_helper(o, n);
3125 globfree(&globdata);
3129 /* Performs globbing on last list[],
3130 * saving each result as a new list[].
3132 static int perform_glob(o_string *o, int n)
3134 char *pattern, *copy;
3136 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3138 return o_save_ptr_helper(o, n);
3139 pattern = o->data + o_get_last_ptr(o, n);
3140 debug_printf_glob("glob pattern '%s'\n", pattern);
3141 if (!glob_needed(pattern)) {
3142 /* unbackslash last string in o in place, fix length */
3143 o->length = unbackslash(pattern) - o->data;
3144 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3145 return o_save_ptr_helper(o, n);
3148 copy = xstrdup(pattern);
3149 /* "forget" pattern in o */
3150 o->length = pattern - o->data;
3151 n = glob_brace(copy, o, n);
3154 debug_print_list("perform_glob returning", o, n);
3158 #else /* !HUSH_BRACE_EXPANSION */
3161 static int glob_needed(const char *s)
3170 if (*s == '*' || *s == '[' || *s == '?')
3176 /* Performs globbing on last list[],
3177 * saving each result as a new list[].
3179 static int perform_glob(o_string *o, int n)
3185 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3187 return o_save_ptr_helper(o, n);
3188 pattern = o->data + o_get_last_ptr(o, n);
3189 debug_printf_glob("glob pattern '%s'\n", pattern);
3190 if (!glob_needed(pattern)) {
3192 /* unbackslash last string in o in place, fix length */
3193 o->length = unbackslash(pattern) - o->data;
3194 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3195 return o_save_ptr_helper(o, n);
3198 memset(&globdata, 0, sizeof(globdata));
3199 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3200 * If we glob "*.\*" and don't find anything, we need
3201 * to fall back to using literal "*.*", but GLOB_NOCHECK
3202 * will return "*.\*"!
3204 gr = glob(pattern, 0, NULL, &globdata);
3205 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3207 if (gr == GLOB_NOMATCH) {
3208 globfree(&globdata);
3211 if (gr == GLOB_NOSPACE)
3212 bb_error_msg_and_die(bb_msg_memory_exhausted);
3213 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3214 * but we didn't specify it. Paranoia again. */
3215 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3217 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3218 char **argv = globdata.gl_pathv;
3219 /* "forget" pattern in o */
3220 o->length = pattern - o->data;
3222 o_addstr_with_NUL(o, *argv);
3223 n = o_save_ptr_helper(o, n);
3229 globfree(&globdata);
3231 debug_print_list("perform_glob returning", o, n);
3235 #endif /* !HUSH_BRACE_EXPANSION */
3237 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3238 * Otherwise, just finish current list[] and start new */
3239 static int o_save_ptr(o_string *o, int n)
3241 if (o->o_expflags & EXP_FLAG_GLOB) {
3242 /* If o->has_empty_slot, list[n] was already globbed
3243 * (if it was requested back then when it was filled)
3244 * so don't do that again! */
3245 if (!o->has_empty_slot)
3246 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3248 return o_save_ptr_helper(o, n);
3251 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3252 static char **o_finalize_list(o_string *o, int n)
3257 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3259 debug_print_list("finalized", o, n);
3260 debug_printf_expand("finalized n:%d\n", n);
3261 list = (char**)o->data;
3262 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3266 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3271 static void free_pipe_list(struct pipe *pi);
3273 /* Returns pi->next - next pipe in the list */
3274 static struct pipe *free_pipe(struct pipe *pi)
3279 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3280 for (i = 0; i < pi->num_cmds; i++) {
3281 struct command *command;
3282 struct redir_struct *r, *rnext;
3284 command = &pi->cmds[i];
3285 debug_printf_clean(" command %d:\n", i);
3286 if (command->argv) {
3290 for (a = 0, p = command->argv; *p; a++, p++) {
3291 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3294 free_strings(command->argv);
3295 //command->argv = NULL;
3297 /* not "else if": on syntax error, we may have both! */
3298 if (command->group) {
3299 debug_printf_clean(" begin group (cmd_type:%d)\n",
3301 free_pipe_list(command->group);
3302 debug_printf_clean(" end group\n");
3303 //command->group = NULL;
3305 /* else is crucial here.
3306 * If group != NULL, child_func is meaningless */
3307 #if ENABLE_HUSH_FUNCTIONS
3308 else if (command->child_func) {
3309 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3310 command->child_func->parent_cmd = NULL;
3314 free(command->group_as_string);
3315 //command->group_as_string = NULL;
3317 for (r = command->redirects; r; r = rnext) {
3318 debug_printf_clean(" redirect %d%s",
3319 r->rd_fd, redir_table[r->rd_type].descrip);
3320 /* guard against the case >$FOO, where foo is unset or blank */
3321 if (r->rd_filename) {
3322 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3323 free(r->rd_filename);
3324 //r->rd_filename = NULL;
3326 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3330 //command->redirects = NULL;
3332 free(pi->cmds); /* children are an array, they get freed all at once */
3336 //pi->cmdtext = NULL;
3344 static void free_pipe_list(struct pipe *pi)
3348 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3350 debug_printf_clean("pipe followup code %d\n", pi->followup);
3356 /*** Parsing routines ***/
3358 #ifndef debug_print_tree
3359 static void debug_print_tree(struct pipe *pi, int lvl)
3361 static const char *const PIPE[] = {
3367 static const char *RES[] = {
3368 [RES_NONE ] = "NONE" ,
3371 [RES_THEN ] = "THEN" ,
3372 [RES_ELIF ] = "ELIF" ,
3373 [RES_ELSE ] = "ELSE" ,
3376 # if ENABLE_HUSH_LOOPS
3377 [RES_FOR ] = "FOR" ,
3378 [RES_WHILE] = "WHILE",
3379 [RES_UNTIL] = "UNTIL",
3381 [RES_DONE ] = "DONE" ,
3383 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3386 # if ENABLE_HUSH_CASE
3387 [RES_CASE ] = "CASE" ,
3388 [RES_CASE_IN ] = "CASE_IN" ,
3389 [RES_MATCH] = "MATCH",
3390 [RES_CASE_BODY] = "CASE_BODY",
3391 [RES_ESAC ] = "ESAC" ,
3393 [RES_XXXX ] = "XXXX" ,
3394 [RES_SNTX ] = "SNTX" ,
3396 static const char *const CMDTYPE[] = {
3400 # if ENABLE_HUSH_FUNCTIONS
3409 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3410 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3412 while (prn < pi->num_cmds) {
3413 struct command *command = &pi->cmds[prn];
3414 char **argv = command->argv;
3416 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3418 command->assignment_cnt);
3419 if (command->group) {
3420 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3421 CMDTYPE[command->cmd_type],
3424 , " group_as_string:", command->group_as_string
3429 debug_print_tree(command->group, lvl+1);
3433 if (argv) while (*argv) {
3434 fdprintf(2, " '%s'", *argv);
3444 #endif /* debug_print_tree */
3446 static struct pipe *new_pipe(void)
3449 pi = xzalloc(sizeof(struct pipe));
3450 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3454 /* Command (member of a pipe) is complete, or we start a new pipe
3455 * if ctx->command is NULL.
3456 * No errors possible here.
3458 static int done_command(struct parse_context *ctx)
3460 /* The command is really already in the pipe structure, so
3461 * advance the pipe counter and make a new, null command. */
3462 struct pipe *pi = ctx->pipe;
3463 struct command *command = ctx->command;
3465 #if 0 /* Instead we emit error message at run time */
3466 if (ctx->pending_redirect) {
3467 /* For example, "cmd >" (no filename to redirect to) */
3468 syntax_error("invalid redirect");
3469 ctx->pending_redirect = NULL;
3474 if (IS_NULL_CMD(command)) {
3475 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3479 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3480 //debug_print_tree(ctx->list_head, 20);
3482 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3485 /* Only real trickiness here is that the uncommitted
3486 * command structure is not counted in pi->num_cmds. */
3487 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3488 ctx->command = command = &pi->cmds[pi->num_cmds];
3490 memset(command, 0, sizeof(*command));
3492 command->lineno = G.lineno;
3494 return pi->num_cmds; /* used only for 0/nonzero check */
3497 static void done_pipe(struct parse_context *ctx, pipe_style type)
3501 debug_printf_parse("done_pipe entered, followup %d\n", type);
3502 /* Close previous command */
3503 not_null = done_command(ctx);
3505 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3506 ctx->ctx_inverted = 0;
3507 ctx->pipe->res_word = ctx->ctx_res_w;
3509 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3510 /* Necessary since && and || have precedence over &:
3511 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3512 * in a backgrounded subshell.
3515 struct command *command;
3517 /* Is this actually this construct, all pipes end with && or ||? */
3518 pi = ctx->list_head;
3519 while (pi != ctx->pipe) {
3520 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3525 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3526 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3527 pi = xzalloc(sizeof(*pi));
3528 pi->followup = PIPE_BG;
3530 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3531 command = &pi->cmds[0];
3532 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3533 command->cmd_type = CMD_NORMAL;
3534 command->group = ctx->list_head;
3536 command->group_as_string = xstrndup(
3537 ctx->as_string.data,
3538 ctx->as_string.length - 1 /* do not copy last char, "&" */
3541 /* Replace all pipes in ctx with one newly created */
3542 ctx->list_head = ctx->pipe = pi;
3545 ctx->pipe->followup = type;
3548 /* Without this check, even just <enter> on command line generates
3549 * tree of three NOPs (!). Which is harmless but annoying.
3550 * IOW: it is safe to do it unconditionally. */
3553 || ctx->ctx_res_w == RES_FI
3555 #if ENABLE_HUSH_LOOPS
3556 || ctx->ctx_res_w == RES_DONE
3557 || ctx->ctx_res_w == RES_FOR
3558 || ctx->ctx_res_w == RES_IN
3560 #if ENABLE_HUSH_CASE
3561 || ctx->ctx_res_w == RES_ESAC
3565 debug_printf_parse("done_pipe: adding new pipe: "
3566 "not_null:%d ctx->ctx_res_w:%d\n",
3567 not_null, ctx->ctx_res_w);
3569 ctx->pipe->next = new_p;
3571 /* RES_THEN, RES_DO etc are "sticky" -
3572 * they remain set for pipes inside if/while.
3573 * This is used to control execution.
3574 * RES_FOR and RES_IN are NOT sticky (needed to support
3575 * cases where variable or value happens to match a keyword):
3577 #if ENABLE_HUSH_LOOPS
3578 if (ctx->ctx_res_w == RES_FOR
3579 || ctx->ctx_res_w == RES_IN)
3580 ctx->ctx_res_w = RES_NONE;
3582 #if ENABLE_HUSH_CASE
3583 if (ctx->ctx_res_w == RES_MATCH)
3584 ctx->ctx_res_w = RES_CASE_BODY;
3585 if (ctx->ctx_res_w == RES_CASE)
3586 ctx->ctx_res_w = RES_CASE_IN;
3588 ctx->command = NULL; /* trick done_command below */
3589 /* Create the memory for command, roughly:
3590 * ctx->pipe->cmds = new struct command;
3591 * ctx->command = &ctx->pipe->cmds[0];
3594 //debug_print_tree(ctx->list_head, 10);
3596 debug_printf_parse("done_pipe return\n");
3599 static void initialize_context(struct parse_context *ctx)
3601 memset(ctx, 0, sizeof(*ctx));
3602 ctx->pipe = ctx->list_head = new_pipe();
3603 /* Create the memory for command, roughly:
3604 * ctx->pipe->cmds = new struct command;
3605 * ctx->command = &ctx->pipe->cmds[0];
3610 /* If a reserved word is found and processed, parse context is modified
3611 * and 1 is returned.
3614 struct reserved_combo {
3617 unsigned char assignment_flag;
3621 FLAG_END = (1 << RES_NONE ),
3623 FLAG_IF = (1 << RES_IF ),
3624 FLAG_THEN = (1 << RES_THEN ),
3625 FLAG_ELIF = (1 << RES_ELIF ),
3626 FLAG_ELSE = (1 << RES_ELSE ),
3627 FLAG_FI = (1 << RES_FI ),
3629 # if ENABLE_HUSH_LOOPS
3630 FLAG_FOR = (1 << RES_FOR ),
3631 FLAG_WHILE = (1 << RES_WHILE),
3632 FLAG_UNTIL = (1 << RES_UNTIL),
3633 FLAG_DO = (1 << RES_DO ),
3634 FLAG_DONE = (1 << RES_DONE ),
3635 FLAG_IN = (1 << RES_IN ),
3637 # if ENABLE_HUSH_CASE
3638 FLAG_MATCH = (1 << RES_MATCH),
3639 FLAG_ESAC = (1 << RES_ESAC ),
3641 FLAG_START = (1 << RES_XXXX ),
3644 static const struct reserved_combo* match_reserved_word(o_string *word)
3646 /* Mostly a list of accepted follow-up reserved words.
3647 * FLAG_END means we are done with the sequence, and are ready
3648 * to turn the compound list into a command.
3649 * FLAG_START means the word must start a new compound list.
3651 static const struct reserved_combo reserved_list[] = {
3653 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3654 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3655 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3656 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3657 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3658 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3660 # if ENABLE_HUSH_LOOPS
3661 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3662 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3663 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3664 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3665 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3666 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3668 # if ENABLE_HUSH_CASE
3669 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3670 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3673 const struct reserved_combo *r;
3675 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3676 if (strcmp(word->data, r->literal) == 0)
3681 /* Return 0: not a keyword, 1: keyword
3683 static int reserved_word(o_string *word, struct parse_context *ctx)
3685 # if ENABLE_HUSH_CASE
3686 static const struct reserved_combo reserved_match = {
3687 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3690 const struct reserved_combo *r;
3692 if (word->has_quoted_part)
3694 r = match_reserved_word(word);
3698 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3699 # if ENABLE_HUSH_CASE
3700 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3701 /* "case word IN ..." - IN part starts first MATCH part */
3702 r = &reserved_match;
3705 if (r->flag == 0) { /* '!' */
3706 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3707 syntax_error("! ! command");
3708 ctx->ctx_res_w = RES_SNTX;
3710 ctx->ctx_inverted = 1;
3713 if (r->flag & FLAG_START) {
3714 struct parse_context *old;
3716 old = xmemdup(ctx, sizeof(*ctx));
3717 debug_printf_parse("push stack %p\n", old);
3718 initialize_context(ctx);
3720 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3721 syntax_error_at(word->data);
3722 ctx->ctx_res_w = RES_SNTX;
3725 /* "{...} fi" is ok. "{...} if" is not
3727 * if { echo foo; } then { echo bar; } fi */
3728 if (ctx->command->group)
3729 done_pipe(ctx, PIPE_SEQ);
3732 ctx->ctx_res_w = r->res;
3733 ctx->old_flag = r->flag;
3734 word->o_assignment = r->assignment_flag;
3735 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3737 if (ctx->old_flag & FLAG_END) {
3738 struct parse_context *old;
3740 done_pipe(ctx, PIPE_SEQ);
3741 debug_printf_parse("pop stack %p\n", ctx->stack);
3743 old->command->group = ctx->list_head;
3744 old->command->cmd_type = CMD_NORMAL;
3746 /* At this point, the compound command's string is in
3747 * ctx->as_string... except for the leading keyword!
3748 * Consider this example: "echo a | if true; then echo a; fi"
3749 * ctx->as_string will contain "true; then echo a; fi",
3750 * with "if " remaining in old->as_string!
3754 int len = old->as_string.length;
3755 /* Concatenate halves */
3756 o_addstr(&old->as_string, ctx->as_string.data);
3757 o_free_unsafe(&ctx->as_string);
3758 /* Find where leading keyword starts in first half */
3759 str = old->as_string.data + len;
3760 if (str > old->as_string.data)
3761 str--; /* skip whitespace after keyword */
3762 while (str > old->as_string.data && isalpha(str[-1]))
3764 /* Ugh, we're done with this horrid hack */
3765 old->command->group_as_string = xstrdup(str);
3766 debug_printf_parse("pop, remembering as:'%s'\n",
3767 old->command->group_as_string);
3770 *ctx = *old; /* physical copy */
3775 #endif /* HAS_KEYWORDS */
3777 /* Word is complete, look at it and update parsing context.
3778 * Normal return is 0. Syntax errors return 1.
3779 * Note: on return, word is reset, but not o_free'd!
3781 static int done_word(o_string *word, struct parse_context *ctx)
3783 struct command *command = ctx->command;
3785 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3786 if (word->length == 0 && !word->has_quoted_part) {
3787 debug_printf_parse("done_word return 0: true null, ignored\n");
3791 if (ctx->pending_redirect) {
3792 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3793 * only if run as "bash", not "sh" */
3794 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3796 * ...the word that follows the redirection operator
3797 * shall be subjected to tilde expansion, parameter expansion,
3798 * command substitution, arithmetic expansion, and quote
3799 * removal. Pathname expansion shall not be performed
3800 * on the word by a non-interactive shell; an interactive
3801 * shell may perform it, but shall do so only when
3802 * the expansion would result in one word."
3804 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3805 /* Cater for >\file case:
3806 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3807 * Same with heredocs:
3808 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3810 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3811 unbackslash(ctx->pending_redirect->rd_filename);
3812 /* Is it <<"HEREDOC"? */
3813 if (word->has_quoted_part) {
3814 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3817 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3818 ctx->pending_redirect = NULL;
3821 # if ENABLE_HUSH_CASE
3822 if (ctx->ctx_dsemicolon
3823 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3825 /* already done when ctx_dsemicolon was set to 1: */
3826 /* ctx->ctx_res_w = RES_MATCH; */
3827 ctx->ctx_dsemicolon = 0;
3830 if (!command->argv /* if it's the first word... */
3831 # if ENABLE_HUSH_LOOPS
3832 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3833 && ctx->ctx_res_w != RES_IN
3835 # if ENABLE_HUSH_CASE
3836 && ctx->ctx_res_w != RES_CASE
3839 int reserved = reserved_word(word, ctx);
3840 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3842 o_reset_to_empty_unquoted(word);
3843 debug_printf_parse("done_word return %d\n",
3844 (ctx->ctx_res_w == RES_SNTX));
3845 return (ctx->ctx_res_w == RES_SNTX);
3848 if (strcmp(word->data, "[[") == 0) {
3849 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3855 if (command->group) {
3856 /* "{ echo foo; } echo bar" - bad */
3857 syntax_error_at(word->data);
3858 debug_printf_parse("done_word return 1: syntax error, "
3859 "groups and arglists don't mix\n");
3863 /* If this word wasn't an assignment, next ones definitely
3864 * can't be assignments. Even if they look like ones. */
3865 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3866 && word->o_assignment != WORD_IS_KEYWORD
3868 word->o_assignment = NOT_ASSIGNMENT;
3870 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3871 command->assignment_cnt++;
3872 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3874 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3875 word->o_assignment = MAYBE_ASSIGNMENT;
3877 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3878 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3879 debug_print_strings("word appended to argv", command->argv);
3882 #if ENABLE_HUSH_LOOPS
3883 if (ctx->ctx_res_w == RES_FOR) {
3884 if (word->has_quoted_part
3885 || !is_well_formed_var_name(command->argv[0], '\0')
3887 /* bash says just "not a valid identifier" */
3888 syntax_error("not a valid identifier in for");
3891 /* Force FOR to have just one word (variable name) */
3892 /* NB: basically, this makes hush see "for v in ..."
3893 * syntax as if it is "for v; in ...". FOR and IN become
3894 * two pipe structs in parse tree. */
3895 done_pipe(ctx, PIPE_SEQ);
3898 #if ENABLE_HUSH_CASE
3899 /* Force CASE to have just one word */
3900 if (ctx->ctx_res_w == RES_CASE) {
3901 done_pipe(ctx, PIPE_SEQ);
3905 o_reset_to_empty_unquoted(word);
3907 debug_printf_parse("done_word return 0\n");
3912 /* Peek ahead in the input to find out if we have a "&n" construct,
3913 * as in "2>&1", that represents duplicating a file descriptor.
3915 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3916 * REDIRFD_SYNTAX_ERR if syntax error,
3917 * REDIRFD_TO_FILE if no & was seen,
3918 * or the number found.
3921 #define parse_redir_right_fd(as_string, input) \
3922 parse_redir_right_fd(input)
3924 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3930 return REDIRFD_TO_FILE;
3932 ch = i_getch(input); /* get the & */
3933 nommu_addchr(as_string, ch);
3936 ch = i_getch(input);
3937 nommu_addchr(as_string, ch);
3938 return REDIRFD_CLOSE;
3942 while (ch != EOF && isdigit(ch)) {
3943 d = d*10 + (ch-'0');
3945 ch = i_getch(input);
3946 nommu_addchr(as_string, ch);
3951 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3953 bb_error_msg("ambiguous redirect");
3954 return REDIRFD_SYNTAX_ERR;
3957 /* Return code is 0 normal, 1 if a syntax error is detected
3959 static int parse_redirect(struct parse_context *ctx,
3962 struct in_str *input)
3964 struct command *command = ctx->command;
3965 struct redir_struct *redir;
3966 struct redir_struct **redirp;
3969 dup_num = REDIRFD_TO_FILE;
3970 if (style != REDIRECT_HEREDOC) {
3971 /* Check for a '>&1' type redirect */
3972 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3973 if (dup_num == REDIRFD_SYNTAX_ERR)
3976 int ch = i_peek(input);
3977 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3978 if (dup_num) { /* <<-... */
3979 ch = i_getch(input);
3980 nommu_addchr(&ctx->as_string, ch);
3985 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3986 int ch = i_peek(input);
3988 /* >|FILE redirect ("clobbering" >).
3989 * Since we do not support "set -o noclobber" yet,
3990 * >| and > are the same for now. Just eat |.
3992 ch = i_getch(input);
3993 nommu_addchr(&ctx->as_string, ch);
3997 /* Create a new redir_struct and append it to the linked list */
3998 redirp = &command->redirects;
3999 while ((redir = *redirp) != NULL) {
4000 redirp = &(redir->next);
4002 *redirp = redir = xzalloc(sizeof(*redir));
4003 /* redir->next = NULL; */
4004 /* redir->rd_filename = NULL; */
4005 redir->rd_type = style;
4006 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4008 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4009 redir_table[style].descrip);
4011 redir->rd_dup = dup_num;
4012 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4013 /* Erik had a check here that the file descriptor in question
4014 * is legit; I postpone that to "run time"
4015 * A "-" representation of "close me" shows up as a -3 here */
4016 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4017 redir->rd_fd, redir->rd_dup);
4019 #if 0 /* Instead we emit error message at run time */
4020 if (ctx->pending_redirect) {
4021 /* For example, "cmd > <file" */
4022 syntax_error("invalid redirect");
4025 /* Set ctx->pending_redirect, so we know what to do at the
4026 * end of the next parsed word. */
4027 ctx->pending_redirect = redir;
4032 /* If a redirect is immediately preceded by a number, that number is
4033 * supposed to tell which file descriptor to redirect. This routine
4034 * looks for such preceding numbers. In an ideal world this routine
4035 * needs to handle all the following classes of redirects...
4036 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4037 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4038 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4039 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4041 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4043 * ... If n is quoted, the number shall not be recognized as part of
4044 * the redirection expression. For example:
4046 * writes the character 2 into file a"
4047 * We are getting it right by setting ->has_quoted_part on any \<char>
4049 * A -1 return means no valid number was found,
4050 * the caller should use the appropriate default for this redirection.
4052 static int redirect_opt_num(o_string *o)
4056 if (o->data == NULL)
4058 num = bb_strtou(o->data, NULL, 10);
4059 if (errno || num < 0)
4061 o_reset_to_empty_unquoted(o);
4066 #define fetch_till_str(as_string, input, word, skip_tabs) \
4067 fetch_till_str(input, word, skip_tabs)
4069 static char *fetch_till_str(o_string *as_string,
4070 struct in_str *input,
4074 o_string heredoc = NULL_O_STRING;
4076 int prev = 0; /* not \ */
4082 ch = i_getch(input);
4084 nommu_addchr(as_string, ch);
4085 if (ch == '\n' || ch == EOF) {
4087 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4088 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4089 heredoc.data[past_EOL] = '\0';
4090 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4091 return heredoc.data;
4094 /* This is a new line.
4095 * Remember position and backslash-escaping status.
4097 o_addchr(&heredoc, ch);
4100 past_EOL = heredoc.length;
4101 /* Get 1st char of next line, possibly skipping leading tabs */
4103 ch = i_getch(input);
4105 nommu_addchr(as_string, ch);
4106 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4107 /* If this immediately ended the line,
4108 * go back to end-of-line checks.
4111 goto check_heredoc_end;
4116 o_free_unsafe(&heredoc);
4119 o_addchr(&heredoc, ch);
4120 nommu_addchr(as_string, ch);
4121 if (prev == '\\' && ch == '\\')
4122 /* Correctly handle foo\\<eol> (not a line cont.) */
4123 prev = 0; /* not \ */
4129 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4130 * and load them all. There should be exactly heredoc_cnt of them.
4132 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4134 struct pipe *pi = ctx->list_head;
4136 while (pi && heredoc_cnt) {
4138 struct command *cmd = pi->cmds;
4140 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4142 cmd->argv ? cmd->argv[0] : "NONE");
4143 for (i = 0; i < pi->num_cmds; i++) {
4144 struct redir_struct *redir = cmd->redirects;
4146 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4147 i, cmd->argv ? cmd->argv[0] : "NONE");
4149 if (redir->rd_type == REDIRECT_HEREDOC) {
4152 redir->rd_type = REDIRECT_HEREDOC2;
4153 /* redir->rd_dup is (ab)used to indicate <<- */
4154 p = fetch_till_str(&ctx->as_string, input,
4155 redir->rd_filename, redir->rd_dup);
4157 syntax_error("unexpected EOF in here document");
4160 free(redir->rd_filename);
4161 redir->rd_filename = p;
4164 redir = redir->next;
4171 /* Should be 0. If it isn't, it's a parse error */
4173 bb_error_msg_and_die("heredoc BUG 2");
4179 static int run_list(struct pipe *pi);
4181 #define parse_stream(pstring, input, end_trigger) \
4182 parse_stream(input, end_trigger)
4184 static struct pipe *parse_stream(char **pstring,
4185 struct in_str *input,
4189 #if !ENABLE_HUSH_FUNCTIONS
4190 #define parse_group(dest, ctx, input, ch) \
4191 parse_group(ctx, input, ch)
4193 static int parse_group(o_string *dest, struct parse_context *ctx,
4194 struct in_str *input, int ch)
4196 /* dest contains characters seen prior to ( or {.
4197 * Typically it's empty, but for function defs,
4198 * it contains function name (without '()'). */
4199 struct pipe *pipe_list;
4201 struct command *command = ctx->command;
4203 debug_printf_parse("parse_group entered\n");
4204 #if ENABLE_HUSH_FUNCTIONS
4205 if (ch == '(' && !dest->has_quoted_part) {
4207 if (done_word(dest, ctx))
4210 goto skip; /* (... */
4211 if (command->argv[1]) { /* word word ... (... */
4212 syntax_error_unexpected_ch('(');
4215 /* it is "word(..." or "word (..." */
4217 ch = i_getch(input);
4218 while (ch == ' ' || ch == '\t');
4220 syntax_error_unexpected_ch(ch);
4223 nommu_addchr(&ctx->as_string, ch);
4225 ch = i_getch(input);
4226 while (ch == ' ' || ch == '\t' || ch == '\n');
4228 syntax_error_unexpected_ch(ch);
4231 nommu_addchr(&ctx->as_string, ch);
4232 command->cmd_type = CMD_FUNCDEF;
4237 #if 0 /* Prevented by caller */
4238 if (command->argv /* word [word]{... */
4239 || dest->length /* word{... */
4240 || dest->has_quoted_part /* ""{... */
4243 debug_printf_parse("parse_group return 1: "
4244 "syntax error, groups and arglists don't mix\n");
4249 #if ENABLE_HUSH_FUNCTIONS
4255 command->cmd_type = CMD_SUBSHELL;
4257 /* bash does not allow "{echo...", requires whitespace */
4259 if (ch != ' ' && ch != '\t' && ch != '\n'
4260 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4262 syntax_error_unexpected_ch(ch);
4266 ch = i_getch(input);
4267 nommu_addchr(&ctx->as_string, ch);
4273 # define as_string NULL
4275 char *as_string = NULL;
4277 pipe_list = parse_stream(&as_string, input, endch);
4280 o_addstr(&ctx->as_string, as_string);
4282 /* empty ()/{} or parse error? */
4283 if (!pipe_list || pipe_list == ERR_PTR) {
4284 /* parse_stream already emitted error msg */
4287 debug_printf_parse("parse_group return 1: "
4288 "parse_stream returned %p\n", pipe_list);
4291 command->group = pipe_list;
4293 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4294 command->group_as_string = as_string;
4295 debug_printf_parse("end of group, remembering as:'%s'\n",
4296 command->group_as_string);
4300 debug_printf_parse("parse_group return 0\n");
4302 /* command remains "open", available for possible redirects */
4305 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4310 ch = i_getch(input);
4313 ch2 = i_peek(input);
4316 /* backslash+newline, skip it */
4321 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4329 ch2 = i_peek2(input);
4332 /* backslash+newline, skip it */
4338 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4339 /* Subroutines for copying $(...) and `...` things */
4340 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4342 static int add_till_single_quote(o_string *dest, struct in_str *input)
4345 int ch = i_getch(input);
4347 syntax_error_unterm_ch('\'');
4355 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4356 static int add_till_double_quote(o_string *dest, struct in_str *input)
4359 int ch = i_getch(input);
4361 syntax_error_unterm_ch('"');
4366 if (ch == '\\') { /* \x. Copy both chars. */
4368 ch = i_getch(input);
4372 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4377 //if (ch == '$') ...
4380 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4382 * "Within the backquoted style of command substitution, backslash
4383 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4384 * The search for the matching backquote shall be satisfied by the first
4385 * backquote found without a preceding backslash; during this search,
4386 * if a non-escaped backquote is encountered within a shell comment,
4387 * a here-document, an embedded command substitution of the $(command)
4388 * form, or a quoted string, undefined results occur. A single-quoted
4389 * or double-quoted string that begins, but does not end, within the
4390 * "`...`" sequence produces undefined results."
4392 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4394 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4397 int ch = i_getch(input);
4401 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4402 ch = i_getch(input);
4406 && (!in_dquote || ch != '"')
4408 o_addchr(dest, '\\');
4412 syntax_error_unterm_ch('`');
4418 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4419 * quoting and nested ()s.
4420 * "With the $(command) style of command substitution, all characters
4421 * following the open parenthesis to the matching closing parenthesis
4422 * constitute the command. Any valid shell script can be used for command,
4423 * except a script consisting solely of redirections which produces
4424 * unspecified results."
4426 * echo $(echo '(TEST)' BEST) (TEST) BEST
4427 * echo $(echo 'TEST)' BEST) TEST) BEST
4428 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4430 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4431 * can contain arbitrary constructs, just like $(cmd).
4432 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4433 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4435 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4436 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4439 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4440 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4441 char end_char2 = end_ch >> 8;
4443 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4446 ch = i_getch(input);
4448 syntax_error_unterm_ch(end_ch);
4452 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4458 /* we look for closing )) of $((EXPR)) */
4459 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4460 i_getch(input); /* eat second ')' */
4465 if (ch == '(' || ch == '{') {
4466 ch = (ch == '(' ? ')' : '}');
4467 if (!add_till_closing_bracket(dest, input, ch))
4473 if (!add_till_single_quote(dest, input))
4479 if (!add_till_double_quote(dest, input))
4485 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4491 /* \x. Copy verbatim. Important for \(, \) */
4492 ch = i_getch(input);
4494 syntax_error_unterm_ch(')');
4499 /* "backslash+newline", ignore both */
4500 o_delchr(dest); /* undo insertion of '\' */
4510 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4512 /* Return code: 0 for OK, 1 for syntax error */
4514 #define parse_dollar(as_string, dest, input, quote_mask) \
4515 parse_dollar(dest, input, quote_mask)
4516 #define as_string NULL
4518 static int parse_dollar(o_string *as_string,
4520 struct in_str *input, unsigned char quote_mask)
4522 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4524 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4526 ch = i_getch(input);
4527 nommu_addchr(as_string, ch);
4529 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4531 debug_printf_parse(": '%c'\n", ch);
4532 o_addchr(dest, ch | quote_mask);
4534 ch = i_peek_and_eat_bkslash_nl(input);
4535 if (!isalnum(ch) && ch != '_') {
4536 /* End of variable name reached */
4539 ch = i_getch(input);
4540 nommu_addchr(as_string, ch);
4542 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4543 } else if (isdigit(ch)) {
4545 ch = i_getch(input);
4546 nommu_addchr(as_string, ch);
4547 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4548 debug_printf_parse(": '%c'\n", ch);
4549 o_addchr(dest, ch | quote_mask);
4550 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4551 } else switch (ch) {
4553 case '!': /* last bg pid */
4554 case '?': /* last exit code */
4555 case '#': /* number of args */
4556 case '*': /* args */
4557 case '@': /* args */
4558 goto make_one_char_var;
4562 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4564 ch = i_getch(input); /* eat '{' */
4565 nommu_addchr(as_string, ch);
4567 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4568 /* It should be ${?}, or ${#var},
4569 * or even ${?+subst} - operator acting on a special variable,
4570 * or the beginning of variable name.
4573 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4576 syntax_error_unterm_str("${name}");
4577 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4580 nommu_addchr(as_string, ch);
4584 /* It's possible to just call add_till_closing_bracket() at this point.
4585 * However, this regresses some of our testsuite cases
4586 * which check invalid constructs like ${%}.
4587 * Oh well... let's check that the var name part is fine... */
4593 debug_printf_parse(": '%c'\n", ch);
4595 ch = i_getch(input);
4596 nommu_addchr(as_string, ch);
4600 if (!isalnum(ch) && ch != '_') {
4602 unsigned char last_ch;
4603 /* handle parameter expansions
4604 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4606 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4607 if (len_single_ch != '#'
4608 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4609 || i_peek(input) != '}'
4611 goto bad_dollar_syntax;
4613 /* else: it's "length of C" ${#C} op,
4614 * where C is a single char
4615 * special var name, e.g. ${#!}.
4618 /* Eat everything until closing '}' (or ':') */
4622 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4624 /* It's ${var:N[:M]} thing */
4625 end_ch = '}' * 0x100 + ':';
4627 if (BASH_PATTERN_SUBST
4630 /* It's ${var/[/]pattern[/repl]} thing */
4631 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4633 nommu_addchr(as_string, '/');
4636 end_ch = '}' * 0x100 + '/';
4642 #if ENABLE_HUSH_DOLLAR_OPS
4643 last_ch = add_till_closing_bracket(dest, input, end_ch);
4644 if (last_ch == 0) /* error? */
4647 #error Simple code to only allow ${var} is not implemented
4650 o_addstr(as_string, dest->data + pos);
4651 o_addchr(as_string, last_ch);
4654 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4655 && (end_ch & 0xff00)
4657 /* close the first block: */
4658 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4659 /* while parsing N from ${var:N[:M]}
4660 * or pattern from ${var/[/]pattern[/repl]} */
4661 if ((end_ch & 0xff) == last_ch) {
4662 /* got ':' or '/'- parse the rest */
4667 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4668 /* it's ${var:N} - emulate :999999999 */
4669 o_addstr(dest, "999999999");
4670 } /* else: it's ${var/[/]pattern} */
4674 len_single_ch = 0; /* it can't be ${#C} op */
4676 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4679 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4683 ch = i_getch(input);
4684 nommu_addchr(as_string, ch);
4685 # if ENABLE_FEATURE_SH_MATH
4686 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4687 ch = i_getch(input);
4688 nommu_addchr(as_string, ch);
4689 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4690 o_addchr(dest, /*quote_mask |*/ '+');
4693 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4694 return 0; /* error */
4696 o_addstr(as_string, dest->data + pos);
4697 o_addchr(as_string, ')');
4698 o_addchr(as_string, ')');
4700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4704 # if ENABLE_HUSH_TICK
4705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4706 o_addchr(dest, quote_mask | '`');
4709 if (!add_till_closing_bracket(dest, input, ')'))
4710 return 0; /* error */
4712 o_addstr(as_string, dest->data + pos);
4713 o_addchr(as_string, ')');
4715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4721 ch = i_getch(input);
4722 nommu_addchr(as_string, ch);
4723 ch = i_peek_and_eat_bkslash_nl(input);
4724 if (isalnum(ch)) { /* it's $_name or $_123 */
4729 /* TODO: $_ and $-: */
4730 /* $_ Shell or shell script name; or last argument of last command
4731 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4732 * but in command's env, set to full pathname used to invoke it */
4733 /* $- Option flags set by set builtin or shell options (-i etc) */
4735 o_addQchr(dest, '$');
4737 debug_printf_parse("parse_dollar return 1 (ok)\n");
4743 # if BASH_PATTERN_SUBST
4744 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4745 encode_string(dest, input, dquote_end, process_bkslash)
4747 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4748 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4749 encode_string(dest, input, dquote_end)
4751 #define as_string NULL
4755 # if BASH_PATTERN_SUBST
4756 /* all parameters are needed, no macro tricks */
4758 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4759 encode_string(as_string, dest, input, dquote_end)
4762 static int encode_string(o_string *as_string,
4764 struct in_str *input,
4766 int process_bkslash)
4768 #if !BASH_PATTERN_SUBST
4769 const int process_bkslash = 1;
4775 ch = i_getch(input);
4777 nommu_addchr(as_string, ch);
4778 if (ch == dquote_end) { /* may be only '"' or EOF */
4779 debug_printf_parse("encode_string return 1 (ok)\n");
4782 /* note: can't move it above ch == dquote_end check! */
4784 syntax_error_unterm_ch('"');
4785 return 0; /* error */
4789 next = i_peek(input);
4791 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4792 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4793 if (process_bkslash && ch == '\\') {
4795 syntax_error("\\<eof>");
4799 * "The backslash retains its special meaning [in "..."]
4800 * only when followed by one of the following characters:
4801 * $, `, ", \, or <newline>. A double quote may be quoted
4802 * within double quotes by preceding it with a backslash."
4803 * NB: in (unquoted) heredoc, above does not apply to ",
4804 * therefore we check for it by "next == dquote_end" cond.
4806 if (next == dquote_end || strchr("$`\\\n", next)) {
4807 ch = i_getch(input); /* eat next */
4809 goto again; /* skip \<newline> */
4810 } /* else: ch remains == '\\', and we double it below: */
4811 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4812 nommu_addchr(as_string, ch);
4816 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4817 debug_printf_parse("encode_string return 0: "
4818 "parse_dollar returned 0 (error)\n");
4823 #if ENABLE_HUSH_TICK
4825 //unsigned pos = dest->length;
4826 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4827 o_addchr(dest, 0x80 | '`');
4828 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4829 return 0; /* error */
4830 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4831 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4835 o_addQchr(dest, ch);
4841 * Scan input until EOF or end_trigger char.
4842 * Return a list of pipes to execute, or NULL on EOF
4843 * or if end_trigger character is met.
4844 * On syntax error, exit if shell is not interactive,
4845 * reset parsing machinery and start parsing anew,
4846 * or return ERR_PTR.
4848 static struct pipe *parse_stream(char **pstring,
4849 struct in_str *input,
4852 struct parse_context ctx;
4853 o_string dest = NULL_O_STRING;
4856 /* Single-quote triggers a bypass of the main loop until its mate is
4857 * found. When recursing, quote state is passed in via dest->o_expflags.
4859 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4860 end_trigger ? end_trigger : 'X');
4863 /* If very first arg is "" or '', dest.data may end up NULL.
4864 * Preventing this: */
4865 o_addchr(&dest, '\0');
4868 /* We used to separate words on $IFS here. This was wrong.
4869 * $IFS is used only for word splitting when $var is expanded,
4870 * here we should use blank chars as separators, not $IFS
4873 if (MAYBE_ASSIGNMENT != 0)
4874 dest.o_assignment = MAYBE_ASSIGNMENT;
4875 initialize_context(&ctx);
4878 const char *is_blank;
4879 const char *is_special;
4883 redir_type redir_style;
4885 ch = i_getch(input);
4886 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4887 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4892 syntax_error_unterm_str("here document");
4895 if (end_trigger == ')') {
4896 syntax_error_unterm_ch('(');
4899 if (end_trigger == '}') {
4900 syntax_error_unterm_ch('{');
4904 if (done_word(&dest, &ctx)) {
4908 done_pipe(&ctx, PIPE_SEQ);
4910 /* If we got nothing... */
4911 /* (this makes bare "&" cmd a no-op.
4912 * bash says: "syntax error near unexpected token '&'") */
4913 if (pi->num_cmds == 0
4914 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4920 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4922 *pstring = ctx.as_string.data;
4924 o_free_unsafe(&ctx.as_string);
4927 debug_printf_parse("parse_stream return %p\n", pi);
4930 nommu_addchr(&ctx.as_string, ch);
4934 next = i_peek(input);
4936 is_special = "{}<>;&|()#'" /* special outside of "str" */
4937 "\\$\"" IF_HUSH_TICK("`") /* always special */
4938 SPECIAL_VAR_SYMBOL_STR;
4939 /* Are { and } special here? */
4940 if (ctx.command->argv /* word [word]{... - non-special */
4941 || dest.length /* word{... - non-special */
4942 || dest.has_quoted_part /* ""{... - non-special */
4943 || (next != ';' /* }; - special */
4944 && next != ')' /* }) - special */
4945 && next != '(' /* {( - special */
4946 && next != '&' /* }& and }&& ... - special */
4947 && next != '|' /* }|| ... - special */
4948 && !strchr(defifs, next) /* {word - non-special */
4951 /* They are not special, skip "{}" */
4954 is_special = strchr(is_special, ch);
4955 is_blank = strchr(defifs, ch);
4957 if (!is_special && !is_blank) { /* ordinary char */
4959 o_addQchr(&dest, ch);
4960 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4961 || dest.o_assignment == WORD_IS_KEYWORD)
4963 && is_well_formed_var_name(dest.data, '=')
4965 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4966 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4972 if (done_word(&dest, &ctx)) {
4976 /* Is this a case when newline is simply ignored?
4978 * "cmd | <newline> cmd ..."
4979 * "case ... in <newline> word) ..."
4981 if (IS_NULL_CMD(ctx.command)
4982 && dest.length == 0 && !dest.has_quoted_part
4984 /* This newline can be ignored. But...
4985 * Without check #1, interactive shell
4986 * ignores even bare <newline>,
4987 * and shows the continuation prompt:
4988 * ps1_prompt$ <enter>
4989 * ps2> _ <=== wrong, should be ps1
4990 * Without check #2, "cmd & <newline>"
4991 * is similarly mistreated.
4992 * (BTW, this makes "cmd & cmd"
4993 * and "cmd && cmd" non-orthogonal.
4994 * Really, ask yourself, why
4995 * "cmd && <newline>" doesn't start
4996 * cmd but waits for more input?
4997 * The only reason is that it might be
4998 * a "cmd1 && <nl> cmd2 &" construct,
4999 * cmd1 may need to run in BG).
5001 struct pipe *pi = ctx.list_head;
5002 if (pi->num_cmds != 0 /* check #1 */
5003 && pi->followup != PIPE_BG /* check #2 */
5008 /* Treat newline as a command separator. */
5009 done_pipe(&ctx, PIPE_SEQ);
5010 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5012 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5017 dest.o_assignment = MAYBE_ASSIGNMENT;
5018 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5020 /* note: if (is_blank) continue;
5021 * will still trigger for us */
5025 /* "cmd}" or "cmd }..." without semicolon or &:
5026 * } is an ordinary char in this case, even inside { cmd; }
5027 * Pathological example: { ""}; } should exec "}" cmd
5030 if (dest.length != 0 /* word} */
5031 || dest.has_quoted_part /* ""} */
5035 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5036 /* Generally, there should be semicolon: "cmd; }"
5037 * However, bash allows to omit it if "cmd" is
5038 * a group. Examples:
5041 * { echo 0 >&2 | { echo 1; } }
5042 * { while false; do :; done }
5043 * { case a in b) ;; esac }
5045 if (ctx.command->group)
5049 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5050 /* Can't be an end of {cmd}, skip the check */
5051 goto skip_end_trigger;
5052 /* else: } does terminate a group */
5055 if (end_trigger && end_trigger == ch
5056 && (ch != ';' || heredoc_cnt == 0)
5057 #if ENABLE_HUSH_CASE
5059 || ctx.ctx_res_w != RES_MATCH
5060 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5065 /* This is technically valid:
5066 * { cat <<HERE; }; echo Ok
5070 * but we don't support this.
5071 * We require heredoc to be in enclosing {}/(),
5074 syntax_error_unterm_str("here document");
5077 if (done_word(&dest, &ctx)) {
5080 done_pipe(&ctx, PIPE_SEQ);
5081 dest.o_assignment = MAYBE_ASSIGNMENT;
5082 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5083 /* Do we sit outside of any if's, loops or case's? */
5085 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5089 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5091 *pstring = ctx.as_string.data;
5093 o_free_unsafe(&ctx.as_string);
5095 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5096 /* Example: bare "{ }", "()" */
5097 G.last_exitcode = 2; /* bash compat */
5098 syntax_error_unexpected_ch(ch);
5101 debug_printf_parse("parse_stream return %p: "
5102 "end_trigger char found\n",
5105 return ctx.list_head;
5112 /* Catch <, > before deciding whether this word is
5113 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5116 redir_fd = redirect_opt_num(&dest);
5117 if (done_word(&dest, &ctx)) {
5120 redir_style = REDIRECT_OVERWRITE;
5122 redir_style = REDIRECT_APPEND;
5123 ch = i_getch(input);
5124 nommu_addchr(&ctx.as_string, ch);
5127 else if (next == '(') {
5128 syntax_error(">(process) not supported");
5132 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5134 continue; /* back to top of while (1) */
5136 redir_fd = redirect_opt_num(&dest);
5137 if (done_word(&dest, &ctx)) {
5140 redir_style = REDIRECT_INPUT;
5142 redir_style = REDIRECT_HEREDOC;
5144 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5145 ch = i_getch(input);
5146 nommu_addchr(&ctx.as_string, ch);
5147 } else if (next == '>') {
5148 redir_style = REDIRECT_IO;
5149 ch = i_getch(input);
5150 nommu_addchr(&ctx.as_string, ch);
5153 else if (next == '(') {
5154 syntax_error("<(process) not supported");
5158 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5160 continue; /* back to top of while (1) */
5162 if (dest.length == 0 && !dest.has_quoted_part) {
5163 /* skip "#comment" */
5164 /* note: we do not add it to &ctx.as_string */
5166 * comment inside $() goes to the next \n, even inside quoted string (!):
5167 * cmd "$(cmd2 #comment)" - syntax error
5168 * cmd "`cmd2 #comment`" - ok
5169 * We accept both (comment ends where command subst ends, in both cases).
5174 nommu_addchr(&ctx.as_string, '\n');
5177 ch = i_getch(input);
5181 continue; /* back to top of while (1) */
5186 /* It's "\<newline>" */
5188 /* Remove trailing '\' from ctx.as_string */
5189 ctx.as_string.data[--ctx.as_string.length] = '\0';
5191 ch = i_getch(input); /* eat it */
5192 continue; /* back to top of while (1) */
5197 if (dest.o_assignment == MAYBE_ASSIGNMENT
5198 /* check that we are not in word in "a=1 2>word b=1": */
5199 && !ctx.pending_redirect
5201 /* ch is a special char and thus this word
5202 * cannot be an assignment */
5203 dest.o_assignment = NOT_ASSIGNMENT;
5204 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5207 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5210 case SPECIAL_VAR_SYMBOL:
5211 /* Convert raw ^C to corresponding special variable reference */
5212 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5213 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5216 /* non-comment #: "echo a#b" etc */
5217 o_addchr(&dest, ch);
5221 syntax_error("\\<eof>");
5224 ch = i_getch(input);
5225 /* note: ch != '\n' (that case does not reach this place) */
5226 o_addchr(&dest, '\\');
5227 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5228 o_addchr(&dest, ch);
5229 nommu_addchr(&ctx.as_string, ch);
5230 /* Example: echo Hello \2>file
5231 * we need to know that word 2 is quoted */
5232 dest.has_quoted_part = 1;
5235 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5236 debug_printf_parse("parse_stream parse error: "
5237 "parse_dollar returned 0 (error)\n");
5242 dest.has_quoted_part = 1;
5243 if (next == '\'' && !ctx.pending_redirect) {
5244 insert_empty_quoted_str_marker:
5245 nommu_addchr(&ctx.as_string, next);
5246 i_getch(input); /* eat second ' */
5247 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5248 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5251 ch = i_getch(input);
5253 syntax_error_unterm_ch('\'');
5256 nommu_addchr(&ctx.as_string, ch);
5259 if (ch == SPECIAL_VAR_SYMBOL) {
5260 /* Convert raw ^C to corresponding special variable reference */
5261 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5262 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5264 o_addqchr(&dest, ch);
5269 dest.has_quoted_part = 1;
5270 if (next == '"' && !ctx.pending_redirect)
5271 goto insert_empty_quoted_str_marker;
5272 if (dest.o_assignment == NOT_ASSIGNMENT)
5273 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5274 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5276 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5278 #if ENABLE_HUSH_TICK
5280 USE_FOR_NOMMU(unsigned pos;)
5282 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5283 o_addchr(&dest, '`');
5284 USE_FOR_NOMMU(pos = dest.length;)
5285 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5288 o_addstr(&ctx.as_string, dest.data + pos);
5289 o_addchr(&ctx.as_string, '`');
5291 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5292 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5297 #if ENABLE_HUSH_CASE
5300 if (done_word(&dest, &ctx)) {
5303 done_pipe(&ctx, PIPE_SEQ);
5304 #if ENABLE_HUSH_CASE
5305 /* Eat multiple semicolons, detect
5306 * whether it means something special */
5311 ch = i_getch(input);
5312 nommu_addchr(&ctx.as_string, ch);
5313 if (ctx.ctx_res_w == RES_CASE_BODY) {
5314 ctx.ctx_dsemicolon = 1;
5315 ctx.ctx_res_w = RES_MATCH;
5321 /* We just finished a cmd. New one may start
5322 * with an assignment */
5323 dest.o_assignment = MAYBE_ASSIGNMENT;
5324 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5327 if (done_word(&dest, &ctx)) {
5331 ch = i_getch(input);
5332 nommu_addchr(&ctx.as_string, ch);
5333 done_pipe(&ctx, PIPE_AND);
5335 done_pipe(&ctx, PIPE_BG);
5339 if (done_word(&dest, &ctx)) {
5342 #if ENABLE_HUSH_CASE
5343 if (ctx.ctx_res_w == RES_MATCH)
5344 break; /* we are in case's "word | word)" */
5346 if (next == '|') { /* || */
5347 ch = i_getch(input);
5348 nommu_addchr(&ctx.as_string, ch);
5349 done_pipe(&ctx, PIPE_OR);
5351 /* we could pick up a file descriptor choice here
5352 * with redirect_opt_num(), but bash doesn't do it.
5353 * "echo foo 2| cat" yields "foo 2". */
5358 #if ENABLE_HUSH_CASE
5359 /* "case... in [(]word)..." - skip '(' */
5360 if (ctx.ctx_res_w == RES_MATCH
5361 && ctx.command->argv == NULL /* not (word|(... */
5362 && dest.length == 0 /* not word(... */
5363 && dest.has_quoted_part == 0 /* not ""(... */
5369 if (parse_group(&dest, &ctx, input, ch) != 0) {
5374 #if ENABLE_HUSH_CASE
5375 if (ctx.ctx_res_w == RES_MATCH)
5379 /* proper use of this character is caught by end_trigger:
5380 * if we see {, we call parse_group(..., end_trigger='}')
5381 * and it will match } earlier (not here). */
5382 G.last_exitcode = 2;
5383 syntax_error_unexpected_ch(ch);
5387 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5392 G.last_exitcode = 1;
5395 struct parse_context *pctx;
5396 IF_HAS_KEYWORDS(struct parse_context *p2;)
5398 /* Clean up allocated tree.
5399 * Sample for finding leaks on syntax error recovery path.
5400 * Run it from interactive shell, watch pmap `pidof hush`.
5401 * while if false; then false; fi; do break; fi
5402 * Samples to catch leaks at execution:
5403 * while if (true | { true;}); then echo ok; fi; do break; done
5404 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5408 /* Update pipe/command counts,
5409 * otherwise freeing may miss some */
5410 done_pipe(pctx, PIPE_SEQ);
5411 debug_printf_clean("freeing list %p from ctx %p\n",
5412 pctx->list_head, pctx);
5413 debug_print_tree(pctx->list_head, 0);
5414 free_pipe_list(pctx->list_head);
5415 debug_printf_clean("freed list %p\n", pctx->list_head);
5417 o_free_unsafe(&pctx->as_string);
5419 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5423 IF_HAS_KEYWORDS(pctx = p2;)
5424 } while (HAS_KEYWORDS && pctx);
5437 /*** Execution routines ***/
5439 /* Expansion can recurse, need forward decls: */
5440 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5441 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5442 #define expand_string_to_string(str, do_unbackslash) \
5443 expand_string_to_string(str)
5445 static char *expand_string_to_string(const char *str, int do_unbackslash);
5446 #if ENABLE_HUSH_TICK
5447 static int process_command_subs(o_string *dest, const char *s);
5450 /* expand_strvec_to_strvec() takes a list of strings, expands
5451 * all variable references within and returns a pointer to
5452 * a list of expanded strings, possibly with larger number
5453 * of strings. (Think VAR="a b"; echo $VAR).
5454 * This new list is allocated as a single malloc block.
5455 * NULL-terminated list of char* pointers is at the beginning of it,
5456 * followed by strings themselves.
5457 * Caller can deallocate entire list by single free(list). */
5459 /* A horde of its helpers come first: */
5461 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5463 while (--len >= 0) {
5466 #if ENABLE_HUSH_BRACE_EXPANSION
5467 if (c == '{' || c == '}') {
5468 /* { -> \{, } -> \} */
5470 /* And now we want to add { or } and continue:
5473 * luckily, just falling through achieves this.
5479 /* \z -> \\\z; \<eol> -> \\<eol> */
5484 o_addchr(o, *str++);
5490 /* Store given string, finalizing the word and starting new one whenever
5491 * we encounter IFS char(s). This is used for expanding variable values.
5492 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5493 * Return in *ended_with_ifs:
5494 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5496 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5498 int last_is_ifs = 0;
5503 if (!*str) /* EOL - do not finalize word */
5505 word_len = strcspn(str, G.ifs);
5507 /* We have WORD_LEN leading non-IFS chars */
5508 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5509 o_addblock(output, str, word_len);
5511 /* Protect backslashes against globbing up :)
5512 * Example: "v='\*'; echo b$v" prints "b\*"
5513 * (and does not try to glob on "*")
5515 o_addblock_duplicate_backslash(output, str, word_len);
5516 /*/ Why can't we do it easier? */
5517 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5518 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5522 if (!*str) /* EOL - do not finalize word */
5526 /* We know str here points to at least one IFS char */
5528 str += strspn(str, G.ifs); /* skip IFS chars */
5529 if (!*str) /* EOL - do not finalize word */
5532 /* Start new word... but not always! */
5533 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5534 if (output->has_quoted_part
5535 /* Case "v=' a'; echo $v":
5536 * here nothing precedes the space in $v expansion,
5537 * therefore we should not finish the word
5538 * (IOW: if there *is* word to finalize, only then do it):
5540 || (n > 0 && output->data[output->length - 1])
5542 o_addchr(output, '\0');
5543 debug_print_list("expand_on_ifs", output, n);
5544 n = o_save_ptr(output, n);
5549 *ended_with_ifs = last_is_ifs;
5550 debug_print_list("expand_on_ifs[1]", output, n);
5554 /* Helper to expand $((...)) and heredoc body. These act as if
5555 * they are in double quotes, with the exception that they are not :).
5556 * Just the rules are similar: "expand only $var and `cmd`"
5558 * Returns malloced string.
5559 * As an optimization, we return NULL if expansion is not needed.
5561 #if !BASH_PATTERN_SUBST
5562 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5563 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5564 encode_then_expand_string(str)
5566 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5568 #if !BASH_PATTERN_SUBST
5569 enum { do_unbackslash = 1 };
5572 struct in_str input;
5573 o_string dest = NULL_O_STRING;
5575 if (!strchr(str, '$')
5576 && !strchr(str, '\\')
5577 #if ENABLE_HUSH_TICK
5578 && !strchr(str, '`')
5584 /* We need to expand. Example:
5585 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5587 setup_string_in_str(&input, str);
5588 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5589 //TODO: error check (encode_string returns 0 on error)?
5590 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5591 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5592 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5593 o_free_unsafe(&dest);
5597 #if ENABLE_FEATURE_SH_MATH
5598 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5600 arith_state_t math_state;
5604 math_state.lookupvar = get_local_var_value;
5605 math_state.setvar = set_local_var_from_halves;
5606 //math_state.endofname = endofname;
5607 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5608 res = arith(&math_state, exp_str ? exp_str : arg);
5611 *errmsg_p = math_state.errmsg;
5612 if (math_state.errmsg)
5613 msg_and_die_if_script(math_state.errmsg);
5618 #if BASH_PATTERN_SUBST
5619 /* ${var/[/]pattern[/repl]} helpers */
5620 static char *strstr_pattern(char *val, const char *pattern, int *size)
5623 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5624 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5631 /* Optimization: if "*pat" did not match the start of "string",
5632 * we know that "tring", "ring" etc will not match too:
5634 if (pattern[0] == '*')
5639 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5641 char *result = NULL;
5642 unsigned res_len = 0;
5643 unsigned repl_len = strlen(repl);
5647 char *s = strstr_pattern(val, pattern, &size);
5651 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5652 strcpy(mempcpy(result + res_len, val, s - val), repl);
5653 res_len += (s - val) + repl_len;
5654 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5660 if (*val && result) {
5661 result = xrealloc(result, res_len + strlen(val) + 1);
5662 strcpy(result + res_len, val);
5663 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5665 debug_printf_varexp("result:'%s'\n", result);
5668 #endif /* BASH_PATTERN_SUBST */
5671 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5673 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5675 const char *val = NULL;
5676 char *to_be_freed = NULL;
5681 char exp_save = exp_save; /* for compiler */
5682 char *exp_saveptr; /* points to expansion operator */
5683 char *exp_word = exp_word; /* for compiler */
5686 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5688 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5690 first_char = arg[0] = arg0 & 0x7f;
5693 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5694 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5695 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5696 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5698 /* It must be length operator: ${#var} */
5702 /* Maybe handle parameter expansion */
5703 if (exp_saveptr /* if 2nd char is one of expansion operators */
5704 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5706 /* ${?:0}, ${#[:]%0} etc */
5707 exp_saveptr = var + 1;
5709 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5710 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5712 exp_op = exp_save = *exp_saveptr;
5714 exp_word = exp_saveptr + 1;
5715 if (exp_op == ':') {
5716 exp_op = *exp_word++;
5717 //TODO: try ${var:} and ${var:bogus} in non-bash config
5719 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5721 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5726 *exp_saveptr = '\0';
5727 } /* else: it's not an expansion op, but bare ${var} */
5730 /* Look up the variable in question */
5731 if (isdigit(var[0])) {
5732 /* parse_dollar should have vetted var for us */
5733 int n = xatoi_positive(var);
5734 if (n < G.global_argc)
5735 val = G.global_argv[n];
5736 /* else val remains NULL: $N with too big N */
5740 val = utoa(G.root_pid);
5742 case '!': /* bg pid */
5743 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5745 case '?': /* exitcode */
5746 val = utoa(G.last_exitcode);
5748 case '#': /* argc */
5749 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5752 val = get_local_var_value(var);
5756 /* Handle any expansions */
5757 if (exp_op == 'L') {
5758 reinit_unicode_for_hush();
5759 debug_printf_expand("expand: length(%s)=", val);
5760 val = utoa(val ? unicode_strlen(val) : 0);
5761 debug_printf_expand("%s\n", val);
5762 } else if (exp_op) {
5763 if (exp_op == '%' || exp_op == '#') {
5764 /* Standard-mandated substring removal ops:
5765 * ${parameter%word} - remove smallest suffix pattern
5766 * ${parameter%%word} - remove largest suffix pattern
5767 * ${parameter#word} - remove smallest prefix pattern
5768 * ${parameter##word} - remove largest prefix pattern
5770 * Word is expanded to produce a glob pattern.
5771 * Then var's value is matched to it and matching part removed.
5773 if (val && val[0]) {
5777 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5778 if (exp_op == *exp_word) /* ## or %% */
5780 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5782 exp_word = exp_exp_word;
5783 /* HACK ALERT. We depend here on the fact that
5784 * G.global_argv and results of utoa and get_local_var_value
5785 * are actually in writable memory:
5786 * scan_and_match momentarily stores NULs there. */
5788 loc = scan_and_match(t, exp_word, scan_flags);
5789 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5790 // exp_op, t, exp_word, loc);
5792 if (loc) { /* match was found */
5793 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5794 val = loc; /* take right part */
5796 val = to_be_freed = xstrndup(val, loc - val); /* left */
5800 #if BASH_PATTERN_SUBST
5801 else if (exp_op == '/' || exp_op == '\\') {
5802 /* It's ${var/[/]pattern[/repl]} thing.
5803 * Note that in encoded form it has TWO parts:
5804 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5805 * and if // is used, it is encoded as \:
5806 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5808 /* Empty variable always gives nothing: */
5809 // "v=''; echo ${v/*/w}" prints "", not "w"
5810 if (val && val[0]) {
5811 /* pattern uses non-standard expansion.
5812 * repl should be unbackslashed and globbed
5813 * by the usual expansion rules:
5815 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5816 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5817 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5818 * v='a bz'; echo ${v/a*z/\z} prints "z"
5819 * (note that a*z _pattern_ is never globbed!)
5821 char *pattern, *repl, *t;
5822 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5824 pattern = xstrdup(exp_word);
5825 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5826 *p++ = SPECIAL_VAR_SYMBOL;
5828 p = strchr(p, SPECIAL_VAR_SYMBOL);
5830 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5831 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5832 /* HACK ALERT. We depend here on the fact that
5833 * G.global_argv and results of utoa and get_local_var_value
5834 * are actually in writable memory:
5835 * replace_pattern momentarily stores NULs there. */
5837 to_be_freed = replace_pattern(t,
5839 (repl ? repl : exp_word),
5841 if (to_be_freed) /* at least one replace happened */
5847 #endif /* BASH_PATTERN_SUBST */
5848 else if (exp_op == ':') {
5849 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5850 /* It's ${var:N[:M]} bashism.
5851 * Note that in encoded form it has TWO parts:
5852 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5857 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5860 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5861 *p++ = SPECIAL_VAR_SYMBOL;
5863 p = strchr(p, SPECIAL_VAR_SYMBOL);
5865 len = expand_and_evaluate_arith(exp_word, &errmsg);
5868 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5870 /* negative beg counts from the end */
5871 beg = (arith_t)strlen(val) + beg;
5872 if (beg < 0) /* ${v: -999999} is "" */
5875 debug_printf_varexp("from val:'%s'\n", val);
5877 /* in bash, len=-n means strlen()-n */
5878 len = (arith_t)strlen(val) - beg + len;
5879 if (len < 0) /* bash compat */
5880 msg_and_die_if_script("%s: substring expression < 0", var);
5882 if (len <= 0 || !val || beg >= strlen(val)) {
5886 /* Paranoia. What if user entered 9999999999999
5887 * which fits in arith_t but not int? */
5890 val = to_be_freed = xstrndup(val + beg, len);
5892 debug_printf_varexp("val:'%s'\n", val);
5893 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5894 msg_and_die_if_script("malformed ${%s:...}", var);
5897 } else { /* one of "-=+?" */
5898 /* Standard-mandated substitution ops:
5899 * ${var?word} - indicate error if unset
5900 * If var is unset, word (or a message indicating it is unset
5901 * if word is null) is written to standard error
5902 * and the shell exits with a non-zero exit status.
5903 * Otherwise, the value of var is substituted.
5904 * ${var-word} - use default value
5905 * If var is unset, word is substituted.
5906 * ${var=word} - assign and use default value
5907 * If var is unset, word is assigned to var.
5908 * In all cases, final value of var is substituted.
5909 * ${var+word} - use alternative value
5910 * If var is unset, null is substituted.
5911 * Otherwise, word is substituted.
5913 * Word is subjected to tilde expansion, parameter expansion,
5914 * command substitution, and arithmetic expansion.
5915 * If word is not needed, it is not expanded.
5917 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5918 * but also treat null var as if it is unset.
5920 int use_word = (!val || ((exp_save == ':') && !val[0]));
5922 use_word = !use_word;
5923 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5924 (exp_save == ':') ? "true" : "false", use_word);
5926 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5928 exp_word = to_be_freed;
5929 if (exp_op == '?') {
5930 /* mimic bash message */
5931 msg_and_die_if_script("%s: %s",
5935 : "parameter null or not set"
5936 /* ash has more specific messages, a-la: */
5937 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
5939 //TODO: how interactive bash aborts expansion mid-command?
5944 if (exp_op == '=') {
5945 /* ${var=[word]} or ${var:=[word]} */
5946 if (isdigit(var[0]) || var[0] == '#') {
5947 /* mimic bash message */
5948 msg_and_die_if_script("$%s: cannot assign in this way", var);
5951 char *new_var = xasprintf("%s=%s", var, val);
5952 set_local_var(new_var, /*flag:*/ 0);
5956 } /* one of "-=+?" */
5958 *exp_saveptr = exp_save;
5964 *to_be_freed_pp = to_be_freed;
5968 /* Expand all variable references in given string, adding words to list[]
5969 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5970 * to be filled). This routine is extremely tricky: has to deal with
5971 * variables/parameters with whitespace, $* and $@, and constructs like
5972 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5973 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5975 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5976 * expansion of right-hand side of assignment == 1-element expand.
5978 char cant_be_null = 0; /* only bit 0x80 matters */
5979 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5982 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5983 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5984 debug_print_list("expand_vars_to_list", output, n);
5985 n = o_save_ptr(output, n);
5986 debug_print_list("expand_vars_to_list[0]", output, n);
5988 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5990 char *to_be_freed = NULL;
5991 const char *val = NULL;
5992 #if ENABLE_HUSH_TICK
5993 o_string subst_result = NULL_O_STRING;
5995 #if ENABLE_FEATURE_SH_MATH
5996 char arith_buf[sizeof(arith_t)*3 + 2];
6000 o_addchr(output, '\0');
6001 n = o_save_ptr(output, n);
6005 o_addblock(output, arg, p - arg);
6006 debug_print_list("expand_vars_to_list[1]", output, n);
6008 p = strchr(p, SPECIAL_VAR_SYMBOL);
6010 /* Fetch special var name (if it is indeed one of them)
6011 * and quote bit, force the bit on if singleword expansion -
6012 * important for not getting v=$@ expand to many words. */
6013 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6015 /* Is this variable quoted and thus expansion can't be null?
6016 * "$@" is special. Even if quoted, it can still
6017 * expand to nothing (not even an empty string),
6018 * thus it is excluded. */
6019 if ((first_ch & 0x7f) != '@')
6020 cant_be_null |= first_ch;
6022 switch (first_ch & 0x7f) {
6023 /* Highest bit in first_ch indicates that var is double-quoted */
6027 if (!G.global_argv[1])
6030 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6031 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6032 while (G.global_argv[i]) {
6033 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
6034 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6035 if (G.global_argv[i++][0] && G.global_argv[i]) {
6036 /* this argv[] is not empty and not last:
6037 * put terminating NUL, start new word */
6038 o_addchr(output, '\0');
6039 debug_print_list("expand_vars_to_list[2]", output, n);
6040 n = o_save_ptr(output, n);
6041 debug_print_list("expand_vars_to_list[3]", output, n);
6045 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6046 * and in this case should treat it like '$*' - see 'else...' below */
6047 if (first_ch == ('@'|0x80) /* quoted $@ */
6048 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6051 o_addQstr(output, G.global_argv[i]);
6052 if (++i >= G.global_argc)
6054 o_addchr(output, '\0');
6055 debug_print_list("expand_vars_to_list[4]", output, n);
6056 n = o_save_ptr(output, n);
6058 } else { /* quoted $* (or v="$@" case): add as one word */
6060 o_addQstr(output, G.global_argv[i]);
6061 if (!G.global_argv[++i])
6064 o_addchr(output, G.ifs[0]);
6066 output->has_quoted_part = 1;
6070 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6071 /* "Empty variable", used to make "" etc to not disappear */
6072 output->has_quoted_part = 1;
6074 cant_be_null = 0x80;
6076 case SPECIAL_VAR_QUOTED_SVS:
6077 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6079 val = SPECIAL_VAR_SYMBOL_STR;
6081 #if ENABLE_HUSH_TICK
6082 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6083 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6085 /* Can't just stuff it into output o_string,
6086 * expanded result may need to be globbed
6088 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6089 G.last_exitcode = process_command_subs(&subst_result, arg);
6090 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6091 val = subst_result.data;
6094 #if ENABLE_FEATURE_SH_MATH
6095 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6098 arg++; /* skip '+' */
6099 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6100 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6101 res = expand_and_evaluate_arith(arg, NULL);
6102 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6103 sprintf(arith_buf, ARITH_FMT, res);
6109 val = expand_one_var(&to_be_freed, arg, &p);
6110 IF_HUSH_TICK(store_val:)
6111 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6112 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6113 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6114 if (val && val[0]) {
6115 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6118 } else { /* quoted $VAR, val will be appended below */
6119 output->has_quoted_part = 1;
6120 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6121 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6124 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6126 if (val && val[0]) {
6127 o_addQstr(output, val);
6131 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6132 * Do the check to avoid writing to a const string. */
6133 if (*p != SPECIAL_VAR_SYMBOL)
6134 *p = SPECIAL_VAR_SYMBOL;
6136 #if ENABLE_HUSH_TICK
6137 o_free(&subst_result);
6140 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6144 o_addchr(output, '\0');
6145 n = o_save_ptr(output, n);
6147 debug_print_list("expand_vars_to_list[a]", output, n);
6148 /* this part is literal, and it was already pre-quoted
6149 * if needed (much earlier), do not use o_addQstr here! */
6150 o_addstr_with_NUL(output, arg);
6151 debug_print_list("expand_vars_to_list[b]", output, n);
6152 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6153 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6156 /* allow to reuse list[n] later without re-growth */
6157 output->has_empty_slot = 1;
6159 o_addchr(output, '\0');
6165 static char **expand_variables(char **argv, unsigned expflags)
6169 o_string output = NULL_O_STRING;
6171 output.o_expflags = expflags;
6175 n = expand_vars_to_list(&output, n, *argv);
6178 debug_print_list("expand_variables", &output, n);
6180 /* output.data (malloced in one block) gets returned in "list" */
6181 list = o_finalize_list(&output, n);
6182 debug_print_strings("expand_variables[1]", list);
6186 static char **expand_strvec_to_strvec(char **argv)
6188 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6192 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6194 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6198 /* Used for expansion of right hand of assignments,
6199 * $((...)), heredocs, variable espansion parts.
6201 * NB: should NOT do globbing!
6202 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6204 static char *expand_string_to_string(const char *str, int do_unbackslash)
6206 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6207 const int do_unbackslash = 1;
6209 char *argv[2], **list;
6211 debug_printf_expand("string_to_string<='%s'\n", str);
6212 /* This is generally an optimization, but it also
6213 * handles "", which otherwise trips over !list[0] check below.
6214 * (is this ever happens that we actually get str="" here?)
6216 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6217 //TODO: Can use on strings with \ too, just unbackslash() them?
6218 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6219 return xstrdup(str);
6222 argv[0] = (char*)str;
6224 list = expand_variables(argv, do_unbackslash
6225 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6226 : EXP_FLAG_SINGLEWORD
6229 if (!list[0] || list[1])
6230 bb_error_msg_and_die("BUG in varexp2");
6231 /* actually, just move string 2*sizeof(char*) bytes back */
6232 overlapping_strcpy((char*)list, list[0]);
6234 unbackslash((char*)list);
6235 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6239 #if ENABLE_HUSH_CASE
6240 static char* expand_strvec_to_string(char **argv)
6244 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6245 /* Convert all NULs to spaces */
6250 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6251 bb_error_msg_and_die("BUG in varexp3");
6252 /* bash uses ' ' regardless of $IFS contents */
6257 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6258 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6263 static char **expand_assignments(char **argv, int count)
6268 G.expanded_assignments = p = NULL;
6269 /* Expand assignments into one string each */
6270 for (i = 0; i < count; i++) {
6271 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6273 G.expanded_assignments = NULL;
6278 static void switch_off_special_sigs(unsigned mask)
6281 while ((mask >>= 1) != 0) {
6285 #if ENABLE_HUSH_TRAP
6287 if (G_traps[sig] && !G_traps[sig][0])
6288 /* trap is '', has to remain SIG_IGN */
6291 G_traps[sig] = NULL;
6294 /* We are here only if no trap or trap was not '' */
6295 install_sighandler(sig, SIG_DFL);
6301 void re_execute_shell(char ***to_free, const char *s,
6302 char *g_argv0, char **g_argv,
6303 char **builtin_argv) NORETURN;
6305 static void reset_traps_to_defaults(void)
6307 /* This function is always called in a child shell
6308 * after fork (not vfork, NOMMU doesn't use this function).
6310 IF_HUSH_TRAP(unsigned sig;)
6313 /* Child shells are not interactive.
6314 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6315 * Testcase: (while :; do :; done) + ^Z should background.
6316 * Same goes for SIGTERM, SIGHUP, SIGINT.
6318 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6319 if (!G_traps && !mask)
6320 return; /* already no traps and no special sigs */
6322 /* Switch off special sigs */
6323 switch_off_special_sigs(mask);
6324 # if ENABLE_HUSH_JOB
6325 G_fatal_sig_mask = 0;
6327 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6328 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6329 * remain set in G.special_sig_mask */
6331 # if ENABLE_HUSH_TRAP
6335 /* Reset all sigs to default except ones with empty traps */
6336 for (sig = 0; sig < NSIG; sig++) {
6338 continue; /* no trap: nothing to do */
6339 if (!G_traps[sig][0])
6340 continue; /* empty trap: has to remain SIG_IGN */
6341 /* sig has non-empty trap, reset it: */
6343 G_traps[sig] = NULL;
6344 /* There is no signal for trap 0 (EXIT) */
6347 install_sighandler(sig, pick_sighandler(sig));
6354 static void re_execute_shell(char ***to_free, const char *s,
6355 char *g_argv0, char **g_argv,
6356 char **builtin_argv) NORETURN;
6357 static void re_execute_shell(char ***to_free, const char *s,
6358 char *g_argv0, char **g_argv,
6359 char **builtin_argv)
6361 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6362 /* delims + 2 * (number of bytes in printed hex numbers) */
6363 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6364 char *heredoc_argv[4];
6365 struct variable *cur;
6366 # if ENABLE_HUSH_FUNCTIONS
6367 struct function *funcp;
6371 unsigned long long empty_trap_mask;
6373 if (!g_argv0) { /* heredoc */
6374 argv = heredoc_argv;
6375 argv[0] = (char *) G.argv0_for_re_execing;
6376 argv[1] = (char *) "-<";
6377 argv[2] = (char *) s;
6379 pp = &argv[3]; /* used as pointer to empty environment */
6385 if (pp) while (*pp++)
6388 empty_trap_mask = 0;
6391 for (sig = 1; sig < NSIG; sig++) {
6392 if (G_traps[sig] && !G_traps[sig][0])
6393 empty_trap_mask |= 1LL << sig;
6397 sprintf(param_buf, NOMMU_HACK_FMT
6398 , (unsigned) G.root_pid
6399 , (unsigned) G.root_ppid
6400 , (unsigned) G.last_bg_pid
6401 , (unsigned) G.last_exitcode
6404 IF_HUSH_LOOPS(, G.depth_of_loop)
6406 # undef NOMMU_HACK_FMT
6407 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6408 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6411 for (cur = G.top_var; cur; cur = cur->next) {
6412 if (!cur->flg_export || cur->flg_read_only)
6415 # if ENABLE_HUSH_FUNCTIONS
6416 for (funcp = G.top_func; funcp; funcp = funcp->next)
6422 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6423 *pp++ = (char *) G.argv0_for_re_execing;
6425 for (cur = G.top_var; cur; cur = cur->next) {
6426 if (strcmp(cur->varstr, hush_version_str) == 0)
6428 if (cur->flg_read_only) {
6429 *pp++ = (char *) "-R";
6430 *pp++ = cur->varstr;
6431 } else if (!cur->flg_export) {
6432 *pp++ = (char *) "-V";
6433 *pp++ = cur->varstr;
6436 # if ENABLE_HUSH_FUNCTIONS
6437 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6438 *pp++ = (char *) "-F";
6439 *pp++ = funcp->name;
6440 *pp++ = funcp->body_as_string;
6443 /* We can pass activated traps here. Say, -Tnn:trap_string
6445 * However, POSIX says that subshells reset signals with traps
6447 * I tested bash-3.2 and it not only does that with true subshells
6448 * of the form ( list ), but with any forked children shells.
6449 * I set trap "echo W" WINCH; and then tried:
6451 * { echo 1; sleep 20; echo 2; } &
6452 * while true; do echo 1; sleep 20; echo 2; break; done &
6453 * true | { echo 1; sleep 20; echo 2; } | cat
6455 * In all these cases sending SIGWINCH to the child shell
6456 * did not run the trap. If I add trap "echo V" WINCH;
6457 * _inside_ group (just before echo 1), it works.
6459 * I conclude it means we don't need to pass active traps here.
6461 *pp++ = (char *) "-c";
6464 while (*++builtin_argv)
6465 *pp++ = *builtin_argv;
6466 *pp++ = (char *) "";
6471 /* *pp = NULL; - is already there */
6475 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6476 /* Don't propagate SIG_IGN to the child */
6477 if (SPECIAL_JOBSTOP_SIGS != 0)
6478 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6479 execve(bb_busybox_exec_path, argv, pp);
6480 /* Fallback. Useful for init=/bin/hush usage etc */
6481 if (argv[0][0] == '/')
6482 execve(argv[0], argv, pp);
6483 xfunc_error_retval = 127;
6484 bb_error_msg_and_die("can't re-execute the shell");
6486 #endif /* !BB_MMU */
6489 static int run_and_free_list(struct pipe *pi);
6491 /* Executing from string: eval, sh -c '...'
6492 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6493 * end_trigger controls how often we stop parsing
6494 * NUL: parse all, execute, return
6495 * ';': parse till ';' or newline, execute, repeat till EOF
6497 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6499 /* Why we need empty flag?
6500 * An obscure corner case "false; ``; echo $?":
6501 * empty command in `` should still set $? to 0.
6502 * But we can't just set $? to 0 at the start,
6503 * this breaks "false; echo `echo $?`" case.
6507 struct pipe *pipe_list;
6509 #if ENABLE_HUSH_INTERACTIVE
6510 if (end_trigger == ';')
6511 inp->promptmode = 0; /* PS1 */
6513 pipe_list = parse_stream(NULL, inp, end_trigger);
6514 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6515 /* If we are in "big" script
6516 * (not in `cmd` or something similar)...
6518 if (pipe_list == ERR_PTR && end_trigger == ';') {
6519 /* Discard cached input (rest of line) */
6520 int ch = inp->last_char;
6521 while (ch != EOF && ch != '\n') {
6522 //bb_error_msg("Discarded:'%c'", ch);
6527 /* This stream isn't empty */
6531 if (!pipe_list && empty)
6532 G.last_exitcode = 0;
6535 debug_print_tree(pipe_list, 0);
6536 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6537 run_and_free_list(pipe_list);
6539 if (G_flag_return_in_progress == 1)
6544 static void parse_and_run_string(const char *s)
6546 struct in_str input;
6547 setup_string_in_str(&input, s);
6548 parse_and_run_stream(&input, '\0');
6551 static void parse_and_run_file(FILE *f)
6553 struct in_str input;
6556 setup_file_in_str(&input, f);
6559 parse_and_run_stream(&input, ';');
6563 #if ENABLE_HUSH_TICK
6564 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6569 char **to_free = NULL;
6573 pid = BB_MMU ? xfork() : xvfork();
6574 if (pid == 0) { /* child */
6575 disable_restore_tty_pgrp_on_exit();
6576 /* Process substitution is not considered to be usual
6577 * 'command execution'.
6578 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6585 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6586 close(channel[0]); /* NB: close _first_, then move fd! */
6587 xmove_fd(channel[1], 1);
6588 /* Prevent it from trying to handle ctrl-z etc */
6589 IF_HUSH_JOB(G.run_list_level = 1;)
6590 # if ENABLE_HUSH_TRAP
6591 /* Awful hack for `trap` or $(trap).
6593 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6594 * contains an example where "trap" is executed in a subshell:
6596 * save_traps=$(trap)
6598 * eval "$save_traps"
6600 * Standard does not say that "trap" in subshell shall print
6601 * parent shell's traps. It only says that its output
6602 * must have suitable form, but then, in the above example
6603 * (which is not supposed to be normative), it implies that.
6605 * bash (and probably other shell) does implement it
6606 * (traps are reset to defaults, but "trap" still shows them),
6607 * but as a result, "trap" logic is hopelessly messed up:
6610 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6611 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6612 * # true | trap <--- trap is in subshell - no output (ditto)
6613 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6614 * trap -- 'echo Ho' SIGWINCH
6615 * # echo `(trap)` <--- in subshell in subshell - output
6616 * trap -- 'echo Ho' SIGWINCH
6617 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6618 * trap -- 'echo Ho' SIGWINCH
6620 * The rules when to forget and when to not forget traps
6621 * get really complex and nonsensical.
6623 * Our solution: ONLY bare $(trap) or `trap` is special.
6625 s = skip_whitespace(s);
6626 if (is_prefixed_with(s, "trap")
6627 && skip_whitespace(s + 4)[0] == '\0'
6629 static const char *const argv[] = { NULL, NULL };
6630 builtin_trap((char**)argv);
6631 fflush_all(); /* important */
6636 reset_traps_to_defaults();
6637 parse_and_run_string(s);
6638 _exit(G.last_exitcode);
6640 /* We re-execute after vfork on NOMMU. This makes this script safe:
6641 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6642 * huge=`cat BIG` # was blocking here forever
6645 re_execute_shell(&to_free,
6655 # if ENABLE_HUSH_FAST
6657 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6658 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6659 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6661 enable_restore_tty_pgrp_on_exit();
6666 return remember_FILE(xfdopen_for_read(channel[0]));
6669 /* Return code is exit status of the process that is run. */
6670 static int process_command_subs(o_string *dest, const char *s)
6673 struct in_str pipe_str;
6675 int status, ch, eol_cnt;
6677 fp = generate_stream_from_string(s, &pid);
6679 /* Now send results of command back into original context */
6680 setup_file_in_str(&pipe_str, fp);
6682 while ((ch = i_getch(&pipe_str)) != EOF) {
6688 o_addchr(dest, '\n');
6691 o_addQchr(dest, ch);
6694 debug_printf("done reading from `cmd` pipe, closing it\n");
6695 fclose_and_forget(fp);
6696 /* We need to extract exitcode. Test case
6697 * "true; echo `sleep 1; false` $?"
6699 safe_waitpid(pid, &status, 0);
6700 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6701 return WEXITSTATUS(status);
6703 #endif /* ENABLE_HUSH_TICK */
6706 static void setup_heredoc(struct redir_struct *redir)
6708 struct fd_pair pair;
6711 /* the _body_ of heredoc (misleading field name) */
6712 const char *heredoc = redir->rd_filename;
6719 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6720 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6724 len = strlen(heredoc);
6726 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6728 xmove_fd(pair.rd, redir->rd_fd);
6730 /* Try writing without forking. Newer kernels have
6731 * dynamically growing pipes. Must use non-blocking write! */
6734 written = write(pair.wr, heredoc, len);
6745 ndelay_off(pair.wr);
6747 /* Okay, pipe buffer was not big enough */
6748 /* Note: we must not create a stray child (bastard? :)
6749 * for the unsuspecting parent process. Child creates a grandchild
6750 * and exits before parent execs the process which consumes heredoc
6751 * (that exec happens after we return from this function) */
6758 disable_restore_tty_pgrp_on_exit();
6759 pid = BB_MMU ? xfork() : xvfork();
6763 close(redir->rd_fd); /* read side of the pipe */
6765 full_write(pair.wr, heredoc, len); /* may loop or block */
6768 /* Delegate blocking writes to another process */
6769 xmove_fd(pair.wr, STDOUT_FILENO);
6770 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6774 #if ENABLE_HUSH_FAST
6776 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6778 enable_restore_tty_pgrp_on_exit();
6784 wait(NULL); /* wait till child has died */
6790 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6791 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6794 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6796 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6797 sq[i].orig_fd = orig;
6798 sq[i].moved_to = moved;
6799 sq[i+1].orig_fd = -1; /* end marker */
6803 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6809 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6810 /* If we collide with an already moved fd... */
6811 if (fd == sq[i].moved_to) {
6812 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6813 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6814 if (sq[i].moved_to < 0) /* what? */
6818 if (fd == sq[i].orig_fd) {
6819 /* Example: echo Hello >/dev/null 1>&2 */
6820 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6825 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6826 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6827 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6828 if (moved_to < 0 && errno != EBADF)
6830 return append_squirrel(sq, i, fd, moved_to);
6833 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6838 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6839 /* If we collide with an already moved fd... */
6840 if (fd == sq[i].orig_fd) {
6842 * "echo 3>FILE 3>&- 3>FILE"
6843 * "echo 3>&- 3>FILE"
6844 * No need for last redirect to insert
6845 * another "need to close 3" indicator.
6847 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6852 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6853 return append_squirrel(sq, i, fd, -1);
6856 /* fd: redirect wants this fd to be used (e.g. 3>file).
6857 * Move all conflicting internally used fds,
6858 * and remember them so that we can restore them later.
6860 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6862 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6865 #if ENABLE_HUSH_INTERACTIVE
6866 if (fd == G.interactive_fd) {
6867 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6868 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6869 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6870 return 1; /* "we closed fd" */
6873 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6874 * (1) Redirect in a forked child. No need to save FILEs' fds,
6875 * we aren't going to use them anymore, ok to trash.
6876 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6877 * but how are we doing to restore them?
6878 * "fileno(fd) = new_fd" can't be done.
6883 /* If this one of script's fds? */
6884 if (save_FILEs_on_redirect(fd, avoid_fd))
6885 return 1; /* yes. "we closed fd" */
6887 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6888 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6889 return 0; /* "we did not close fd" */
6892 static void restore_redirects(struct squirrel *sq)
6896 for (i = 0; sq[i].orig_fd >= 0; i++) {
6897 if (sq[i].moved_to >= 0) {
6898 /* We simply die on error */
6899 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6900 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6902 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6903 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6904 close(sq[i].orig_fd);
6910 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6912 restore_redirected_FILEs();
6915 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6916 static void close_saved_fds_and_FILE_fds(void)
6918 if (G_interactive_fd)
6919 close(G_interactive_fd);
6920 close_all_FILE_list();
6924 static int internally_opened_fd(int fd, struct squirrel *sq)
6928 #if ENABLE_HUSH_INTERACTIVE
6929 if (fd == G.interactive_fd)
6932 /* If this one of script's fds? */
6933 if (fd_in_FILEs(fd))
6936 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6937 if (fd == sq[i].moved_to)
6943 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6944 * and stderr if they are redirected. */
6945 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6947 struct redir_struct *redir;
6949 for (redir = prog->redirects; redir; redir = redir->next) {
6953 if (redir->rd_type == REDIRECT_HEREDOC2) {
6954 /* "rd_fd<<HERE" case */
6955 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6956 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6958 debug_printf_parse("set heredoc '%s'\n",
6959 redir->rd_filename);
6960 setup_heredoc(redir);
6964 if (redir->rd_dup == REDIRFD_TO_FILE) {
6965 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6969 if (redir->rd_filename == NULL) {
6972 * "cmd >" (no filename)
6973 * "cmd > <file" (2nd redirect starts too early)
6975 syntax_error("invalid redirect");
6978 mode = redir_table[redir->rd_type].mode;
6979 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6980 newfd = open_or_warn(p, mode);
6983 /* Error message from open_or_warn can be lost
6984 * if stderr has been redirected, but bash
6985 * and ash both lose it as well
6986 * (though zsh doesn't!)
6990 if (newfd == redir->rd_fd && sqp) {
6991 /* open() gave us precisely the fd we wanted.
6992 * This means that this fd was not busy
6993 * (not opened to anywhere).
6994 * Remember to close it on restore:
6996 *sqp = add_squirrel_closed(*sqp, newfd);
6997 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7000 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7001 newfd = redir->rd_dup;
7004 if (newfd == redir->rd_fd)
7007 /* if "N>FILE": move newfd to redir->rd_fd */
7008 /* if "N>&M": dup newfd to redir->rd_fd */
7009 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7011 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7012 if (newfd == REDIRFD_CLOSE) {
7013 /* "N>&-" means "close me" */
7015 /* ^^^ optimization: saving may already
7016 * have closed it. If not... */
7017 close(redir->rd_fd);
7019 /* Sometimes we do another close on restore, getting EBADF.
7020 * Consider "echo 3>FILE 3>&-"
7021 * first redirect remembers "need to close 3",
7022 * and second redirect closes 3! Restore code then closes 3 again.
7025 /* if newfd is a script fd or saved fd, simulate EBADF */
7026 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7028 //bb_perror_msg_and_die("can't duplicate file descriptor");
7029 newfd = -1; /* same effect as code above */
7031 xdup2(newfd, redir->rd_fd);
7032 if (redir->rd_dup == REDIRFD_TO_FILE)
7033 /* "rd_fd > FILE" */
7035 /* else: "rd_fd > rd_dup" */
7041 static char *find_in_path(const char *arg)
7044 const char *PATH = get_local_var_value("PATH");
7050 const char *end = strchrnul(PATH, ':');
7051 int sz = end - PATH; /* must be int! */
7055 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7057 /* We have xxx::yyyy in $PATH,
7058 * it means "use current dir" */
7061 if (access(ret, F_OK) == 0)
7074 static const struct built_in_command *find_builtin_helper(const char *name,
7075 const struct built_in_command *x,
7076 const struct built_in_command *end)
7079 if (strcmp(name, x->b_cmd) != 0) {
7083 debug_printf_exec("found builtin '%s'\n", name);
7088 static const struct built_in_command *find_builtin1(const char *name)
7090 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7092 static const struct built_in_command *find_builtin(const char *name)
7094 const struct built_in_command *x = find_builtin1(name);
7097 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7100 #if ENABLE_HUSH_FUNCTIONS
7101 static struct function **find_function_slot(const char *name)
7103 struct function **funcpp = &G.top_func;
7105 if (strcmp(name, (*funcpp)->name) == 0) {
7108 funcpp = &(*funcpp)->next;
7113 static const struct function *find_function(const char *name)
7115 const struct function *funcp = *find_function_slot(name);
7117 debug_printf_exec("found function '%s'\n", name);
7121 /* Note: takes ownership on name ptr */
7122 static struct function *new_function(char *name)
7124 struct function **funcpp = find_function_slot(name);
7125 struct function *funcp = *funcpp;
7127 if (funcp != NULL) {
7128 struct command *cmd = funcp->parent_cmd;
7129 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7131 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7133 /* Note: if !funcp->body, do not free body_as_string!
7134 * This is a special case of "-F name body" function:
7135 * body_as_string was not malloced! */
7137 free_pipe_list(funcp->body);
7139 free(funcp->body_as_string);
7143 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7144 cmd->argv[0] = funcp->name;
7145 cmd->group = funcp->body;
7147 cmd->group_as_string = funcp->body_as_string;
7151 debug_printf_exec("remembering new function '%s'\n", name);
7152 funcp = *funcpp = xzalloc(sizeof(*funcp));
7153 /*funcp->next = NULL;*/
7160 # if ENABLE_HUSH_UNSET
7161 static void unset_func(const char *name)
7163 struct function **funcpp = find_function_slot(name);
7164 struct function *funcp = *funcpp;
7166 if (funcp != NULL) {
7167 debug_printf_exec("freeing function '%s'\n", funcp->name);
7168 *funcpp = funcp->next;
7169 /* funcp is unlinked now, deleting it.
7170 * Note: if !funcp->body, the function was created by
7171 * "-F name body", do not free ->body_as_string
7172 * and ->name as they were not malloced. */
7174 free_pipe_list(funcp->body);
7177 free(funcp->body_as_string);
7186 #define exec_function(to_free, funcp, argv) \
7187 exec_function(funcp, argv)
7189 static void exec_function(char ***to_free,
7190 const struct function *funcp,
7191 char **argv) NORETURN;
7192 static void exec_function(char ***to_free,
7193 const struct function *funcp,
7199 argv[0] = G.global_argv[0];
7200 G.global_argv = argv;
7201 G.global_argc = n = 1 + string_array_len(argv + 1);
7203 // Example when we are here: "cmd | func"
7204 // func will run with saved-redirect fds open.
7205 // $ f() { echo /proc/self/fd/*; }
7207 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7208 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7211 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7212 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7213 // They are CLOEXEC so external programs won't see them, but
7214 // for "more correctness" we might want to close those extra fds here:
7215 //? close_saved_fds_and_FILE_fds();
7217 /* "we are in function, ok to use return" */
7218 G_flag_return_in_progress = -1;
7219 IF_HUSH_LOCAL(G.func_nest_level++;)
7221 /* On MMU, funcp->body is always non-NULL */
7222 n = run_list(funcp->body);
7226 //? close_saved_fds_and_FILE_fds();
7228 //TODO: check whether "true | func_with_return" works
7230 re_execute_shell(to_free,
7231 funcp->body_as_string,
7238 static int run_function(const struct function *funcp, char **argv)
7244 save_and_replace_G_args(&sv, argv);
7246 /* "we are in function, ok to use return" */
7247 sv_flg = G_flag_return_in_progress;
7248 G_flag_return_in_progress = -1;
7249 IF_HUSH_LOCAL(G.func_nest_level++;)
7251 /* On MMU, funcp->body is always non-NULL */
7254 /* Function defined by -F */
7255 parse_and_run_string(funcp->body_as_string);
7256 rc = G.last_exitcode;
7260 rc = run_list(funcp->body);
7263 # if ENABLE_HUSH_LOCAL
7265 struct variable *var;
7266 struct variable **var_pp;
7268 var_pp = &G.top_var;
7269 while ((var = *var_pp) != NULL) {
7270 if (var->func_nest_level < G.func_nest_level) {
7271 var_pp = &var->next;
7275 if (var->flg_export)
7276 bb_unsetenv(var->varstr);
7277 /* Remove from global list */
7278 *var_pp = var->next;
7284 G.func_nest_level--;
7287 G_flag_return_in_progress = sv_flg;
7289 restore_G_args(&sv, argv);
7293 #endif /* ENABLE_HUSH_FUNCTIONS */
7297 #define exec_builtin(to_free, x, argv) \
7298 exec_builtin(x, argv)
7300 #define exec_builtin(to_free, x, argv) \
7301 exec_builtin(to_free, argv)
7303 static void exec_builtin(char ***to_free,
7304 const struct built_in_command *x,
7305 char **argv) NORETURN;
7306 static void exec_builtin(char ***to_free,
7307 const struct built_in_command *x,
7313 //? close_saved_fds_and_FILE_fds();
7314 rcode = x->b_function(argv);
7319 /* On NOMMU, we must never block!
7320 * Example: { sleep 99 | read line; } & echo Ok
7322 re_execute_shell(to_free,
7331 static void execvp_or_die(char **argv) NORETURN;
7332 static void execvp_or_die(char **argv)
7335 debug_printf_exec("execing '%s'\n", argv[0]);
7336 /* Don't propagate SIG_IGN to the child */
7337 if (SPECIAL_JOBSTOP_SIGS != 0)
7338 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7339 execvp(argv[0], argv);
7341 if (errno == EACCES) e = 126;
7342 if (errno == ENOENT) e = 127;
7343 bb_perror_msg("can't execute '%s'", argv[0]);
7347 #if ENABLE_HUSH_MODE_X
7348 static void dump_cmd_in_x_mode(char **argv)
7350 if (G_x_mode && argv) {
7351 /* We want to output the line in one write op */
7359 len += strlen(argv[n++]) + 1;
7365 p += sprintf(p, " %s", argv[n++]);
7373 # define dump_cmd_in_x_mode(argv) ((void)0)
7376 #if ENABLE_HUSH_COMMAND
7377 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7386 char *path = getenv("PATH");
7387 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
7389 _exit(1); /* PROG was not found */
7391 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7393 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
7399 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
7403 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7404 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7405 #define pseudo_exec(nommu_save, command, argv_expanded) \
7406 pseudo_exec(command, argv_expanded)
7409 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7411 * Don't exit() here. If you don't exec, use _exit instead.
7412 * The at_exit handlers apparently confuse the calling process,
7413 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7415 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7416 char **argv, int assignment_cnt,
7417 char **argv_expanded) NORETURN;
7418 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7419 char **argv, int assignment_cnt,
7420 char **argv_expanded)
7422 const struct built_in_command *x;
7424 #if ENABLE_HUSH_COMMAND
7428 new_env = expand_assignments(argv, assignment_cnt);
7429 dump_cmd_in_x_mode(new_env);
7431 if (!argv[assignment_cnt]) {
7432 /* Case when we are here: ... | var=val | ...
7433 * (note that we do not exit early, i.e., do not optimize out
7434 * expand_assignments(): think about ... | var=`sleep 1` | ...
7436 free_strings(new_env);
7437 _exit(EXIT_SUCCESS);
7441 set_vars_and_save_old(new_env);
7442 free(new_env); /* optional */
7443 /* we can also destroy set_vars_and_save_old's return value,
7446 nommu_save->new_env = new_env;
7447 nommu_save->old_vars = set_vars_and_save_old(new_env);
7450 if (argv_expanded) {
7451 argv = argv_expanded;
7453 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7455 nommu_save->argv = argv;
7458 dump_cmd_in_x_mode(argv);
7460 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7461 if (strchr(argv[0], '/') != NULL)
7465 #if ENABLE_HUSH_FUNCTIONS
7466 /* Check if the command matches any functions (this goes before bltins) */
7468 const struct function *funcp = find_function(argv[0]);
7470 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7475 #if ENABLE_HUSH_COMMAND
7476 /* "command BAR": run BAR without looking it up among functions
7477 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7478 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7480 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7485 if (p[0] != '-' || !p[1])
7486 continue; /* bash allows "command command command [-OPT] BAR" */
7494 if (p[0] != '-' || !p[1])
7496 continue; /* next arg is also -opts, process it too */
7502 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7507 # if ENABLE_HUSH_FUNCTIONS
7508 if (opt_vV && find_function(argv[0]))
7509 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7513 /* Check if the command matches any of the builtins.
7514 * Depending on context, this might be redundant. But it's
7515 * easier to waste a few CPU cycles than it is to figure out
7516 * if this is one of those cases.
7518 /* Why "BB_MMU ? :" difference in logic? -
7519 * On NOMMU, it is more expensive to re-execute shell
7520 * just in order to run echo or test builtin.
7521 * It's better to skip it here and run corresponding
7522 * non-builtin later. */
7523 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7525 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7526 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7529 #if ENABLE_FEATURE_SH_STANDALONE
7530 /* Check if the command matches any busybox applets */
7532 int a = find_applet_by_name(argv[0]);
7534 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
7535 # if BB_MMU /* see above why on NOMMU it is not allowed */
7536 if (APPLET_IS_NOEXEC(a)) {
7537 /* Do not leak open fds from opened script files etc.
7538 * Testcase: interactive "ls -l /proc/self/fd"
7539 * should not show tty fd open.
7541 close_saved_fds_and_FILE_fds();
7542 //FIXME: should also close saved redir fds
7543 /* Without this, "rm -i FILE" can't be ^C'ed: */
7544 switch_off_special_sigs(G.special_sig_mask);
7545 debug_printf_exec("running applet '%s'\n", argv[0]);
7546 run_noexec_applet_and_exit(a, argv[0], argv);
7549 /* Re-exec ourselves */
7550 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7551 /* Don't propagate SIG_IGN to the child */
7552 if (SPECIAL_JOBSTOP_SIGS != 0)
7553 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7554 execv(bb_busybox_exec_path, argv);
7555 /* If they called chroot or otherwise made the binary no longer
7556 * executable, fall through */
7561 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7564 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
7565 execvp_or_die(argv);
7568 /* Called after [v]fork() in run_pipe
7570 static void pseudo_exec(nommu_save_t *nommu_save,
7571 struct command *command,
7572 char **argv_expanded) NORETURN;
7573 static void pseudo_exec(nommu_save_t *nommu_save,
7574 struct command *command,
7575 char **argv_expanded)
7577 if (command->argv) {
7578 pseudo_exec_argv(nommu_save, command->argv,
7579 command->assignment_cnt, argv_expanded);
7582 if (command->group) {
7583 /* Cases when we are here:
7586 * ... | ( list ) | ...
7587 * ... | { list } | ...
7591 debug_printf_exec("pseudo_exec: run_list\n");
7592 reset_traps_to_defaults();
7593 rcode = run_list(command->group);
7594 /* OK to leak memory by not calling free_pipe_list,
7595 * since this process is about to exit */
7598 re_execute_shell(&nommu_save->argv_from_re_execing,
7599 command->group_as_string,
7606 /* Case when we are here: ... | >file */
7607 debug_printf_exec("pseudo_exec'ed null command\n");
7608 _exit(EXIT_SUCCESS);
7612 static const char *get_cmdtext(struct pipe *pi)
7618 /* This is subtle. ->cmdtext is created only on first backgrounding.
7619 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7620 * On subsequent bg argv is trashed, but we won't use it */
7624 argv = pi->cmds[0].argv;
7626 pi->cmdtext = xzalloc(1);
7631 len += strlen(*argv) + 1;
7635 argv = pi->cmds[0].argv;
7637 p = stpcpy(p, *argv);
7644 static void remove_job_from_table(struct pipe *pi)
7646 struct pipe *prev_pipe;
7648 if (pi == G.job_list) {
7649 G.job_list = pi->next;
7651 prev_pipe = G.job_list;
7652 while (prev_pipe->next != pi)
7653 prev_pipe = prev_pipe->next;
7654 prev_pipe->next = pi->next;
7658 G.last_jobid = G.job_list->jobid;
7661 static void delete_finished_job(struct pipe *pi)
7663 remove_job_from_table(pi);
7667 static void clean_up_last_dead_job(void)
7669 if (G.job_list && !G.job_list->alive_cmds)
7670 delete_finished_job(G.job_list);
7673 static void insert_job_into_table(struct pipe *pi)
7675 struct pipe *job, **jobp;
7678 clean_up_last_dead_job();
7680 /* Find the end of the list, and find next job ID to use */
7683 while ((job = *jobp) != NULL) {
7690 /* Create a new job struct at the end */
7691 job = *jobp = xmemdup(pi, sizeof(*pi));
7693 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7694 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7695 for (i = 0; i < pi->num_cmds; i++) {
7696 job->cmds[i].pid = pi->cmds[i].pid;
7697 /* all other fields are not used and stay zero */
7699 job->cmdtext = xstrdup(get_cmdtext(pi));
7701 if (G_interactive_fd)
7702 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7703 G.last_jobid = job->jobid;
7707 static int job_exited_or_stopped(struct pipe *pi)
7711 if (pi->alive_cmds != pi->stopped_cmds)
7714 /* All processes in fg pipe have exited or stopped */
7718 rcode = pi->cmds[i].cmd_exitcode;
7719 /* usually last process gives overall exitstatus,
7720 * but with "set -o pipefail", last *failed* process does */
7721 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7724 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7728 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7735 dead = WIFEXITED(status) || WIFSIGNALED(status);
7738 if (WIFSTOPPED(status))
7739 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7740 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7741 if (WIFSIGNALED(status))
7742 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7743 childpid, WTERMSIG(status), WEXITSTATUS(status));
7744 if (WIFEXITED(status))
7745 debug_printf_jobs("pid %d exited, exitcode %d\n",
7746 childpid, WEXITSTATUS(status));
7748 /* Were we asked to wait for a fg pipe? */
7750 i = fg_pipe->num_cmds;
7755 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7756 if (fg_pipe->cmds[i].pid != childpid)
7760 fg_pipe->cmds[i].pid = 0;
7761 fg_pipe->alive_cmds--;
7762 ex = WEXITSTATUS(status);
7763 /* bash prints killer signal's name for *last*
7764 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7765 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7767 if (WIFSIGNALED(status)) {
7768 int sig = WTERMSIG(status);
7769 if (i == fg_pipe->num_cmds-1)
7770 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7771 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7772 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7773 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7774 * Maybe we need to use sig | 128? */
7777 fg_pipe->cmds[i].cmd_exitcode = ex;
7779 fg_pipe->stopped_cmds++;
7781 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7782 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7783 rcode = job_exited_or_stopped(fg_pipe);
7785 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7786 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7787 * and "killall -STOP cat" */
7788 if (G_interactive_fd) {
7790 if (fg_pipe->alive_cmds != 0)
7791 insert_job_into_table(fg_pipe);
7795 if (fg_pipe->alive_cmds == 0)
7798 /* There are still running processes in the fg_pipe */
7801 /* It wasn't in fg_pipe, look for process in bg pipes */
7805 /* We were asked to wait for bg or orphaned children */
7806 /* No need to remember exitcode in this case */
7807 for (pi = G.job_list; pi; pi = pi->next) {
7808 for (i = 0; i < pi->num_cmds; i++) {
7809 if (pi->cmds[i].pid == childpid)
7810 goto found_pi_and_prognum;
7813 /* Happens when shell is used as init process (init=/bin/sh) */
7814 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7815 return -1; /* this wasn't a process from fg_pipe */
7817 found_pi_and_prognum:
7820 int rcode = WEXITSTATUS(status);
7821 if (WIFSIGNALED(status))
7822 rcode = 128 + WTERMSIG(status);
7823 pi->cmds[i].cmd_exitcode = rcode;
7824 if (G.last_bg_pid == pi->cmds[i].pid)
7825 G.last_bg_pid_exitcode = rcode;
7826 pi->cmds[i].pid = 0;
7828 if (!pi->alive_cmds) {
7829 if (G_interactive_fd) {
7830 printf(JOB_STATUS_FORMAT, pi->jobid,
7831 "Done", pi->cmdtext);
7832 delete_finished_job(pi);
7835 * bash deletes finished jobs from job table only in interactive mode,
7836 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7837 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7838 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7839 * We only retain one "dead" job, if it's the single job on the list.
7840 * This covers most of real-world scenarios where this is useful.
7842 if (pi != G.job_list)
7843 delete_finished_job(pi);
7851 return -1; /* this wasn't a process from fg_pipe */
7854 /* Check to see if any processes have exited -- if they have,
7855 * figure out why and see if a job has completed.
7857 * If non-NULL fg_pipe: wait for its completion or stop.
7858 * Return its exitcode or zero if stopped.
7860 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7861 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7862 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7863 * or 0 if no children changed status.
7865 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7866 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7867 * or 0 if no children changed status.
7869 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7875 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7877 attributes = WUNTRACED;
7878 if (fg_pipe == NULL)
7879 attributes |= WNOHANG;
7882 #if ENABLE_HUSH_FAST
7883 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7884 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7885 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7886 /* There was neither fork nor SIGCHLD since last waitpid */
7887 /* Avoid doing waitpid syscall if possible */
7888 if (!G.we_have_children) {
7892 if (fg_pipe == NULL) { /* is WNOHANG set? */
7893 /* We have children, but they did not exit
7894 * or stop yet (we saw no SIGCHLD) */
7897 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7901 /* Do we do this right?
7902 * bash-3.00# sleep 20 | false
7904 * [3]+ Stopped sleep 20 | false
7905 * bash-3.00# echo $?
7906 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7907 * [hush 1.14.0: yes we do it right]
7911 #if ENABLE_HUSH_FAST
7913 i = G.count_SIGCHLD;
7915 childpid = waitpid(-1, &status, attributes);
7916 if (childpid <= 0) {
7917 if (childpid && errno != ECHILD)
7918 bb_perror_msg("waitpid");
7919 #if ENABLE_HUSH_FAST
7920 else { /* Until next SIGCHLD, waitpid's are useless */
7921 G.we_have_children = (childpid == 0);
7922 G.handled_SIGCHLD = i;
7923 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7926 /* ECHILD (no children), or 0 (no change in children status) */
7930 rcode = process_wait_result(fg_pipe, childpid, status);
7932 /* fg_pipe exited or stopped */
7935 if (childpid == waitfor_pid) {
7936 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7937 rcode = WEXITSTATUS(status);
7938 if (WIFSIGNALED(status))
7939 rcode = 128 + WTERMSIG(status);
7940 if (WIFSTOPPED(status))
7941 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7942 rcode = 128 + WSTOPSIG(status);
7944 break; /* "wait PID" called us, give it exitcode+1 */
7946 /* This wasn't one of our processes, or */
7947 /* fg_pipe still has running processes, do waitpid again */
7948 } /* while (waitpid succeeds)... */
7954 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7957 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7958 if (G_saved_tty_pgrp) {
7959 /* Job finished, move the shell to the foreground */
7960 p = getpgrp(); /* our process group id */
7961 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7962 tcsetpgrp(G_interactive_fd, p);
7968 /* Start all the jobs, but don't wait for anything to finish.
7971 * Return code is normally -1, when the caller has to wait for children
7972 * to finish to determine the exit status of the pipe. If the pipe
7973 * is a simple builtin command, however, the action is done by the
7974 * time run_pipe returns, and the exit code is provided as the
7977 * Returns -1 only if started some children. IOW: we have to
7978 * mask out retvals of builtins etc with 0xff!
7980 * The only case when we do not need to [v]fork is when the pipe
7981 * is single, non-backgrounded, non-subshell command. Examples:
7982 * cmd ; ... { list } ; ...
7983 * cmd && ... { list } && ...
7984 * cmd || ... { list } || ...
7985 * If it is, then we can run cmd as a builtin, NOFORK,
7986 * or (if SH_STANDALONE) an applet, and we can run the { list }
7987 * with run_list. If it isn't one of these, we fork and exec cmd.
7989 * Cases when we must fork:
7990 * non-single: cmd | cmd
7991 * backgrounded: cmd & { list } &
7992 * subshell: ( list ) [&]
7994 #if !ENABLE_HUSH_MODE_X
7995 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7996 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7998 static int redirect_and_varexp_helper(char ***new_env_p,
7999 struct variable **old_vars_p,
8000 struct command *command,
8001 struct squirrel **sqp,
8002 char **argv_expanded)
8004 /* setup_redirects acts on file descriptors, not FILEs.
8005 * This is perfect for work that comes after exec().
8006 * Is it really safe for inline use? Experimentally,
8007 * things seem to work. */
8008 int rcode = setup_redirects(command, sqp);
8010 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8011 *new_env_p = new_env;
8012 dump_cmd_in_x_mode(new_env);
8013 dump_cmd_in_x_mode(argv_expanded);
8015 *old_vars_p = set_vars_and_save_old(new_env);
8019 static NOINLINE int run_pipe(struct pipe *pi)
8021 static const char *const null_ptr = NULL;
8025 struct command *command;
8026 char **argv_expanded;
8028 struct squirrel *squirrel = NULL;
8031 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8034 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8035 * Result should be 3 lines: q w e, qwe, q w e
8037 G.ifs = get_local_var_value("IFS");
8041 IF_HUSH_JOB(pi->pgrp = -1;)
8042 pi->stopped_cmds = 0;
8043 command = &pi->cmds[0];
8044 argv_expanded = NULL;
8046 if (pi->num_cmds != 1
8047 || pi->followup == PIPE_BG
8048 || command->cmd_type == CMD_SUBSHELL
8055 debug_printf_exec(": group:%p argv:'%s'\n",
8056 command->group, command->argv ? command->argv[0] : "NONE");
8058 if (command->group) {
8059 #if ENABLE_HUSH_FUNCTIONS
8060 if (command->cmd_type == CMD_FUNCDEF) {
8061 /* "executing" func () { list } */
8062 struct function *funcp;
8064 funcp = new_function(command->argv[0]);
8065 /* funcp->name is already set to argv[0] */
8066 funcp->body = command->group;
8068 funcp->body_as_string = command->group_as_string;
8069 command->group_as_string = NULL;
8071 command->group = NULL;
8072 command->argv[0] = NULL;
8073 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8074 funcp->parent_cmd = command;
8075 command->child_func = funcp;
8077 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8079 return EXIT_SUCCESS;
8083 debug_printf("non-subshell group\n");
8084 rcode = 1; /* exitcode if redir failed */
8085 if (setup_redirects(command, &squirrel) == 0) {
8086 debug_printf_exec(": run_list\n");
8087 rcode = run_list(command->group) & 0xff;
8089 restore_redirects(squirrel);
8090 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8092 debug_printf_exec("run_pipe: return %d\n", rcode);
8096 argv = command->argv ? command->argv : (char **) &null_ptr;
8098 const struct built_in_command *x;
8099 #if ENABLE_HUSH_FUNCTIONS
8100 const struct function *funcp;
8104 char **new_env = NULL;
8105 struct variable *old_vars = NULL;
8108 strcpy(G_lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8110 if (argv[command->assignment_cnt] == NULL) {
8111 /* Assignments, but no command */
8112 /* Ensure redirects take effect (that is, create files).
8113 * Try "a=t >file" */
8114 #if 0 /* A few cases in testsuite fail with this code. FIXME */
8115 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
8116 /* Set shell variables */
8120 if (set_local_var(*argv, /*flag:*/ 0)) {
8121 /* assignment to readonly var / putenv error? */
8127 /* Redirect error sets $? to 1. Otherwise,
8128 * if evaluating assignment value set $?, retain it.
8129 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8131 rcode = G.last_exitcode;
8132 /* Exit, _skipping_ variable restoring code: */
8133 goto clean_up_and_ret0;
8135 #else /* Older, bigger, but more correct code */
8137 rcode = setup_redirects(command, &squirrel);
8138 restore_redirects(squirrel);
8139 /* Set shell variables */
8141 bb_putchar_stderr('+');
8143 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8145 fprintf(stderr, " %s", p);
8146 debug_printf_exec("set shell var:'%s'->'%s'\n",
8148 if (set_local_var(p, /*flag:*/ 0)) {
8149 /* assignment to readonly var / putenv error? */
8155 bb_putchar_stderr('\n');
8156 /* Redirect error sets $? to 1. Otherwise,
8157 * if evaluating assignment value set $?, retain it.
8158 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8160 rcode = G.last_exitcode;
8161 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8163 debug_printf_exec("run_pipe: return %d\n", rcode);
8168 /* Expand the rest into (possibly) many strings each */
8170 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8171 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8175 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8178 /* if someone gives us an empty string: `cmd with empty output` */
8179 if (!argv_expanded[0]) {
8180 free(argv_expanded);
8182 return G.last_exitcode;
8185 #if ENABLE_HUSH_FUNCTIONS
8186 /* Check if argv[0] matches any functions (this goes before bltins) */
8187 funcp = find_function(argv_expanded[0]);
8191 x = find_builtin(argv_expanded[0]);
8194 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8195 debug_printf("exec with redirects only\n");
8196 rcode = setup_redirects(command, NULL);
8197 /* rcode=1 can be if redir file can't be opened */
8198 goto clean_up_and_ret1;
8201 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8204 debug_printf_exec(": builtin '%s' '%s'...\n",
8205 x->b_cmd, argv_expanded[1]);
8207 rcode = x->b_function(argv_expanded) & 0xff;
8210 #if ENABLE_HUSH_FUNCTIONS
8212 # if ENABLE_HUSH_LOCAL
8213 struct variable **sv;
8214 sv = G.shadowed_vars_pp;
8215 G.shadowed_vars_pp = &old_vars;
8217 debug_printf_exec(": function '%s' '%s'...\n",
8218 funcp->name, argv_expanded[1]);
8219 rcode = run_function(funcp, argv_expanded) & 0xff;
8220 # if ENABLE_HUSH_LOCAL
8221 G.shadowed_vars_pp = sv;
8227 unset_vars(new_env);
8229 /* clean_up_and_ret0: */
8230 restore_redirects(squirrel);
8232 * Try "usleep 99999999" + ^C + "echo $?"
8233 * with FEATURE_SH_NOFORK=y.
8236 /* It was builtin or nofork.
8237 * if this would be a real fork/execed program,
8238 * it should have died if a fatal sig was received.
8239 * But OTOH, there was no separate process,
8240 * the sig was sent to _shell_, not to non-existing
8242 * Let's just handle ^C only, this one is obvious:
8243 * we aren't ok with exitcode 0 when ^C was pressed
8244 * during builtin/nofork.
8246 if (sigismember(&G.pending_set, SIGINT))
8247 rcode = 128 + SIGINT;
8250 free(argv_expanded);
8251 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8253 debug_printf_exec("run_pipe return %d\n", rcode);
8257 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
8258 int n = find_applet_by_name(argv_expanded[0]);
8259 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8260 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8262 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8263 argv_expanded[0], argv_expanded[1]);
8265 * Note: signals (^C) can't interrupt here.
8266 * We remember them and they will be acted upon
8267 * after applet returns.
8268 * This makes applets which can run for a long time
8269 * and/or wait for user input ineligible for NOFORK:
8270 * for example, "yes" or "rm" (rm -i waits for input).
8272 rcode = run_nofork_applet(n, argv_expanded);
8274 goto clean_up_and_ret;
8277 /* It is neither builtin nor applet. We must fork. */
8281 /* NB: argv_expanded may already be created, and that
8282 * might include `cmd` runs! Do not rerun it! We *must*
8283 * use argv_expanded if it's non-NULL */
8285 /* Going to fork a child per each pipe member */
8290 while (cmd_no < pi->num_cmds) {
8291 struct fd_pair pipefds;
8293 volatile nommu_save_t nommu_save;
8294 nommu_save.new_env = NULL;
8295 nommu_save.old_vars = NULL;
8296 nommu_save.argv = NULL;
8297 nommu_save.argv_from_re_execing = NULL;
8299 command = &pi->cmds[cmd_no];
8301 if (command->argv) {
8302 debug_printf_exec(": pipe member '%s' '%s'...\n",
8303 command->argv[0], command->argv[1]);
8305 debug_printf_exec(": pipe member with no argv\n");
8308 /* pipes are inserted between pairs of commands */
8311 if (cmd_no < pi->num_cmds)
8312 xpiped_pair(pipefds);
8315 strcpy(G_lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8317 command->pid = BB_MMU ? fork() : vfork();
8318 if (!command->pid) { /* child */
8320 disable_restore_tty_pgrp_on_exit();
8321 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8323 /* Every child adds itself to new process group
8324 * with pgid == pid_of_first_child_in_pipe */
8325 if (G.run_list_level == 1 && G_interactive_fd) {
8328 if (pgrp < 0) /* true for 1st process only */
8330 if (setpgid(0, pgrp) == 0
8331 && pi->followup != PIPE_BG
8332 && G_saved_tty_pgrp /* we have ctty */
8334 /* We do it in *every* child, not just first,
8336 tcsetpgrp(G_interactive_fd, pgrp);
8340 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8341 /* 1st cmd in backgrounded pipe
8342 * should have its stdin /dev/null'ed */
8344 if (open(bb_dev_null, O_RDONLY))
8345 xopen("/", O_RDONLY);
8347 xmove_fd(next_infd, 0);
8349 xmove_fd(pipefds.wr, 1);
8352 /* Like bash, explicit redirects override pipes,
8353 * and the pipe fd (fd#1) is available for dup'ing:
8354 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8355 * of cmd1 goes into pipe.
8357 if (setup_redirects(command, NULL)) {
8358 /* Happens when redir file can't be opened:
8359 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8361 * hush: can't open '/qwe/rty': No such file or directory
8363 * (echo BAR is not executed, it hits _exit(1) below)
8368 /* Stores to nommu_save list of env vars putenv'ed
8369 * (NOMMU, on MMU we don't need that) */
8370 /* cast away volatility... */
8371 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8372 /* pseudo_exec() does not return */
8375 /* parent or error */
8376 #if ENABLE_HUSH_FAST
8378 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8380 enable_restore_tty_pgrp_on_exit();
8382 /* Clean up after vforked child */
8383 free(nommu_save.argv);
8384 free(nommu_save.argv_from_re_execing);
8385 unset_vars(nommu_save.new_env);
8386 add_vars(nommu_save.old_vars);
8388 free(argv_expanded);
8389 argv_expanded = NULL;
8390 if (command->pid < 0) { /* [v]fork failed */
8391 /* Clearly indicate, was it fork or vfork */
8392 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8396 /* Second and next children need to know pid of first one */
8398 pi->pgrp = command->pid;
8404 if (cmd_no < pi->num_cmds)
8406 /* Pass read (output) pipe end to next iteration */
8407 next_infd = pipefds.rd;
8410 if (!pi->alive_cmds) {
8412 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8417 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8421 /* NB: called by pseudo_exec, and therefore must not modify any
8422 * global data until exec/_exit (we can be a child after vfork!) */
8423 static int run_list(struct pipe *pi)
8425 #if ENABLE_HUSH_CASE
8426 char *case_word = NULL;
8428 #if ENABLE_HUSH_LOOPS
8429 struct pipe *loop_top = NULL;
8430 char **for_lcur = NULL;
8431 char **for_list = NULL;
8433 smallint last_followup;
8435 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8436 smalluint cond_code = 0;
8438 enum { cond_code = 0 };
8441 smallint rword; /* RES_foo */
8442 smallint last_rword; /* ditto */
8445 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8448 #if ENABLE_HUSH_LOOPS
8449 /* Check syntax for "for" */
8452 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8453 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8455 /* current word is FOR or IN (BOLD in comments below) */
8456 if (cpipe->next == NULL) {
8457 syntax_error("malformed for");
8459 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8462 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8463 if (cpipe->next->res_word == RES_DO)
8465 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8466 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8467 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8469 syntax_error("malformed for");
8471 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8478 /* Past this point, all code paths should jump to ret: label
8479 * in order to return, no direct "return" statements please.
8480 * This helps to ensure that no memory is leaked. */
8488 last_rword = RES_XXXX;
8490 last_followup = PIPE_SEQ;
8491 rcode = G.last_exitcode;
8493 /* Go through list of pipes, (maybe) executing them. */
8494 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8496 int sv_errexit_depth;
8500 if (G_flag_return_in_progress == 1)
8503 IF_HAS_KEYWORDS(rword = pi->res_word;)
8504 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8505 rword, cond_code, last_rword);
8507 sv_errexit_depth = G.errexit_depth;
8510 rword == RES_IF || rword == RES_ELIF ||
8512 pi->followup != PIPE_SEQ
8516 #if ENABLE_HUSH_LOOPS
8517 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8518 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8520 /* start of a loop: remember where loop starts */
8525 /* Still in the same "if...", "then..." or "do..." branch? */
8526 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8527 if ((rcode == 0 && last_followup == PIPE_OR)
8528 || (rcode != 0 && last_followup == PIPE_AND)
8530 /* It is "<true> || CMD" or "<false> && CMD"
8531 * and we should not execute CMD */
8532 debug_printf_exec("skipped cmd because of || or &&\n");
8533 last_followup = pi->followup;
8534 goto dont_check_jobs_but_continue;
8537 last_followup = pi->followup;
8538 IF_HAS_KEYWORDS(last_rword = rword;)
8541 if (rword == RES_THEN) {
8542 /* if false; then ... fi has exitcode 0! */
8543 G.last_exitcode = rcode = EXIT_SUCCESS;
8544 /* "if <false> THEN cmd": skip cmd */
8548 if (rword == RES_ELSE || rword == RES_ELIF) {
8549 /* "if <true> then ... ELSE/ELIF cmd":
8550 * skip cmd and all following ones */
8555 #if ENABLE_HUSH_LOOPS
8556 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8558 /* first loop through for */
8560 static const char encoded_dollar_at[] ALIGN1 = {
8561 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8562 }; /* encoded representation of "$@" */
8563 static const char *const encoded_dollar_at_argv[] = {
8564 encoded_dollar_at, NULL
8565 }; /* argv list with one element: "$@" */
8568 vals = (char**)encoded_dollar_at_argv;
8569 if (pi->next->res_word == RES_IN) {
8570 /* if no variable values after "in" we skip "for" */
8571 if (!pi->next->cmds[0].argv) {
8572 G.last_exitcode = rcode = EXIT_SUCCESS;
8573 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8576 vals = pi->next->cmds[0].argv;
8577 } /* else: "for var; do..." -> assume "$@" list */
8578 /* create list of variable values */
8579 debug_print_strings("for_list made from", vals);
8580 for_list = expand_strvec_to_strvec(vals);
8581 for_lcur = for_list;
8582 debug_print_strings("for_list", for_list);
8585 /* "for" loop is over, clean up */
8591 /* Insert next value from for_lcur */
8592 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8593 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8596 if (rword == RES_IN) {
8597 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8599 if (rword == RES_DONE) {
8600 continue; /* "done" has no cmds too */
8603 #if ENABLE_HUSH_CASE
8604 if (rword == RES_CASE) {
8605 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8606 case_word = expand_strvec_to_string(pi->cmds->argv);
8607 unbackslash(case_word);
8610 if (rword == RES_MATCH) {
8613 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8614 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8616 /* all prev words didn't match, does this one match? */
8617 argv = pi->cmds->argv;
8619 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8620 /* TODO: which FNM_xxx flags to use? */
8621 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8622 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8624 if (cond_code == 0) { /* match! we will execute this branch */
8626 case_word = NULL; /* make future "word)" stop */
8633 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8634 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8636 continue; /* not matched yet, skip this pipe */
8638 if (rword == RES_ESAC) {
8639 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8641 /* "case" did not match anything: still set $? (to 0) */
8642 G.last_exitcode = rcode = EXIT_SUCCESS;
8646 /* Just pressing <enter> in shell should check for jobs.
8647 * OTOH, in non-interactive shell this is useless
8648 * and only leads to extra job checks */
8649 if (pi->num_cmds == 0) {
8650 if (G_interactive_fd)
8651 goto check_jobs_and_continue;
8655 /* After analyzing all keywords and conditions, we decided
8656 * to execute this pipe. NB: have to do checkjobs(NULL)
8657 * after run_pipe to collect any background children,
8658 * even if list execution is to be stopped. */
8659 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8660 #if ENABLE_HUSH_LOOPS
8661 G.flag_break_continue = 0;
8663 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8665 /* We ran a builtin, function, or group.
8666 * rcode is already known
8667 * and we don't need to wait for anything. */
8668 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8669 G.last_exitcode = rcode;
8670 check_and_run_traps();
8671 #if ENABLE_HUSH_LOOPS
8672 /* Was it "break" or "continue"? */
8673 if (G.flag_break_continue) {
8674 smallint fbc = G.flag_break_continue;
8675 /* We might fall into outer *loop*,
8676 * don't want to break it too */
8678 G.depth_break_continue--;
8679 if (G.depth_break_continue == 0)
8680 G.flag_break_continue = 0;
8681 /* else: e.g. "continue 2" should *break* once, *then* continue */
8682 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8683 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8684 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8687 /* "continue": simulate end of loop */
8692 if (G_flag_return_in_progress == 1) {
8693 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8696 } else if (pi->followup == PIPE_BG) {
8697 /* What does bash do with attempts to background builtins? */
8698 /* even bash 3.2 doesn't do that well with nested bg:
8699 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8700 * I'm NOT treating inner &'s as jobs */
8702 if (G.run_list_level == 1)
8703 insert_job_into_table(pi);
8705 /* Last command's pid goes to $! */
8706 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8707 G.last_bg_pid_exitcode = 0;
8708 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8709 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8710 rcode = EXIT_SUCCESS;
8714 if (G.run_list_level == 1 && G_interactive_fd) {
8715 /* Waits for completion, then fg's main shell */
8716 rcode = checkjobs_and_fg_shell(pi);
8717 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8721 /* This one just waits for completion */
8722 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8723 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8725 G.last_exitcode = rcode;
8726 check_and_run_traps();
8729 /* Handle "set -e" */
8730 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8731 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8732 if (G.errexit_depth == 0)
8735 G.errexit_depth = sv_errexit_depth;
8737 /* Analyze how result affects subsequent commands */
8739 if (rword == RES_IF || rword == RES_ELIF)
8742 check_jobs_and_continue:
8743 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8744 dont_check_jobs_but_continue: ;
8745 #if ENABLE_HUSH_LOOPS
8746 /* Beware of "while false; true; do ..."! */
8748 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8749 /* check for RES_DONE is needed for "while ...; do \n done" case */
8751 if (rword == RES_WHILE) {
8753 /* "while false; do...done" - exitcode 0 */
8754 G.last_exitcode = rcode = EXIT_SUCCESS;
8755 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8759 if (rword == RES_UNTIL) {
8761 debug_printf_exec(": until expr is true: breaking\n");
8772 #if ENABLE_HUSH_LOOPS
8777 #if ENABLE_HUSH_CASE
8781 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8785 /* Select which version we will use */
8786 static int run_and_free_list(struct pipe *pi)
8789 debug_printf_exec("run_and_free_list entered\n");
8790 if (!G.o_opt[OPT_O_NOEXEC]) {
8791 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8792 rcode = run_list(pi);
8794 /* free_pipe_list has the side effect of clearing memory.
8795 * In the long run that function can be merged with run_list,
8796 * but doing that now would hobble the debugging effort. */
8798 debug_printf_exec("run_and_free_list return %d\n", rcode);
8803 static void install_sighandlers(unsigned mask)
8805 sighandler_t old_handler;
8807 while ((mask >>= 1) != 0) {
8811 old_handler = install_sighandler(sig, pick_sighandler(sig));
8812 /* POSIX allows shell to re-enable SIGCHLD
8813 * even if it was SIG_IGN on entry.
8814 * Therefore we skip IGN check for it:
8818 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8819 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8821 //if (sig == SIGHUP) continue; - TODO?
8822 if (old_handler == SIG_IGN) {
8823 /* oops... restore back to IGN, and record this fact */
8824 install_sighandler(sig, old_handler);
8825 #if ENABLE_HUSH_TRAP
8827 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8829 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8835 /* Called a few times only (or even once if "sh -c") */
8836 static void install_special_sighandlers(void)
8840 /* Which signals are shell-special? */
8841 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8842 if (G_interactive_fd) {
8843 mask |= SPECIAL_INTERACTIVE_SIGS;
8844 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8845 mask |= SPECIAL_JOBSTOP_SIGS;
8847 /* Careful, do not re-install handlers we already installed */
8848 if (G.special_sig_mask != mask) {
8849 unsigned diff = mask & ~G.special_sig_mask;
8850 G.special_sig_mask = mask;
8851 install_sighandlers(diff);
8857 /* Set handlers to restore tty pgrp and exit */
8858 static void install_fatal_sighandlers(void)
8862 /* We will restore tty pgrp on these signals */
8864 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8865 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8866 + (1 << SIGBUS ) * HUSH_DEBUG
8867 + (1 << SIGSEGV) * HUSH_DEBUG
8868 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8870 /* bash 3.2 seems to handle these just like 'fatal' ones */
8873 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8874 * if we aren't interactive... but in this case
8875 * we never want to restore pgrp on exit, and this fn is not called
8877 /*+ (1 << SIGHUP )*/
8878 /*+ (1 << SIGTERM)*/
8879 /*+ (1 << SIGINT )*/
8881 G_fatal_sig_mask = mask;
8883 install_sighandlers(mask);
8887 static int set_mode(int state, char mode, const char *o_opt)
8892 G.o_opt[OPT_O_NOEXEC] = state;
8895 IF_HUSH_MODE_X(G_x_mode = state;)
8899 /* "set -+o" without parameter.
8900 * in bash, set -o produces this output:
8904 * We always use the second form.
8906 const char *p = o_opt_strings;
8909 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8915 idx = index_in_strings(o_opt_strings, o_opt);
8917 G.o_opt[idx] = state;
8921 G.o_opt[OPT_O_ERREXIT] = state;
8924 return EXIT_FAILURE;
8926 return EXIT_SUCCESS;
8929 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8930 int hush_main(int argc, char **argv)
8933 OPT_login = (1 << 0),
8937 unsigned builtin_argc;
8939 struct variable *cur_var;
8940 struct variable *shell_ver;
8943 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8944 G.last_exitcode = EXIT_SUCCESS;
8946 #if ENABLE_HUSH_FAST
8947 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8950 G.argv0_for_re_execing = argv[0];
8953 /* Deal with HUSH_VERSION */
8954 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8955 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8956 shell_ver = xzalloc(sizeof(*shell_ver));
8957 shell_ver->flg_export = 1;
8958 shell_ver->flg_read_only = 1;
8959 /* Code which handles ${var<op>...} needs writable values for all variables,
8960 * therefore we xstrdup: */
8961 shell_ver->varstr = xstrdup(hush_version_str);
8963 /* Create shell local variables from the values
8964 * currently living in the environment */
8965 G.top_var = shell_ver;
8966 cur_var = G.top_var;
8969 char *value = strchr(*e, '=');
8970 if (value) { /* paranoia */
8971 cur_var->next = xzalloc(sizeof(*cur_var));
8972 cur_var = cur_var->next;
8973 cur_var->varstr = *e;
8974 cur_var->max_len = strlen(*e);
8975 cur_var->flg_export = 1;
8979 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8980 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8981 putenv(shell_ver->varstr);
8984 set_pwd_var(SETFLAG_EXPORT);
8986 #if BASH_HOSTNAME_VAR
8987 /* Set (but not export) HOSTNAME unless already set */
8988 if (!get_local_var_value("HOSTNAME")) {
8991 set_local_var_from_halves("HOSTNAME", uts.nodename);
8993 /* bash also exports SHLVL and _,
8994 * and sets (but doesn't export) the following variables:
8996 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8997 * BASH_VERSION='3.2.0(1)-release'
8999 * MACHTYPE=i386-pc-linux-gnu
9001 * PPID=<NNNNN> - we also do it elsewhere
9012 * PIPESTATUS=([0]="0")
9013 * HISTFILE=/<xxx>/.bash_history
9017 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9019 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9031 if (BASH_LINENO_VAR) {
9032 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9033 set_local_var(p, /*flags*/ 0);
9034 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9038 #if ENABLE_FEATURE_EDITING
9039 G.line_input_state = new_line_input_t(FOR_SHELL);
9042 /* Initialize some more globals to non-zero values */
9043 cmdedit_update_prompt();
9045 die_func = restore_ttypgrp_and__exit;
9047 /* Shell is non-interactive at first. We need to call
9048 * install_special_sighandlers() if we are going to execute "sh <script>",
9049 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9050 * If we later decide that we are interactive, we run install_special_sighandlers()
9051 * in order to intercept (more) signals.
9055 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9056 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9059 opt = getopt(argc, argv, "+c:exinsl"
9062 # if ENABLE_HUSH_FUNCTIONS
9072 * sh ... -c 'script'
9073 * sh ... -c 'script' ARG0 [ARG1...]
9074 * On NOMMU, if builtin_argc != 0,
9075 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9076 * "" needs to be replaced with NULL
9077 * and BARGV vector fed to builtin function.
9078 * Note: the form without ARG0 never happens:
9079 * sh ... -c 'builtin' BARGV... ""
9082 G.root_pid = getpid();
9083 G.root_ppid = getppid();
9085 G.global_argv = argv + optind;
9086 G.global_argc = argc - optind;
9088 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9089 const struct built_in_command *x;
9091 install_special_sighandlers();
9092 x = find_builtin(optarg);
9093 if (x) { /* paranoia */
9094 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9095 G.global_argv += builtin_argc;
9096 G.global_argv[-1] = NULL; /* replace "" */
9098 G.last_exitcode = x->b_function(argv + optind - 1);
9102 if (!G.global_argv[0]) {
9103 /* -c 'script' (no params): prevent empty $0 */
9104 G.global_argv--; /* points to argv[i] of 'script' */
9105 G.global_argv[0] = argv[0];
9107 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
9108 install_special_sighandlers();
9109 parse_and_run_string(optarg);
9112 /* Well, we cannot just declare interactiveness,
9113 * we have to have some stuff (ctty, etc) */
9114 /* G_interactive_fd++; */
9117 /* "-s" means "read from stdin", but this is how we always
9118 * operate, so simply do nothing here. */
9124 case '<': /* "big heredoc" support */
9125 full_write1_str(optarg);
9128 unsigned long long empty_trap_mask;
9130 G.root_pid = bb_strtou(optarg, &optarg, 16);
9132 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9134 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9136 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
9138 builtin_argc = bb_strtou(optarg, &optarg, 16);
9140 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9141 if (empty_trap_mask != 0) {
9142 IF_HUSH_TRAP(int sig;)
9143 install_special_sighandlers();
9144 # if ENABLE_HUSH_TRAP
9145 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9146 for (sig = 1; sig < NSIG; sig++) {
9147 if (empty_trap_mask & (1LL << sig)) {
9148 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9149 install_sighandler(sig, SIG_IGN);
9154 # if ENABLE_HUSH_LOOPS
9156 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
9162 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9164 # if ENABLE_HUSH_FUNCTIONS
9166 struct function *funcp = new_function(optarg);
9167 /* funcp->name is already set to optarg */
9168 /* funcp->body is set to NULL. It's a special case. */
9169 funcp->body_as_string = argv[optind];
9178 if (set_mode(1, opt, NULL) == 0) /* no error */
9182 fprintf(stderr, "Usage: sh [FILE]...\n"
9183 " or: sh -c command [args]...\n\n");
9189 } /* option parsing loop */
9191 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9192 G.global_argc = argc - (optind - 1);
9193 G.global_argv = argv + (optind - 1);
9194 G.global_argv[0] = argv[0];
9197 G.root_pid = getpid();
9198 G.root_ppid = getppid();
9201 /* If we are login shell... */
9202 if (flags & OPT_login) {
9204 debug_printf("sourcing /etc/profile\n");
9205 input = fopen_for_read("/etc/profile");
9206 if (input != NULL) {
9207 remember_FILE(input);
9208 install_special_sighandlers();
9209 parse_and_run_file(input);
9210 fclose_and_forget(input);
9212 /* bash: after sourcing /etc/profile,
9213 * tries to source (in the given order):
9214 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9215 * stopping on first found. --noprofile turns this off.
9216 * bash also sources ~/.bash_logout on exit.
9217 * If called as sh, skips .bash_XXX files.
9221 if (G.global_argv[1]) {
9224 * "bash <script>" (which is never interactive (unless -i?))
9225 * sources $BASH_ENV here (without scanning $PATH).
9226 * If called as sh, does the same but with $ENV.
9227 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9231 debug_printf("running script '%s'\n", G.global_argv[0]);
9232 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9233 input = xfopen_for_read(G.global_argv[0]);
9234 xfunc_error_retval = 1;
9235 remember_FILE(input);
9236 install_special_sighandlers();
9237 parse_and_run_file(input);
9238 #if ENABLE_FEATURE_CLEAN_UP
9239 fclose_and_forget(input);
9244 /* Up to here, shell was non-interactive. Now it may become one.
9245 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9248 /* A shell is interactive if the '-i' flag was given,
9249 * or if all of the following conditions are met:
9251 * no arguments remaining or the -s flag given
9252 * standard input is a terminal
9253 * standard output is a terminal
9254 * Refer to Posix.2, the description of the 'sh' utility.
9257 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9258 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9259 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9260 if (G_saved_tty_pgrp < 0)
9261 G_saved_tty_pgrp = 0;
9263 /* try to dup stdin to high fd#, >= 255 */
9264 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9265 if (G_interactive_fd < 0) {
9266 /* try to dup to any fd */
9267 G_interactive_fd = dup(STDIN_FILENO);
9268 if (G_interactive_fd < 0) {
9270 G_interactive_fd = 0;
9271 G_saved_tty_pgrp = 0;
9274 // TODO: track & disallow any attempts of user
9275 // to (inadvertently) close/redirect G_interactive_fd
9277 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9278 if (G_interactive_fd) {
9279 close_on_exec_on(G_interactive_fd);
9281 if (G_saved_tty_pgrp) {
9282 /* If we were run as 'hush &', sleep until we are
9283 * in the foreground (tty pgrp == our pgrp).
9284 * If we get started under a job aware app (like bash),
9285 * make sure we are now in charge so we don't fight over
9286 * who gets the foreground */
9288 pid_t shell_pgrp = getpgrp();
9289 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9290 if (G_saved_tty_pgrp == shell_pgrp)
9292 /* send TTIN to ourself (should stop us) */
9293 kill(- shell_pgrp, SIGTTIN);
9297 /* Install more signal handlers */
9298 install_special_sighandlers();
9300 if (G_saved_tty_pgrp) {
9301 /* Set other signals to restore saved_tty_pgrp */
9302 install_fatal_sighandlers();
9303 /* Put ourselves in our own process group
9304 * (bash, too, does this only if ctty is available) */
9305 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9306 /* Grab control of the terminal */
9307 tcsetpgrp(G_interactive_fd, getpid());
9309 enable_restore_tty_pgrp_on_exit();
9311 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9313 const char *hp = get_local_var_value("HISTFILE");
9315 hp = get_local_var_value("HOME");
9317 hp = concat_path_file(hp, ".hush_history");
9322 G.line_input_state->hist_file = hp;
9323 //set_local_var(xasprintf("HISTFILE=%s", ...));
9325 # if ENABLE_FEATURE_SH_HISTFILESIZE
9326 hp = get_local_var_value("HISTFILESIZE");
9327 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9332 install_special_sighandlers();
9334 #elif ENABLE_HUSH_INTERACTIVE
9335 /* No job control compiled in, only prompt/line editing */
9336 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9337 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9338 if (G_interactive_fd < 0) {
9339 /* try to dup to any fd */
9340 G_interactive_fd = dup(STDIN_FILENO);
9341 if (G_interactive_fd < 0)
9343 G_interactive_fd = 0;
9346 if (G_interactive_fd) {
9347 close_on_exec_on(G_interactive_fd);
9349 install_special_sighandlers();
9351 /* We have interactiveness code disabled */
9352 install_special_sighandlers();
9355 * if interactive but not a login shell, sources ~/.bashrc
9356 * (--norc turns this off, --rcfile <file> overrides)
9359 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9360 /* note: ash and hush share this string */
9361 printf("\n\n%s %s\n"
9362 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9365 "hush - the humble shell"
9369 parse_and_run_file(stdin);
9372 hush_exit(G.last_exitcode);
9379 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9384 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9385 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9387 int argc = string_array_len(argv);
9388 return applet_main_func(argc, argv);
9391 #if ENABLE_HUSH_TEST || BASH_TEST2
9392 static int FAST_FUNC builtin_test(char **argv)
9394 return run_applet_main(argv, test_main);
9397 #if ENABLE_HUSH_ECHO
9398 static int FAST_FUNC builtin_echo(char **argv)
9400 return run_applet_main(argv, echo_main);
9403 #if ENABLE_HUSH_PRINTF
9404 static int FAST_FUNC builtin_printf(char **argv)
9406 return run_applet_main(argv, printf_main);
9410 #if ENABLE_HUSH_HELP
9411 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9413 const struct built_in_command *x;
9416 "Built-in commands:\n"
9417 "------------------\n");
9418 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9420 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9422 return EXIT_SUCCESS;
9426 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9427 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9429 show_history(G.line_input_state);
9430 return EXIT_SUCCESS;
9434 static char **skip_dash_dash(char **argv)
9437 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9442 static int FAST_FUNC builtin_cd(char **argv)
9446 argv = skip_dash_dash(argv);
9448 if (newdir == NULL) {
9449 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9450 * bash says "bash: cd: HOME not set" and does nothing
9453 const char *home = get_local_var_value("HOME");
9454 newdir = home ? home : "/";
9456 if (chdir(newdir)) {
9457 /* Mimic bash message exactly */
9458 bb_perror_msg("cd: %s", newdir);
9459 return EXIT_FAILURE;
9461 /* Read current dir (get_cwd(1) is inside) and set PWD.
9462 * Note: do not enforce exporting. If PWD was unset or unexported,
9463 * set it again, but do not export. bash does the same.
9465 set_pwd_var(/*flag:*/ 0);
9466 return EXIT_SUCCESS;
9469 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9472 return EXIT_SUCCESS;
9475 static int FAST_FUNC builtin_eval(char **argv)
9477 int rcode = EXIT_SUCCESS;
9479 argv = skip_dash_dash(argv);
9484 /* "The eval utility shall construct a command by
9485 * concatenating arguments together, separating
9486 * each with a <space> character."
9492 len += strlen(*pp) + 1;
9494 str = p = xmalloc(len);
9504 * eval "echo Hi; done" ("done" is syntax error):
9505 * "echo Hi" will not execute too.
9507 parse_and_run_string(str ? str : argv[0]);
9509 rcode = G.last_exitcode;
9514 static int FAST_FUNC builtin_exec(char **argv)
9516 argv = skip_dash_dash(argv);
9517 if (argv[0] == NULL)
9518 return EXIT_SUCCESS; /* bash does this */
9520 /* Careful: we can end up here after [v]fork. Do not restore
9521 * tty pgrp then, only top-level shell process does that */
9522 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9523 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9525 /* Saved-redirect fds, script fds and G_interactive_fd are still
9526 * open here. However, they are all CLOEXEC, and execv below
9527 * closes them. Try interactive "exec ls -l /proc/self/fd",
9528 * it should show no extra open fds in the "ls" process.
9529 * If we'd try to run builtins/NOEXECs, this would need improving.
9531 //close_saved_fds_and_FILE_fds();
9533 /* TODO: if exec fails, bash does NOT exit! We do.
9534 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9535 * and tcsetpgrp, and this is inherently racy.
9537 execvp_or_die(argv);
9540 static int FAST_FUNC builtin_exit(char **argv)
9542 debug_printf_exec("%s()\n", __func__);
9544 /* interactive bash:
9545 * # trap "echo EEE" EXIT
9548 * There are stopped jobs.
9549 * (if there are _stopped_ jobs, running ones don't count)
9552 * EEE (then bash exits)
9554 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9557 /* note: EXIT trap is run by hush_exit */
9558 argv = skip_dash_dash(argv);
9559 if (argv[0] == NULL)
9560 hush_exit(G.last_exitcode);
9561 /* mimic bash: exit 123abc == exit 255 + error msg */
9562 xfunc_error_retval = 255;
9563 /* bash: exit -2 == exit 254, no error msg */
9564 hush_exit(xatoi(argv[0]) & 0xff);
9567 #if ENABLE_HUSH_TYPE
9568 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9569 static int FAST_FUNC builtin_type(char **argv)
9571 int ret = EXIT_SUCCESS;
9577 if (0) {} /* make conditional compile easier below */
9578 /*else if (find_alias(*argv))
9579 type = "an alias";*/
9580 #if ENABLE_HUSH_FUNCTIONS
9581 else if (find_function(*argv))
9582 type = "a function";
9584 else if (find_builtin(*argv))
9585 type = "a shell builtin";
9586 else if ((path = find_in_path(*argv)) != NULL)
9589 bb_error_msg("type: %s: not found", *argv);
9594 printf("%s is %s\n", *argv, type);
9602 #if ENABLE_HUSH_READ
9603 /* Interruptibility of read builtin in bash
9604 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9606 * Empty trap makes read ignore corresponding signal, for any signal.
9609 * - terminates non-interactive shell;
9610 * - interrupts read in interactive shell;
9611 * if it has non-empty trap:
9612 * - executes trap and returns to command prompt in interactive shell;
9613 * - executes trap and returns to read in non-interactive shell;
9615 * - is ignored (does not interrupt) read in interactive shell;
9616 * - terminates non-interactive shell;
9617 * if it has non-empty trap:
9618 * - executes trap and returns to read;
9620 * - terminates shell (regardless of interactivity);
9621 * if it has non-empty trap:
9622 * - executes trap and returns to read;
9623 * SIGCHLD from children:
9624 * - does not interrupt read regardless of interactivity:
9625 * try: sleep 1 & read x; echo $x
9627 static int FAST_FUNC builtin_read(char **argv)
9634 char *opt_d = NULL; /* optimized out if !BASH */
9638 /* "!": do not abort on errors.
9639 * Option string must start with "sr" to match BUILTIN_READ_xxx
9641 read_flags = getopt32(argv,
9643 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9645 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9648 if (read_flags == (uint32_t)-1)
9649 return EXIT_FAILURE;
9651 ifs = get_local_var_value("IFS"); /* can be NULL */
9654 r = shell_builtin_read(set_local_var_from_halves,
9665 if ((uintptr_t)r == 1 && errno == EINTR) {
9666 unsigned sig = check_and_run_traps();
9671 if ((uintptr_t)r > 1) {
9672 bb_error_msg("%s", r);
9673 r = (char*)(uintptr_t)1;
9676 return (uintptr_t)r;
9680 #if ENABLE_HUSH_UMASK
9681 static int FAST_FUNC builtin_umask(char **argv)
9688 argv = skip_dash_dash(argv);
9690 mode_t old_mask = mask;
9692 /* numeric umasks are taken as-is */
9693 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9694 if (!isdigit(argv[0][0]))
9696 mask = bb_parse_mode(argv[0], mask);
9697 if (!isdigit(argv[0][0]))
9699 if ((unsigned)mask > 0777) {
9702 * bash: umask: 'q': invalid symbolic mode operator
9703 * bash: umask: 999: octal number out of range
9705 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9710 printf("%04o\n", (unsigned) mask);
9711 /* fall through and restore mask which we set to 0 */
9715 return !rc; /* rc != 0 - success */
9719 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9720 static void print_escaped(const char *s)
9725 const char *p = strchrnul(s, '\'');
9726 /* print 'xxxx', possibly just '' */
9727 printf("'%.*s'", (int)(p - s), s);
9732 /* s points to '; print "'''...'''" */
9734 do putchar('\''); while (*++s == '\'');
9740 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9741 static int helper_export_local(char **argv, unsigned flags)
9745 char *name_end = strchrnul(name, '=');
9747 /* So far we do not check that name is valid (TODO?) */
9749 if (*name_end == '\0') {
9750 struct variable *var, **vpp;
9752 vpp = get_ptr_to_local_var(name, name_end - name);
9753 var = vpp ? *vpp : NULL;
9755 if (flags & SETFLAG_UNEXPORT) {
9756 /* export -n NAME (without =VALUE) */
9758 var->flg_export = 0;
9759 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9761 } /* else: export -n NOT_EXISTING_VAR: no-op */
9764 if (flags & SETFLAG_EXPORT) {
9765 /* export NAME (without =VALUE) */
9767 var->flg_export = 1;
9768 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9769 putenv(var->varstr);
9773 if (flags & SETFLAG_MAKE_RO) {
9774 /* readonly NAME (without =VALUE) */
9776 var->flg_read_only = 1;
9780 # if ENABLE_HUSH_LOCAL
9781 /* Is this "local" bltin? */
9782 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9783 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9784 if (var && var->func_nest_level == lvl) {
9785 /* "local x=abc; ...; local x" - ignore second local decl */
9790 /* Exporting non-existing variable.
9791 * bash does not put it in environment,
9792 * but remembers that it is exported,
9793 * and does put it in env when it is set later.
9794 * We just set it to "" and export.
9796 /* Or, it's "local NAME" (without =VALUE).
9797 * bash sets the value to "".
9799 /* Or, it's "readonly NAME" (without =VALUE).
9800 * bash remembers NAME and disallows its creation
9803 name = xasprintf("%s=", name);
9805 /* (Un)exporting/making local NAME=VALUE */
9806 name = xstrdup(name);
9808 if (set_local_var(name, flags))
9809 return EXIT_FAILURE;
9811 return EXIT_SUCCESS;
9815 #if ENABLE_HUSH_EXPORT
9816 static int FAST_FUNC builtin_export(char **argv)
9818 unsigned opt_unexport;
9820 #if ENABLE_HUSH_EXPORT_N
9821 /* "!": do not abort on errors */
9822 opt_unexport = getopt32(argv, "!n");
9823 if (opt_unexport == (uint32_t)-1)
9824 return EXIT_FAILURE;
9831 if (argv[0] == NULL) {
9838 /* ash emits: export VAR='VAL'
9839 * bash: declare -x VAR="VAL"
9840 * we follow ash example */
9841 const char *s = *e++;
9842 const char *p = strchr(s, '=');
9844 if (!p) /* wtf? take next variable */
9847 printf("export %.*s", (int)(p - s) + 1, s);
9848 print_escaped(p + 1);
9852 /*fflush_all(); - done after each builtin anyway */
9854 return EXIT_SUCCESS;
9857 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9861 #if ENABLE_HUSH_LOCAL
9862 static int FAST_FUNC builtin_local(char **argv)
9864 if (G.func_nest_level == 0) {
9865 bb_error_msg("%s: not in a function", argv[0]);
9866 return EXIT_FAILURE; /* bash compat */
9869 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9873 #if ENABLE_HUSH_READONLY
9874 static int FAST_FUNC builtin_readonly(char **argv)
9877 if (*argv == NULL) {
9878 /* bash: readonly [-p]: list all readonly VARs
9879 * (-p has no effect in bash)
9882 for (e = G.top_var; e; e = e->next) {
9883 if (e->flg_read_only) {
9884 //TODO: quote value: readonly VAR='VAL'
9885 printf("readonly %s\n", e->varstr);
9888 return EXIT_SUCCESS;
9890 return helper_export_local(argv, SETFLAG_MAKE_RO);
9894 #if ENABLE_HUSH_UNSET
9895 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9896 static int FAST_FUNC builtin_unset(char **argv)
9901 /* "!": do not abort on errors */
9902 /* "+": stop at 1st non-option */
9903 opts = getopt32(argv, "!+vf");
9904 if (opts == (unsigned)-1)
9905 return EXIT_FAILURE;
9907 bb_error_msg("unset: -v and -f are exclusive");
9908 return EXIT_FAILURE;
9914 if (!(opts & 2)) { /* not -f */
9915 if (unset_local_var(*argv)) {
9916 /* unset <nonexistent_var> doesn't fail.
9917 * Error is when one tries to unset RO var.
9918 * Message was printed by unset_local_var. */
9922 # if ENABLE_HUSH_FUNCTIONS
9934 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9935 * built-in 'set' handler
9937 * set [-abCefhmnuvx] [-o option] [argument...]
9938 * set [+abCefhmnuvx] [+o option] [argument...]
9939 * set -- [argument...]
9942 * Implementations shall support the options in both their hyphen and
9943 * plus-sign forms. These options can also be specified as options to sh.
9945 * Write out all variables and their values: set
9946 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9947 * Turn on the -x and -v options: set -xv
9948 * Unset all positional parameters: set --
9949 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9950 * Set the positional parameters to the expansion of x, even if x expands
9951 * with a leading '-' or '+': set -- $x
9953 * So far, we only support "set -- [argument...]" and some of the short names.
9955 static int FAST_FUNC builtin_set(char **argv)
9958 char **pp, **g_argv;
9959 char *arg = *++argv;
9963 for (e = G.top_var; e; e = e->next)
9965 return EXIT_SUCCESS;
9969 if (strcmp(arg, "--") == 0) {
9973 if (arg[0] != '+' && arg[0] != '-')
9975 for (n = 1; arg[n]; ++n) {
9976 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9978 if (arg[n] == 'o' && argv[1])
9981 } while ((arg = *++argv) != NULL);
9982 /* Now argv[0] is 1st argument */
9985 return EXIT_SUCCESS;
9988 /* NB: G.global_argv[0] ($0) is never freed/changed */
9989 g_argv = G.global_argv;
9990 if (G.global_args_malloced) {
9996 G.global_args_malloced = 1;
9997 pp = xzalloc(sizeof(pp[0]) * 2);
9998 pp[0] = g_argv[0]; /* retain $0 */
10001 /* This realloc's G.global_argv */
10002 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10004 G.global_argc = 1 + string_array_len(pp + 1);
10006 return EXIT_SUCCESS;
10008 /* Nothing known, so abort */
10010 bb_error_msg("%s: %s: invalid option", "set", arg);
10011 return EXIT_FAILURE;
10015 static int FAST_FUNC builtin_shift(char **argv)
10018 argv = skip_dash_dash(argv);
10020 n = bb_strtou(argv[0], NULL, 10);
10021 if (errno || n < 0) {
10022 /* shared string with ash.c */
10023 bb_error_msg("Illegal number: %s", argv[0]);
10025 * ash aborts in this case.
10026 * bash prints error message and set $? to 1.
10027 * Interestingly, for "shift 99999" bash does not
10028 * print error message, but does set $? to 1
10029 * (and does no shifting at all).
10033 if (n >= 0 && n < G.global_argc) {
10034 if (G_global_args_malloced) {
10037 free(G.global_argv[m++]);
10039 G.global_argc -= n;
10040 memmove(&G.global_argv[1], &G.global_argv[n+1],
10041 G.global_argc * sizeof(G.global_argv[0]));
10042 return EXIT_SUCCESS;
10044 return EXIT_FAILURE;
10047 #if ENABLE_HUSH_GETOPTS
10048 static int FAST_FUNC builtin_getopts(char **argv)
10050 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10053 If a required argument is not found, and getopts is not silent,
10054 a question mark (?) is placed in VAR, OPTARG is unset, and a
10055 diagnostic message is printed. If getopts is silent, then a
10056 colon (:) is placed in VAR and OPTARG is set to the option
10059 Test that VAR is a valid variable name?
10061 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10064 const char *cp, *optstring, *var;
10065 int c, n, exitcode, my_opterr;
10068 optstring = *++argv;
10069 if (!optstring || !(var = *++argv)) {
10070 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10071 return EXIT_FAILURE;
10075 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10077 argv = G.global_argv;
10081 if (optstring[0] != ':') {
10082 cp = get_local_var_value("OPTERR");
10083 /* 0 if "OPTERR=0", 1 otherwise */
10084 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
10087 /* getopts stops on first non-option. Add "+" to force that */
10088 /*if (optstring[0] != '+')*/ {
10089 char *s = alloca(strlen(optstring) + 2);
10090 sprintf(s, "+%s", optstring);
10094 /* Naively, now we should just
10095 * cp = get_local_var_value("OPTIND");
10096 * optind = cp ? atoi(cp) : 0;
10098 * opterr = my_opterr;
10099 * c = getopt(string_array_len(argv), argv, optstring);
10100 * and be done? Not so fast...
10101 * Unlike normal getopt() usage in C programs, here
10102 * each successive call will (usually) have the same argv[] CONTENTS,
10103 * but not the ADDRESSES. Worse yet, it's possible that between
10104 * invocations of "getopts", there will be calls to shell builtins
10105 * which use getopt() internally. Example:
10106 * while getopts "abc" RES -a -bc -abc de; do
10109 * This would not work correctly: getopt() call inside "unset"
10110 * modifies internal libc state which is tracking position in
10111 * multi-option strings ("-abc"). At best, it can skip options
10112 * or return the same option infinitely. With glibc implementation
10113 * of getopt(), it would use outright invalid pointers and return
10114 * garbage even _without_ "unset" mangling internal state.
10116 * We resort to resetting getopt() state and calling it N times,
10117 * until we get Nth result (or failure).
10118 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10122 n = string_array_len(argv);
10125 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10126 c = getopt(n, argv, optstring);
10130 } while (count <= G.getopt_count);
10132 /* Set OPTIND. Prevent resetting of the magic counter! */
10133 set_local_var_from_halves("OPTIND", utoa(optind));
10134 G.getopt_count = count; /* "next time, give me N+1'th result" */
10135 GETOPT_RESET(); /* just in case */
10138 /* Always set or unset, never left as-is, even on exit/error:
10139 * "If no option was found, or if the option that was found
10140 * does not have an option-argument, OPTARG shall be unset."
10144 /* If ":optstring" and unknown option is seen,
10145 * it is stored to OPTARG.
10147 if (optstring[1] == ':') {
10153 set_local_var_from_halves("OPTARG", cp);
10155 unset_local_var("OPTARG");
10157 /* Convert -1 to "?" */
10158 exitcode = EXIT_SUCCESS;
10159 if (c < 0) { /* -1: end of options */
10160 exitcode = EXIT_FAILURE;
10166 set_local_var_from_halves(var, cbuf);
10172 static int FAST_FUNC builtin_source(char **argv)
10174 char *arg_path, *filename;
10177 char *args_need_save;
10178 #if ENABLE_HUSH_FUNCTIONS
10182 argv = skip_dash_dash(argv);
10183 filename = argv[0];
10185 /* bash says: "bash: .: filename argument required" */
10186 return 2; /* bash compat */
10189 if (!strchr(filename, '/')) {
10190 arg_path = find_in_path(filename);
10192 filename = arg_path;
10194 input = remember_FILE(fopen_or_warn(filename, "r"));
10197 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10198 /* POSIX: non-interactive shell should abort here,
10199 * not merely fail. So far no one complained :)
10201 return EXIT_FAILURE;
10204 #if ENABLE_HUSH_FUNCTIONS
10205 sv_flg = G_flag_return_in_progress;
10206 /* "we are inside sourced file, ok to use return" */
10207 G_flag_return_in_progress = -1;
10209 args_need_save = argv[1]; /* used as a boolean variable */
10210 if (args_need_save)
10211 save_and_replace_G_args(&sv, argv);
10213 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10214 G.last_exitcode = 0;
10215 parse_and_run_file(input);
10216 fclose_and_forget(input);
10218 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10219 restore_G_args(&sv, argv);
10220 #if ENABLE_HUSH_FUNCTIONS
10221 G_flag_return_in_progress = sv_flg;
10224 return G.last_exitcode;
10227 #if ENABLE_HUSH_TRAP
10228 static int FAST_FUNC builtin_trap(char **argv)
10234 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10239 /* No args: print all trapped */
10240 for (i = 0; i < NSIG; ++i) {
10242 printf("trap -- ");
10243 print_escaped(G_traps[i]);
10244 /* note: bash adds "SIG", but only if invoked
10245 * as "bash". If called as "sh", or if set -o posix,
10246 * then it prints short signal names.
10247 * We are printing short names: */
10248 printf(" %s\n", get_signame(i));
10251 /*fflush_all(); - done after each builtin anyway */
10252 return EXIT_SUCCESS;
10256 /* If first arg is a number: reset all specified signals */
10257 sig = bb_strtou(*argv, NULL, 10);
10261 ret = EXIT_SUCCESS;
10263 sighandler_t handler;
10265 sig = get_signum(*argv++);
10267 ret = EXIT_FAILURE;
10268 /* Mimic bash message exactly */
10269 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
10273 free(G_traps[sig]);
10274 G_traps[sig] = xstrdup(new_cmd);
10276 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
10277 get_signame(sig), sig, G_traps[sig]);
10279 /* There is no signal for 0 (EXIT) */
10284 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10286 /* We are removing trap handler */
10287 handler = pick_sighandler(sig);
10288 install_sighandler(sig, handler);
10293 if (!argv[1]) { /* no second arg */
10294 bb_error_msg("trap: invalid arguments");
10295 return EXIT_FAILURE;
10298 /* First arg is "-": reset all specified to default */
10299 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10300 /* Everything else: set arg as signal handler
10301 * (includes "" case, which ignores signal) */
10302 if (argv[0][0] == '-') {
10303 if (argv[0][1] == '\0') { /* "-" */
10304 /* new_cmd remains NULL: "reset these sigs" */
10307 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10310 /* else: "-something", no special meaning */
10315 goto process_sig_list;
10319 #if ENABLE_HUSH_JOB
10320 static struct pipe *parse_jobspec(const char *str)
10325 if (sscanf(str, "%%%u", &jobnum) != 1) {
10327 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10329 bb_error_msg("bad argument '%s'", str);
10332 /* It is "%%", "%+" or "%" - current job */
10333 jobnum = G.last_jobid;
10335 bb_error_msg("no current job");
10339 for (pi = G.job_list; pi; pi = pi->next) {
10340 if (pi->jobid == jobnum) {
10344 bb_error_msg("%u: no such job", jobnum);
10348 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10351 const char *status_string;
10353 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10354 for (job = G.job_list; job; job = job->next) {
10355 if (job->alive_cmds == job->stopped_cmds)
10356 status_string = "Stopped";
10358 status_string = "Running";
10360 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10363 clean_up_last_dead_job();
10365 return EXIT_SUCCESS;
10368 /* built-in 'fg' and 'bg' handler */
10369 static int FAST_FUNC builtin_fg_bg(char **argv)
10374 if (!G_interactive_fd)
10375 return EXIT_FAILURE;
10377 /* If they gave us no args, assume they want the last backgrounded task */
10379 for (pi = G.job_list; pi; pi = pi->next) {
10380 if (pi->jobid == G.last_jobid) {
10384 bb_error_msg("%s: no current job", argv[0]);
10385 return EXIT_FAILURE;
10388 pi = parse_jobspec(argv[1]);
10390 return EXIT_FAILURE;
10392 /* TODO: bash prints a string representation
10393 * of job being foregrounded (like "sleep 1 | cat") */
10394 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10395 /* Put the job into the foreground. */
10396 tcsetpgrp(G_interactive_fd, pi->pgrp);
10399 /* Restart the processes in the job */
10400 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10401 for (i = 0; i < pi->num_cmds; i++) {
10402 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10404 pi->stopped_cmds = 0;
10406 i = kill(- pi->pgrp, SIGCONT);
10408 if (errno == ESRCH) {
10409 delete_finished_job(pi);
10410 return EXIT_SUCCESS;
10412 bb_perror_msg("kill (SIGCONT)");
10415 if (argv[0][0] == 'f') {
10416 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10417 return checkjobs_and_fg_shell(pi);
10419 return EXIT_SUCCESS;
10423 #if ENABLE_HUSH_KILL
10424 static int FAST_FUNC builtin_kill(char **argv)
10428 # if ENABLE_HUSH_JOB
10429 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10437 if (argv[i][0] != '%')
10440 * "kill %N" - job kill
10441 * Converting to pgrp / pid kill
10443 pi = parse_jobspec(argv[i]);
10445 /* Eat bad jobspec */
10449 argv[j - 1] = argv[j];
10456 * In jobs started under job control, we signal
10457 * entire process group by kill -PGRP_ID.
10458 * This happens, f.e., in interactive shell.
10460 * Otherwise, we signal each child via
10461 * kill PID1 PID2 PID3.
10463 * sh -c 'sleep 1|sleep 1 & kill %1'
10464 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10465 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10467 n = G_interactive_fd ? 1 : pi->num_cmds;
10468 dst = alloca(n * sizeof(int)*4);
10470 if (G_interactive_fd)
10471 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10472 else for (j = 0; j < n; j++) {
10473 struct command *cmd = &pi->cmds[j];
10474 /* Skip exited members of the job */
10478 * kill_main has matching code to expect
10479 * leading space. Needed to not confuse
10480 * negative pids with "kill -SIGNAL_NO" syntax
10482 dst += sprintf(dst, " %u", (int)cmd->pid);
10485 } while (argv[++i]);
10489 if (argv[1] || ret == 0) {
10490 ret = run_applet_main(argv, kill_main);
10492 /* else: ret = 1, "kill %bad_jobspec" case */
10497 #if ENABLE_HUSH_WAIT
10498 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10499 #if !ENABLE_HUSH_JOB
10500 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10502 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10509 if (!sigisemptyset(&G.pending_set))
10512 /* waitpid is not interruptible by SA_RESTARTed
10513 * signals which we use. Thus, this ugly dance:
10516 /* Make sure possible SIGCHLD is stored in kernel's
10517 * pending signal mask before we call waitpid.
10518 * Or else we may race with SIGCHLD, lose it,
10519 * and get stuck in sigsuspend...
10521 sigfillset(&oldset); /* block all signals, remember old set */
10522 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10524 if (!sigisemptyset(&G.pending_set)) {
10525 /* Crap! we raced with some signal! */
10529 /*errno = 0; - checkjobs does this */
10530 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10531 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10532 debug_printf_exec("checkjobs:%d\n", ret);
10533 #if ENABLE_HUSH_JOB
10534 if (waitfor_pipe) {
10535 int rcode = job_exited_or_stopped(waitfor_pipe);
10536 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10539 sigprocmask(SIG_SETMASK, &oldset, NULL);
10544 /* if ECHILD, there are no children (ret is -1 or 0) */
10545 /* if ret == 0, no children changed state */
10546 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10547 if (errno == ECHILD || ret) {
10549 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10551 sigprocmask(SIG_SETMASK, &oldset, NULL);
10554 /* Wait for SIGCHLD or any other signal */
10555 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10556 /* Note: sigsuspend invokes signal handler */
10557 sigsuspend(&oldset);
10559 sigprocmask(SIG_SETMASK, &oldset, NULL);
10561 /* So, did we get a signal? */
10562 sig = check_and_run_traps();
10563 if (sig /*&& sig != SIGCHLD - always true */) {
10564 /* Do this for any (non-ignored) signal, not only for ^C */
10568 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10573 static int FAST_FUNC builtin_wait(char **argv)
10578 argv = skip_dash_dash(argv);
10579 if (argv[0] == NULL) {
10580 /* Don't care about wait results */
10581 /* Note 1: must wait until there are no more children */
10582 /* Note 2: must be interruptible */
10584 * $ sleep 3 & sleep 6 & wait
10585 * [1] 30934 sleep 3
10586 * [2] 30935 sleep 6
10589 * $ sleep 3 & sleep 6 & wait
10590 * [1] 30936 sleep 3
10591 * [2] 30937 sleep 6
10593 * ^C <-- after ~4 sec from keyboard
10596 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10600 pid_t pid = bb_strtou(*argv, NULL, 10);
10601 if (errno || pid <= 0) {
10602 #if ENABLE_HUSH_JOB
10603 if (argv[0][0] == '%') {
10604 struct pipe *wait_pipe;
10605 ret = 127; /* bash compat for bad jobspecs */
10606 wait_pipe = parse_jobspec(*argv);
10608 ret = job_exited_or_stopped(wait_pipe);
10610 ret = wait_for_child_or_signal(wait_pipe, 0);
10612 /* waiting on "last dead job" removes it */
10613 clean_up_last_dead_job();
10616 /* else: parse_jobspec() already emitted error msg */
10620 /* mimic bash message */
10621 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10622 ret = EXIT_FAILURE;
10623 continue; /* bash checks all argv[] */
10626 /* Do we have such child? */
10627 ret = waitpid(pid, &status, WNOHANG);
10631 if (errno == ECHILD) {
10632 if (pid == G.last_bg_pid) {
10633 /* "wait $!" but last bg task has already exited. Try:
10634 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10635 * In bash it prints exitcode 0, then 3.
10636 * In dash, it is 127.
10638 ret = G.last_bg_pid_exitcode;
10640 /* Example: "wait 1". mimic bash message */
10641 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10645 bb_perror_msg("wait %s", *argv);
10647 continue; /* bash checks all argv[] */
10650 /* Yes, and it still runs */
10651 ret = wait_for_child_or_signal(NULL, pid);
10653 /* Yes, and it just exited */
10654 process_wait_result(NULL, pid, status);
10655 ret = WEXITSTATUS(status);
10656 if (WIFSIGNALED(status))
10657 ret = 128 + WTERMSIG(status);
10665 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10666 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10669 def = bb_strtou(argv[1], NULL, 10);
10670 if (errno || def < def_min || argv[2]) {
10671 bb_error_msg("%s: bad arguments", argv[0]);
10679 #if ENABLE_HUSH_LOOPS
10680 static int FAST_FUNC builtin_break(char **argv)
10683 if (G.depth_of_loop == 0) {
10684 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10685 /* if we came from builtin_continue(), need to undo "= 1" */
10686 G.flag_break_continue = 0;
10687 return EXIT_SUCCESS; /* bash compat */
10689 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10691 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10692 if (depth == UINT_MAX)
10693 G.flag_break_continue = BC_BREAK;
10694 if (G.depth_of_loop < depth)
10695 G.depth_break_continue = G.depth_of_loop;
10697 return EXIT_SUCCESS;
10700 static int FAST_FUNC builtin_continue(char **argv)
10702 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10703 return builtin_break(argv);
10707 #if ENABLE_HUSH_FUNCTIONS
10708 static int FAST_FUNC builtin_return(char **argv)
10712 if (G_flag_return_in_progress != -1) {
10713 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10714 return EXIT_FAILURE; /* bash compat */
10717 G_flag_return_in_progress = 1;
10720 * out of range: wraps around at 256, does not error out
10721 * non-numeric param:
10722 * f() { false; return qwe; }; f; echo $?
10723 * bash: return: qwe: numeric argument required <== we do this
10724 * 255 <== we also do this
10726 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10731 #if ENABLE_HUSH_TIMES
10732 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10734 static const uint8_t times_tbl[] ALIGN1 = {
10735 ' ', offsetof(struct tms, tms_utime),
10736 '\n', offsetof(struct tms, tms_stime),
10737 ' ', offsetof(struct tms, tms_cutime),
10738 '\n', offsetof(struct tms, tms_cstime),
10745 clk_tck = bb_clk_tck();
10750 unsigned sec, frac;
10752 t = *(clock_t *)(((char *) &buf) + p[1]);
10754 frac = t % clk_tck;
10755 printf("%um%u.%03us%c",
10756 sec / 60, sec % 60,
10757 (frac * 1000) / clk_tck,
10762 return EXIT_SUCCESS;
10766 #if ENABLE_HUSH_MEMLEAK
10767 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10772 # ifdef M_TRIM_THRESHOLD
10773 /* Optional. Reduces probability of false positives */
10776 /* Crude attempt to find where "free memory" starts,
10777 * sans fragmentation. */
10779 l = (unsigned long)p;
10782 if (l < (unsigned long)p) l = (unsigned long)p;
10788 struct mallinfo mi = mallinfo();
10789 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10790 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10794 if (!G.memleak_value)
10795 G.memleak_value = l;
10797 l -= G.memleak_value;
10804 /* Exitcode is "how many kilobytes we leaked since 1st call" */