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;
942 struct FILE_list *FILE_list;
943 /* Which signals have non-DFL handler (even with no traps set)?
944 * Set at the start to:
945 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
946 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
947 * The rest is cleared right before execv syscalls.
948 * Other than these two times, never modified.
950 unsigned special_sig_mask;
952 unsigned fatal_sig_mask;
953 # define G_fatal_sig_mask (G.fatal_sig_mask)
955 # define G_fatal_sig_mask 0
958 char **traps; /* char *traps[NSIG] */
959 # define G_traps G.traps
961 # define G_traps ((char**)NULL)
963 sigset_t pending_set;
964 #if ENABLE_HUSH_MEMLEAK
965 unsigned long memleak_value;
971 #if ENABLE_FEATURE_EDITING
972 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
975 #define G (*ptr_to_globals)
976 /* Not #defining name to G.name - this quickly gets unwieldy
977 * (too many defines). Also, I actually prefer to see when a variable
978 * is global, thus "G." prefix is a useful hint */
979 #define INIT_G() do { \
980 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
981 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
982 sigfillset(&G.sa.sa_mask); \
983 G.sa.sa_flags = SA_RESTART; \
987 /* Function prototypes for builtins */
988 static int builtin_cd(char **argv) FAST_FUNC;
990 static int builtin_echo(char **argv) FAST_FUNC;
992 static int builtin_eval(char **argv) FAST_FUNC;
993 static int builtin_exec(char **argv) FAST_FUNC;
994 static int builtin_exit(char **argv) FAST_FUNC;
995 #if ENABLE_HUSH_EXPORT
996 static int builtin_export(char **argv) FAST_FUNC;
998 #if ENABLE_HUSH_READONLY
999 static int builtin_readonly(char **argv) FAST_FUNC;
1002 static int builtin_fg_bg(char **argv) FAST_FUNC;
1003 static int builtin_jobs(char **argv) FAST_FUNC;
1005 #if ENABLE_HUSH_GETOPTS
1006 static int builtin_getopts(char **argv) FAST_FUNC;
1008 #if ENABLE_HUSH_HELP
1009 static int builtin_help(char **argv) FAST_FUNC;
1011 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1012 static int builtin_history(char **argv) FAST_FUNC;
1014 #if ENABLE_HUSH_LOCAL
1015 static int builtin_local(char **argv) FAST_FUNC;
1017 #if ENABLE_HUSH_MEMLEAK
1018 static int builtin_memleak(char **argv) FAST_FUNC;
1020 #if ENABLE_HUSH_PRINTF
1021 static int builtin_printf(char **argv) FAST_FUNC;
1023 static int builtin_pwd(char **argv) FAST_FUNC;
1024 #if ENABLE_HUSH_READ
1025 static int builtin_read(char **argv) FAST_FUNC;
1028 static int builtin_set(char **argv) FAST_FUNC;
1030 static int builtin_shift(char **argv) FAST_FUNC;
1031 static int builtin_source(char **argv) FAST_FUNC;
1032 #if ENABLE_HUSH_TEST || BASH_TEST2
1033 static int builtin_test(char **argv) FAST_FUNC;
1035 #if ENABLE_HUSH_TRAP
1036 static int builtin_trap(char **argv) FAST_FUNC;
1038 #if ENABLE_HUSH_TYPE
1039 static int builtin_type(char **argv) FAST_FUNC;
1041 #if ENABLE_HUSH_TIMES
1042 static int builtin_times(char **argv) FAST_FUNC;
1044 static int builtin_true(char **argv) FAST_FUNC;
1045 #if ENABLE_HUSH_UMASK
1046 static int builtin_umask(char **argv) FAST_FUNC;
1048 #if ENABLE_HUSH_UNSET
1049 static int builtin_unset(char **argv) FAST_FUNC;
1051 #if ENABLE_HUSH_KILL
1052 static int builtin_kill(char **argv) FAST_FUNC;
1054 #if ENABLE_HUSH_WAIT
1055 static int builtin_wait(char **argv) FAST_FUNC;
1057 #if ENABLE_HUSH_LOOPS
1058 static int builtin_break(char **argv) FAST_FUNC;
1059 static int builtin_continue(char **argv) FAST_FUNC;
1061 #if ENABLE_HUSH_FUNCTIONS
1062 static int builtin_return(char **argv) FAST_FUNC;
1065 /* Table of built-in functions. They can be forked or not, depending on
1066 * context: within pipes, they fork. As simple commands, they do not.
1067 * When used in non-forking context, they can change global variables
1068 * in the parent shell process. If forked, of course they cannot.
1069 * For example, 'unset foo | whatever' will parse and run, but foo will
1070 * still be set at the end. */
1071 struct built_in_command {
1073 int (*b_function)(char **argv) FAST_FUNC;
1074 #if ENABLE_HUSH_HELP
1075 const char *b_descr;
1076 # define BLTIN(cmd, func, help) { cmd, func, help }
1078 # define BLTIN(cmd, func, help) { cmd, func }
1082 static const struct built_in_command bltins1[] = {
1083 BLTIN("." , builtin_source , "Run commands in file"),
1084 BLTIN(":" , builtin_true , NULL),
1086 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1088 #if ENABLE_HUSH_LOOPS
1089 BLTIN("break" , builtin_break , "Exit loop"),
1091 BLTIN("cd" , builtin_cd , "Change directory"),
1092 #if ENABLE_HUSH_LOOPS
1093 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1095 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1096 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1097 BLTIN("exit" , builtin_exit , NULL),
1098 #if ENABLE_HUSH_EXPORT
1099 BLTIN("export" , builtin_export , "Set environment variables"),
1102 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1104 #if ENABLE_HUSH_GETOPTS
1105 BLTIN("getopts" , builtin_getopts , NULL),
1107 #if ENABLE_HUSH_HELP
1108 BLTIN("help" , builtin_help , NULL),
1110 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1111 BLTIN("history" , builtin_history , "Show history"),
1114 BLTIN("jobs" , builtin_jobs , "List jobs"),
1116 #if ENABLE_HUSH_KILL
1117 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1119 #if ENABLE_HUSH_LOCAL
1120 BLTIN("local" , builtin_local , "Set local variables"),
1122 #if ENABLE_HUSH_MEMLEAK
1123 BLTIN("memleak" , builtin_memleak , NULL),
1125 #if ENABLE_HUSH_READ
1126 BLTIN("read" , builtin_read , "Input into variable"),
1128 #if ENABLE_HUSH_READONLY
1129 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1131 #if ENABLE_HUSH_FUNCTIONS
1132 BLTIN("return" , builtin_return , "Return from function"),
1135 BLTIN("set" , builtin_set , "Set positional parameters"),
1137 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1139 BLTIN("source" , builtin_source , NULL),
1141 #if ENABLE_HUSH_TIMES
1142 BLTIN("times" , builtin_times , NULL),
1144 #if ENABLE_HUSH_TRAP
1145 BLTIN("trap" , builtin_trap , "Trap signals"),
1147 BLTIN("true" , builtin_true , NULL),
1148 #if ENABLE_HUSH_TYPE
1149 BLTIN("type" , builtin_type , "Show command type"),
1151 #if ENABLE_HUSH_ULIMIT
1152 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1154 #if ENABLE_HUSH_UMASK
1155 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1157 #if ENABLE_HUSH_UNSET
1158 BLTIN("unset" , builtin_unset , "Unset variables"),
1160 #if ENABLE_HUSH_WAIT
1161 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1164 /* These builtins won't be used if we are on NOMMU and need to re-exec
1165 * (it's cheaper to run an external program in this case):
1167 static const struct built_in_command bltins2[] = {
1168 #if ENABLE_HUSH_TEST
1169 BLTIN("[" , builtin_test , NULL),
1172 BLTIN("[[" , builtin_test , NULL),
1174 #if ENABLE_HUSH_ECHO
1175 BLTIN("echo" , builtin_echo , NULL),
1177 #if ENABLE_HUSH_PRINTF
1178 BLTIN("printf" , builtin_printf , NULL),
1180 BLTIN("pwd" , builtin_pwd , NULL),
1181 #if ENABLE_HUSH_TEST
1182 BLTIN("test" , builtin_test , NULL),
1190 /* prevent disasters with G.debug_indent < 0 */
1191 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1192 # define debug_enter() (G.debug_indent++)
1193 # define debug_leave() (G.debug_indent--)
1195 # define indent() ((void)0)
1196 # define debug_enter() ((void)0)
1197 # define debug_leave() ((void)0)
1200 #ifndef debug_printf
1201 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1204 #ifndef debug_printf_parse
1205 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1208 #ifndef debug_printf_exec
1209 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1212 #ifndef debug_printf_env
1213 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1216 #ifndef debug_printf_jobs
1217 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1218 # define DEBUG_JOBS 1
1220 # define DEBUG_JOBS 0
1223 #ifndef debug_printf_expand
1224 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1225 # define DEBUG_EXPAND 1
1227 # define DEBUG_EXPAND 0
1230 #ifndef debug_printf_varexp
1231 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1234 #ifndef debug_printf_glob
1235 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1236 # define DEBUG_GLOB 1
1238 # define DEBUG_GLOB 0
1241 #ifndef debug_printf_redir
1242 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1245 #ifndef debug_printf_list
1246 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1249 #ifndef debug_printf_subst
1250 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1253 #ifndef debug_printf_clean
1254 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1255 # define DEBUG_CLEAN 1
1257 # define DEBUG_CLEAN 0
1261 static void debug_print_strings(const char *prefix, char **vv)
1264 fdprintf(2, "%s:\n", prefix);
1266 fdprintf(2, " '%s'\n", *vv++);
1269 # define debug_print_strings(prefix, vv) ((void)0)
1273 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1276 static void *xxmalloc(int lineno, size_t size)
1278 void *ptr = xmalloc((size + 0xff) & ~0xff);
1279 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1282 static void *xxrealloc(int lineno, void *ptr, size_t size)
1284 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1285 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1288 static char *xxstrdup(int lineno, const char *str)
1290 char *ptr = xstrdup(str);
1291 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1294 static void xxfree(void *ptr)
1296 fdprintf(2, "free %p\n", ptr);
1299 # define xmalloc(s) xxmalloc(__LINE__, s)
1300 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1301 # define xstrdup(s) xxstrdup(__LINE__, s)
1302 # define free(p) xxfree(p)
1306 /* Syntax and runtime errors. They always abort scripts.
1307 * In interactive use they usually discard unparsed and/or unexecuted commands
1308 * and return to the prompt.
1309 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1312 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1313 # define syntax_error(lineno, msg) syntax_error(msg)
1314 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1315 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1316 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1317 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1320 static void die_if_script(void)
1322 if (!G_interactive_fd) {
1323 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1324 xfunc_error_retval = G.last_exitcode;
1329 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1334 bb_error_msg("hush.c:%u", lineno);
1337 bb_verror_msg(fmt, p, NULL);
1342 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1345 bb_error_msg("syntax error: %s", msg);
1347 bb_error_msg("syntax error");
1351 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1353 bb_error_msg("syntax error at '%s'", msg);
1357 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1359 bb_error_msg("syntax error: unterminated %s", s);
1360 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1364 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1366 char msg[2] = { ch, '\0' };
1367 syntax_error_unterm_str(lineno, msg);
1370 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1376 bb_error_msg("hush.c:%u", lineno);
1378 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1383 # undef msg_and_die_if_script
1384 # undef syntax_error
1385 # undef syntax_error_at
1386 # undef syntax_error_unterm_ch
1387 # undef syntax_error_unterm_str
1388 # undef syntax_error_unexpected_ch
1390 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1391 # define syntax_error(msg) syntax_error(__LINE__, msg)
1392 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1393 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1394 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1395 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1399 #if ENABLE_HUSH_INTERACTIVE
1400 static void cmdedit_update_prompt(void);
1402 # define cmdedit_update_prompt() ((void)0)
1406 /* Utility functions
1408 /* Replace each \x with x in place, return ptr past NUL. */
1409 static char *unbackslash(char *src)
1411 char *dst = src = strchrnul(src, '\\');
1415 if ((*dst++ = *src++) == '\0')
1421 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1442 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1443 v[count1 + count2] = NULL;
1446 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1450 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1452 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1453 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1456 #define add_strings_to_strings(strings, add, need_to_dup) \
1457 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1460 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1461 static char **add_string_to_strings(char **strings, char *add)
1466 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1469 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1471 char **ptr = add_string_to_strings(strings, add);
1472 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1475 #define add_string_to_strings(strings, add) \
1476 xx_add_string_to_strings(__LINE__, strings, add)
1479 static void free_strings(char **strings)
1493 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1497 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1507 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1511 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1517 /* fd was not open? */
1522 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1523 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1529 /* Manipulating the list of open FILEs */
1530 static FILE *remember_FILE(FILE *fp)
1533 struct FILE_list *n = xmalloc(sizeof(*n));
1534 n->next = G.FILE_list;
1538 close_on_exec_on(n->fd);
1542 static void fclose_and_forget(FILE *fp)
1544 struct FILE_list **pp = &G.FILE_list;
1546 struct FILE_list *cur = *pp;
1547 if (cur->fp == fp) {
1556 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1558 struct FILE_list *fl = G.FILE_list;
1561 /* We use it only on script files, they are all CLOEXEC */
1562 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1563 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1570 static void restore_redirected_FILEs(void)
1572 struct FILE_list *fl = G.FILE_list;
1574 int should_be = fileno(fl->fp);
1575 if (fl->fd != should_be) {
1576 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1577 xmove_fd(fl->fd, should_be);
1583 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1584 static void close_all_FILE_list(void)
1586 struct FILE_list *fl = G.FILE_list;
1588 /* fclose would also free FILE object.
1589 * It is disastrous if we share memory with a vforked parent.
1590 * I'm not sure we never come here after vfork.
1591 * Therefore just close fd, nothing more.
1593 /*fclose(fl->fp); - unsafe */
1599 static int fd_in_FILEs(int fd)
1601 struct FILE_list *fl = G.FILE_list;
1611 /* Helpers for setting new $n and restoring them back
1613 typedef struct save_arg_t {
1617 IF_HUSH_SET(smallint sv_g_malloced;)
1620 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1622 sv->sv_argv0 = argv[0];
1623 sv->sv_g_argv = G.global_argv;
1624 sv->sv_g_argc = G.global_argc;
1625 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1627 argv[0] = G.global_argv[0]; /* retain $0 */
1628 G.global_argv = argv;
1629 IF_HUSH_SET(G.global_args_malloced = 0;)
1631 G.global_argc = 1 + string_array_len(argv + 1);
1634 static void restore_G_args(save_arg_t *sv, char **argv)
1637 if (G.global_args_malloced) {
1638 /* someone ran "set -- arg1 arg2 ...", undo */
1639 char **pp = G.global_argv;
1640 while (*++pp) /* note: does not free $0 */
1642 free(G.global_argv);
1645 argv[0] = sv->sv_argv0;
1646 G.global_argv = sv->sv_g_argv;
1647 G.global_argc = sv->sv_g_argc;
1648 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1652 /* Basic theory of signal handling in shell
1653 * ========================================
1654 * This does not describe what hush does, rather, it is current understanding
1655 * what it _should_ do. If it doesn't, it's a bug.
1656 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1658 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1659 * is finished or backgrounded. It is the same in interactive and
1660 * non-interactive shells, and is the same regardless of whether
1661 * a user trap handler is installed or a shell special one is in effect.
1662 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1663 * backgrounds (i.e. stops) or kills all members of currently running
1666 * Wait builtin is interruptible by signals for which user trap is set
1667 * or by SIGINT in interactive shell.
1669 * Trap handlers will execute even within trap handlers. (right?)
1671 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1672 * except for handlers set to '' (empty string).
1674 * If job control is off, backgrounded commands ("cmd &")
1675 * have SIGINT, SIGQUIT set to SIG_IGN.
1677 * Commands which are run in command substitution ("`cmd`")
1678 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1680 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1681 * by the shell from its parent.
1683 * Signals which differ from SIG_DFL action
1684 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1687 * SIGTERM (interactive): ignore
1688 * SIGHUP (interactive):
1689 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1690 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1691 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1692 * that all pipe members are stopped. Try this in bash:
1693 * while :; do :; done - ^Z does not background it
1694 * (while :; do :; done) - ^Z backgrounds it
1695 * SIGINT (interactive): wait for last pipe, ignore the rest
1696 * of the command line, show prompt. NB: ^C does not send SIGINT
1697 * to interactive shell while shell is waiting for a pipe,
1698 * since shell is bg'ed (is not in foreground process group).
1699 * Example 1: this waits 5 sec, but does not execute ls:
1700 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1701 * Example 2: this does not wait and does not execute ls:
1702 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1703 * Example 3: this does not wait 5 sec, but executes ls:
1704 * "sleep 5; ls -l" + press ^C
1705 * Example 4: this does not wait and does not execute ls:
1706 * "sleep 5 & wait; ls -l" + press ^C
1708 * (What happens to signals which are IGN on shell start?)
1709 * (What happens with signal mask on shell start?)
1711 * Old implementation
1712 * ==================
1713 * We use in-kernel pending signal mask to determine which signals were sent.
1714 * We block all signals which we don't want to take action immediately,
1715 * i.e. we block all signals which need to have special handling as described
1716 * above, and all signals which have traps set.
1717 * After each pipe execution, we extract any pending signals via sigtimedwait()
1720 * unsigned special_sig_mask: a mask of such "special" signals
1721 * sigset_t blocked_set: current blocked signal set
1724 * clear bit in blocked_set unless it is also in special_sig_mask
1725 * "trap 'cmd' SIGxxx":
1726 * set bit in blocked_set (even if 'cmd' is '')
1727 * after [v]fork, if we plan to be a shell:
1728 * unblock signals with special interactive handling
1729 * (child shell is not interactive),
1730 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1731 * after [v]fork, if we plan to exec:
1732 * POSIX says fork clears pending signal mask in child - no need to clear it.
1733 * Restore blocked signal set to one inherited by shell just prior to exec.
1735 * Note: as a result, we do not use signal handlers much. The only uses
1736 * are to count SIGCHLDs
1737 * and to restore tty pgrp on signal-induced exit.
1740 * Standard says "When a subshell is entered, traps that are not being ignored
1741 * are set to the default actions". bash interprets it so that traps which
1742 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1744 * Problem: the above approach makes it unwieldy to catch signals while
1745 * we are in read builtin, or while we read commands from stdin:
1746 * masked signals are not visible!
1748 * New implementation
1749 * ==================
1750 * We record each signal we are interested in by installing signal handler
1751 * for them - a bit like emulating kernel pending signal mask in userspace.
1752 * We are interested in: signals which need to have special handling
1753 * as described above, and all signals which have traps set.
1754 * Signals are recorded in pending_set.
1755 * After each pipe execution, we extract any pending signals
1758 * unsigned special_sig_mask: a mask of shell-special signals.
1759 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1760 * char *traps[sig] if trap for sig is set (even if it's '').
1761 * sigset_t pending_set: set of sigs we received.
1764 * if sig is in special_sig_mask, set handler back to:
1765 * record_pending_signo, or to IGN if it's a tty stop signal
1766 * if sig is in fatal_sig_mask, set handler back to sigexit.
1767 * else: set handler back to SIG_DFL
1768 * "trap 'cmd' SIGxxx":
1769 * set handler to record_pending_signo.
1771 * set handler to SIG_IGN.
1772 * after [v]fork, if we plan to be a shell:
1773 * set signals with special interactive handling to SIG_DFL
1774 * (because child shell is not interactive),
1775 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1776 * after [v]fork, if we plan to exec:
1777 * POSIX says fork clears pending signal mask in child - no need to clear it.
1779 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1780 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1783 * Standard says "When a subshell is entered, traps that are not being ignored
1784 * are set to the default actions". bash interprets it so that traps which
1785 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1788 SPECIAL_INTERACTIVE_SIGS = 0
1793 SPECIAL_JOBSTOP_SIGS = 0
1802 static void record_pending_signo(int sig)
1804 sigaddset(&G.pending_set, sig);
1805 #if ENABLE_HUSH_FAST
1806 if (sig == SIGCHLD) {
1808 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1813 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1815 struct sigaction old_sa;
1817 /* We could use signal() to install handlers... almost:
1818 * except that we need to mask ALL signals while handlers run.
1819 * I saw signal nesting in strace, race window isn't small.
1820 * SA_RESTART is also needed, but in Linux, signal()
1821 * sets SA_RESTART too.
1823 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1824 /* sigfillset(&G.sa.sa_mask); - already done */
1825 /* G.sa.sa_flags = SA_RESTART; - already done */
1826 G.sa.sa_handler = handler;
1827 sigaction(sig, &G.sa, &old_sa);
1828 return old_sa.sa_handler;
1831 static void hush_exit(int exitcode) NORETURN;
1833 static void restore_ttypgrp_and__exit(void) NORETURN;
1834 static void restore_ttypgrp_and__exit(void)
1836 /* xfunc has failed! die die die */
1837 /* no EXIT traps, this is an escape hatch! */
1839 hush_exit(xfunc_error_retval);
1844 /* Needed only on some libc:
1845 * It was observed that on exit(), fgetc'ed buffered data
1846 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1847 * With the net effect that even after fork(), not vfork(),
1848 * exit() in NOEXECed applet in "sh SCRIPT":
1849 * noexec_applet_here
1850 * echo END_OF_SCRIPT
1851 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1852 * This makes "echo END_OF_SCRIPT" executed twice.
1853 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1854 * and in `cmd` handling.
1855 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1857 static void fflush_and__exit(void) NORETURN;
1858 static void fflush_and__exit(void)
1861 _exit(xfunc_error_retval);
1864 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1865 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1866 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1867 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1869 /* Restores tty foreground process group, and exits.
1870 * May be called as signal handler for fatal signal
1871 * (will resend signal to itself, producing correct exit state)
1872 * or called directly with -EXITCODE.
1873 * We also call it if xfunc is exiting.
1875 static void sigexit(int sig) NORETURN;
1876 static void sigexit(int sig)
1878 /* Careful: we can end up here after [v]fork. Do not restore
1879 * tty pgrp then, only top-level shell process does that */
1880 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1881 /* Disable all signals: job control, SIGPIPE, etc.
1882 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1884 sigprocmask_allsigs(SIG_BLOCK);
1885 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1888 /* Not a signal, just exit */
1892 kill_myself_with_sig(sig); /* does not return */
1896 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1897 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1901 static sighandler_t pick_sighandler(unsigned sig)
1903 sighandler_t handler = SIG_DFL;
1904 if (sig < sizeof(unsigned)*8) {
1905 unsigned sigmask = (1 << sig);
1909 if (G_fatal_sig_mask & sigmask)
1913 /* sig has special handling? */
1914 if (G.special_sig_mask & sigmask) {
1915 handler = record_pending_signo;
1916 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1917 * in order to ignore them: they will be raised
1918 * in an endless loop when we try to do some
1919 * terminal ioctls! We do have to _ignore_ these.
1921 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1928 /* Restores tty foreground process group, and exits. */
1929 static void hush_exit(int exitcode)
1931 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1932 save_history(G.line_input_state);
1936 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1938 /* argv[0] is unused */
1939 argv[1] = G_traps[0];
1941 G.exiting = 1; /* prevent EXIT trap recursion */
1942 /* Note: G_traps[0] is not cleared!
1943 * "trap" will still show it, if executed
1948 #if ENABLE_FEATURE_CLEAN_UP
1950 struct variable *cur_var;
1951 if (G.cwd != bb_msg_unknown)
1953 cur_var = G.top_var;
1955 struct variable *tmp = cur_var;
1956 if (!cur_var->max_len)
1957 free(cur_var->varstr);
1958 cur_var = cur_var->next;
1966 sigexit(- (exitcode & 0xff));
1973 //TODO: return a mask of ALL handled sigs?
1974 static int check_and_run_traps(void)
1981 if (sigisemptyset(&G.pending_set))
1986 if (sigismember(&G.pending_set, sig)) {
1987 sigdelset(&G.pending_set, sig);
1990 } while (sig < NSIG);
1993 if (G_traps && G_traps[sig]) {
1994 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1995 if (G_traps[sig][0]) {
1996 /* We have user-defined handler */
1997 smalluint save_rcode;
1999 /* argv[0] is unused */
2000 argv[1] = G_traps[sig];
2002 save_rcode = G.last_exitcode;
2004 //FIXME: shouldn't it be set to 128 + sig instead?
2005 G.last_exitcode = save_rcode;
2007 } /* else: "" trap, ignoring signal */
2010 /* not a trap: special action */
2013 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2019 //TODO: why are we doing this? ash and dash don't do this,
2020 //they have no handler for SIGHUP at all,
2021 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2023 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2024 /* bash is observed to signal whole process groups,
2025 * not individual processes */
2026 for (job = G.job_list; job; job = job->next) {
2029 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2030 if (kill(- job->pgrp, SIGHUP) == 0)
2031 kill(- job->pgrp, SIGCONT);
2036 #if ENABLE_HUSH_FAST
2038 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2040 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2042 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2043 * This simplifies wait builtin a bit.
2047 default: /* ignored: */
2048 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2049 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2051 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2052 * Example: wait is not interrupted by TERM
2053 * in interactive shell, because TERM is ignored.
2062 static const char *get_cwd(int force)
2064 if (force || G.cwd == NULL) {
2065 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2066 * we must not try to free(bb_msg_unknown) */
2067 if (G.cwd == bb_msg_unknown)
2069 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2071 G.cwd = bb_msg_unknown;
2078 * Shell and environment variable support
2080 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2082 struct variable **pp;
2083 struct variable *cur;
2086 while ((cur = *pp) != NULL) {
2087 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2094 static const char* FAST_FUNC get_local_var_value(const char *name)
2096 struct variable **vpp;
2097 unsigned len = strlen(name);
2099 if (G.expanded_assignments) {
2100 char **cpp = G.expanded_assignments;
2103 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2104 return cp + len + 1;
2109 vpp = get_ptr_to_local_var(name, len);
2111 return (*vpp)->varstr + len + 1;
2113 if (strcmp(name, "PPID") == 0)
2114 return utoa(G.root_ppid);
2115 // bash compat: UID? EUID?
2116 #if ENABLE_HUSH_RANDOM_SUPPORT
2117 if (strcmp(name, "RANDOM") == 0)
2118 return utoa(next_random(&G.random_gen));
2123 /* str holds "NAME=VAL" and is expected to be malloced.
2124 * We take ownership of it.
2126 #define SETFLAG_EXPORT (1 << 0)
2127 #define SETFLAG_UNEXPORT (1 << 1)
2128 #define SETFLAG_MAKE_RO (1 << 2)
2129 #define SETFLAG_LOCAL_SHIFT 3
2130 static int set_local_var(char *str, unsigned flags)
2132 struct variable **var_pp;
2133 struct variable *cur;
2134 char *free_me = NULL;
2137 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2139 eq_sign = strchr(str, '=');
2140 if (!eq_sign) { /* not expected to ever happen? */
2145 name_len = eq_sign - str + 1; /* including '=' */
2148 if (name_len == 7 && strncmp("LINENO", str, 6) == 0)
2149 G.lineno_var = NULL;
2153 var_pp = &G.top_var;
2154 while ((cur = *var_pp) != NULL) {
2155 if (strncmp(cur->varstr, str, name_len) != 0) {
2156 var_pp = &cur->next;
2160 /* We found an existing var with this name */
2161 if (cur->flg_read_only) {
2162 bb_error_msg("%s: readonly variable", str);
2164 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2165 //but export per se succeeds (does put the var in env). We don't mimic that.
2168 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2169 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2174 #if ENABLE_HUSH_LOCAL
2175 if (cur->func_nest_level < local_lvl) {
2176 /* New variable is declared as local,
2177 * and existing one is global, or local
2178 * from enclosing function.
2179 * Remove and save old one: */
2180 *var_pp = cur->next;
2181 cur->next = *G.shadowed_vars_pp;
2182 *G.shadowed_vars_pp = cur;
2183 /* bash 3.2.33(1) and exported vars:
2185 * # f() { local z=a; env | grep ^z; }
2191 if (cur->flg_export)
2192 flags |= SETFLAG_EXPORT;
2196 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2201 if (cur->max_len != 0) {
2202 if (cur->max_len >= strlen(str)) {
2203 /* This one is from startup env, reuse space */
2204 strcpy(cur->varstr, str);
2209 goto set_str_and_exp;
2211 /* max_len == 0 signifies "malloced" var, which we can
2212 * (and have to) free. But we can't free(cur->varstr) here:
2213 * if cur->flg_export is 1, it is in the environment.
2214 * We should either unsetenv+free, or wait until putenv,
2215 * then putenv(new)+free(old).
2217 free_me = cur->varstr;
2218 goto set_str_and_exp;
2221 /* Not found - create new variable struct */
2222 cur = xzalloc(sizeof(*cur));
2223 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2224 cur->next = *var_pp;
2230 #if !BB_MMU || ENABLE_HUSH_READONLY
2231 if (flags & SETFLAG_MAKE_RO) {
2232 cur->flg_read_only = 1;
2235 if (flags & SETFLAG_EXPORT)
2236 cur->flg_export = 1;
2237 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2238 cmdedit_update_prompt();
2239 #if ENABLE_HUSH_GETOPTS
2240 /* defoptindvar is a "OPTIND=..." constant string */
2241 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
2244 if (cur->flg_export) {
2245 if (flags & SETFLAG_UNEXPORT) {
2246 cur->flg_export = 0;
2247 /* unsetenv was already done */
2250 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2251 i = putenv(cur->varstr);
2252 /* only now we can free old exported malloced string */
2261 /* Used at startup and after each cd */
2262 static void set_pwd_var(unsigned flag)
2264 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2267 static int unset_local_var_len(const char *name, int name_len)
2269 struct variable *cur;
2270 struct variable **var_pp;
2273 return EXIT_SUCCESS;
2275 #if ENABLE_HUSH_GETOPTS
2276 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2280 if (name_len == 6 && G.lineno_var && strncmp(name, "LINENO", 6) == 0)
2281 G.lineno_var = NULL;
2284 var_pp = &G.top_var;
2285 while ((cur = *var_pp) != NULL) {
2286 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2287 if (cur->flg_read_only) {
2288 bb_error_msg("%s: readonly variable", name);
2289 return EXIT_FAILURE;
2291 *var_pp = cur->next;
2292 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2293 bb_unsetenv(cur->varstr);
2294 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2295 cmdedit_update_prompt();
2299 return EXIT_SUCCESS;
2301 var_pp = &cur->next;
2303 return EXIT_SUCCESS;
2306 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2307 static int unset_local_var(const char *name)
2309 return unset_local_var_len(name, strlen(name));
2313 static void unset_vars(char **strings)
2321 const char *eq = strchrnul(*v, '=');
2322 unset_local_var_len(*v, (int)(eq - *v));
2328 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
2329 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2331 char *var = xasprintf("%s=%s", name, val);
2332 set_local_var(var, /*flag:*/ 0);
2338 * Helpers for "var1=val1 var2=val2 cmd" feature
2340 static void add_vars(struct variable *var)
2342 struct variable *next;
2346 var->next = G.top_var;
2348 if (var->flg_export) {
2349 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2350 putenv(var->varstr);
2352 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2358 static struct variable *set_vars_and_save_old(char **strings)
2361 struct variable *old = NULL;
2367 struct variable *var_p;
2368 struct variable **var_pp;
2371 eq = strchr(*s, '=');
2373 var_pp = get_ptr_to_local_var(*s, eq - *s);
2376 if (var_p->flg_read_only) {
2378 bb_error_msg("%s: readonly variable", *s);
2380 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2381 * If VAR is readonly, leaving it in the list
2382 * after asssignment error (msg above)
2383 * causes doubled error message later, on unset.
2385 debug_printf_env("removing/freeing '%s' element\n", *s);
2388 do { *p = p[1]; p++; } while (*p);
2391 /* Remove variable from global linked list */
2392 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2393 *var_pp = var_p->next;
2394 /* Add it to returned list */
2398 set_local_var(*s, SETFLAG_EXPORT);
2410 static void reinit_unicode_for_hush(void)
2412 /* Unicode support should be activated even if LANG is set
2413 * _during_ shell execution, not only if it was set when
2414 * shell was started. Therefore, re-check LANG every time:
2416 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2417 || ENABLE_UNICODE_USING_LOCALE
2419 const char *s = get_local_var_value("LC_ALL");
2420 if (!s) s = get_local_var_value("LC_CTYPE");
2421 if (!s) s = get_local_var_value("LANG");
2427 * in_str support (strings, and "strings" read from files).
2430 #if ENABLE_HUSH_INTERACTIVE
2431 /* To test correct lineedit/interactive behavior, type from command line:
2437 * It exercises a lot of corner cases.
2439 static void cmdedit_update_prompt(void)
2441 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2442 G.PS1 = get_local_var_value("PS1");
2445 G.PS2 = get_local_var_value("PS2");
2452 static const char *setup_prompt_string(int promptmode)
2454 const char *prompt_str;
2455 debug_printf("setup_prompt_string %d ", promptmode);
2456 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2457 /* Set up the prompt */
2458 if (promptmode == 0) { /* PS1 */
2460 /* bash uses $PWD value, even if it is set by user.
2461 * It uses current dir only if PWD is unset.
2462 * We always use current dir. */
2463 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2468 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2469 debug_printf("prompt_str '%s'\n", prompt_str);
2472 static int get_user_input(struct in_str *i)
2475 const char *prompt_str;
2477 prompt_str = setup_prompt_string(i->promptmode);
2478 # if ENABLE_FEATURE_EDITING
2480 reinit_unicode_for_hush();
2481 if (G.flag_SIGINT) {
2482 /* There was ^C'ed, make it look prettier: */
2486 /* buglet: SIGINT will not make new prompt to appear _at once_,
2487 * only after <Enter>. (^C works immediately) */
2488 r = read_line_input(G.line_input_state, prompt_str,
2489 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2491 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2494 check_and_run_traps();
2495 if (r != 0 && !G.flag_SIGINT)
2497 /* ^C or SIGINT: repeat */
2498 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2499 write(STDOUT_FILENO, "^C", 2);
2500 G.last_exitcode = 128 + SIGINT;
2503 /* EOF/error detected */
2505 i->peek_buf[0] = r = EOF;
2508 i->p = G.user_input_buf;
2509 return (unsigned char)*i->p++;
2513 if (i->last_char == '\0' || i->last_char == '\n') {
2514 /* Why check_and_run_traps here? Try this interactively:
2515 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2516 * $ <[enter], repeatedly...>
2517 * Without check_and_run_traps, handler never runs.
2519 check_and_run_traps();
2520 fputs(prompt_str, stdout);
2523 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2525 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2526 * no ^C masking happens during fgetc, no special code for ^C:
2527 * it generates SIGINT as usual.
2529 check_and_run_traps();
2531 G.last_exitcode = 128 + SIGINT;
2538 /* This is the magic location that prints prompts
2539 * and gets data back from the user */
2540 static int fgetc_interactive(struct in_str *i)
2543 /* If it's interactive stdin, get new line. */
2544 if (G_interactive_fd && i->file == stdin) {
2545 /* Returns first char (or EOF), the rest is in i->p[] */
2546 ch = get_user_input(i);
2547 i->promptmode = 1; /* PS2 */
2549 /* Not stdin: script file, sourced file, etc */
2550 do ch = fgetc(i->file); while (ch == '\0');
2555 static inline int fgetc_interactive(struct in_str *i)
2558 do ch = fgetc(i->file); while (ch == '\0');
2561 #endif /* INTERACTIVE */
2563 static int i_getch(struct in_str *i)
2568 /* string-based in_str */
2569 ch = (unsigned char)*i->p;
2578 /* FILE-based in_str */
2580 #if ENABLE_FEATURE_EDITING
2581 /* This can be stdin, check line editing char[] buffer */
2582 if (i->p && *i->p != '\0') {
2583 ch = (unsigned char)*i->p++;
2587 /* peek_buf[] is an int array, not char. Can contain EOF. */
2588 ch = i->peek_buf[0];
2590 int ch2 = i->peek_buf[1];
2591 i->peek_buf[0] = ch2;
2592 if (ch2 == 0) /* very likely, avoid redundant write */
2598 ch = fgetc_interactive(i);
2600 debug_printf("file_get: got '%c' %d\n", ch, ch);
2609 static int i_peek(struct in_str *i)
2614 /* string-based in_str */
2615 /* Doesn't report EOF on NUL. None of the callers care. */
2616 return (unsigned char)*i->p;
2619 /* FILE-based in_str */
2621 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2622 /* This can be stdin, check line editing char[] buffer */
2623 if (i->p && *i->p != '\0')
2624 return (unsigned char)*i->p;
2626 /* peek_buf[] is an int array, not char. Can contain EOF. */
2627 ch = i->peek_buf[0];
2631 /* Need to get a new char */
2632 ch = fgetc_interactive(i);
2633 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2635 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2636 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2642 i->peek_buf[0] = ch;
2643 /*i->peek_buf[1] = 0; - already is */
2647 /* Only ever called if i_peek() was called, and did not return EOF.
2648 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2649 * not end-of-line. Therefore we never need to read a new editing line here.
2651 static int i_peek2(struct in_str *i)
2655 /* There are two cases when i->p[] buffer exists.
2656 * (1) it's a string in_str.
2657 * (2) It's a file, and we have a saved line editing buffer.
2658 * In both cases, we know that i->p[0] exists and not NUL, and
2659 * the peek2 result is in i->p[1].
2662 return (unsigned char)i->p[1];
2664 /* Now we know it is a file-based in_str. */
2666 /* peek_buf[] is an int array, not char. Can contain EOF. */
2667 /* Is there 2nd char? */
2668 ch = i->peek_buf[1];
2670 /* We did not read it yet, get it now */
2671 do ch = fgetc(i->file); while (ch == '\0');
2672 i->peek_buf[1] = ch;
2675 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2679 static void setup_file_in_str(struct in_str *i, FILE *f)
2681 memset(i, 0, sizeof(*i));
2682 /* i->promptmode = 0; - PS1 (memset did it) */
2687 static void setup_string_in_str(struct in_str *i, const char *s)
2689 memset(i, 0, sizeof(*i));
2690 /* i->promptmode = 0; - PS1 (memset did it) */
2691 /*i->file = NULL */;
2699 #define B_CHUNK (32 * sizeof(char*))
2701 static void o_reset_to_empty_unquoted(o_string *o)
2704 o->has_quoted_part = 0;
2709 static void o_free(o_string *o)
2712 memset(o, 0, sizeof(*o));
2715 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2720 static void o_grow_by(o_string *o, int len)
2722 if (o->length + len > o->maxlen) {
2723 o->maxlen += (2 * len) | (B_CHUNK-1);
2724 o->data = xrealloc(o->data, 1 + o->maxlen);
2728 static void o_addchr(o_string *o, int ch)
2730 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2731 if (o->length < o->maxlen) {
2732 /* likely. avoid o_grow_by() call */
2734 o->data[o->length] = ch;
2736 o->data[o->length] = '\0';
2744 /* Valid only if we know o_string is not empty */
2745 static void o_delchr(o_string *o)
2748 o->data[o->length] = '\0';
2752 static void o_addblock(o_string *o, const char *str, int len)
2755 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2759 static void o_addstr(o_string *o, const char *str)
2761 o_addblock(o, str, strlen(str));
2765 static void nommu_addchr(o_string *o, int ch)
2771 # define nommu_addchr(o, str) ((void)0)
2774 static void o_addstr_with_NUL(o_string *o, const char *str)
2776 o_addblock(o, str, strlen(str) + 1);
2780 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2781 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2782 * Apparently, on unquoted $v bash still does globbing
2783 * ("v='*.txt'; echo $v" prints all .txt files),
2784 * but NOT brace expansion! Thus, there should be TWO independent
2785 * quoting mechanisms on $v expansion side: one protects
2786 * $v from brace expansion, and other additionally protects "$v" against globbing.
2787 * We have only second one.
2790 #if ENABLE_HUSH_BRACE_EXPANSION
2791 # define MAYBE_BRACES "{}"
2793 # define MAYBE_BRACES ""
2796 /* My analysis of quoting semantics tells me that state information
2797 * is associated with a destination, not a source.
2799 static void o_addqchr(o_string *o, int ch)
2802 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2807 o->data[o->length] = '\\';
2810 o->data[o->length] = ch;
2812 o->data[o->length] = '\0';
2815 static void o_addQchr(o_string *o, int ch)
2818 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2819 && strchr("*?[\\" MAYBE_BRACES, ch)
2822 o->data[o->length] = '\\';
2826 o->data[o->length] = ch;
2828 o->data[o->length] = '\0';
2831 static void o_addqblock(o_string *o, const char *str, int len)
2836 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2837 if (ordinary_cnt > len) /* paranoia */
2839 o_addblock(o, str, ordinary_cnt);
2840 if (ordinary_cnt == len)
2841 return; /* NUL is already added by o_addblock */
2842 str += ordinary_cnt;
2843 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2847 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2849 o->data[o->length] = '\\';
2853 o->data[o->length] = ch;
2856 o->data[o->length] = '\0';
2859 static void o_addQblock(o_string *o, const char *str, int len)
2861 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2862 o_addblock(o, str, len);
2865 o_addqblock(o, str, len);
2868 static void o_addQstr(o_string *o, const char *str)
2870 o_addQblock(o, str, strlen(str));
2873 /* A special kind of o_string for $VAR and `cmd` expansion.
2874 * It contains char* list[] at the beginning, which is grown in 16 element
2875 * increments. Actual string data starts at the next multiple of 16 * (char*).
2876 * list[i] contains an INDEX (int!) into this string data.
2877 * It means that if list[] needs to grow, data needs to be moved higher up
2878 * but list[i]'s need not be modified.
2879 * NB: remembering how many list[i]'s you have there is crucial.
2880 * o_finalize_list() operation post-processes this structure - calculates
2881 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2883 #if DEBUG_EXPAND || DEBUG_GLOB
2884 static void debug_print_list(const char *prefix, o_string *o, int n)
2886 char **list = (char**)o->data;
2887 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2891 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2892 prefix, list, n, string_start, o->length, o->maxlen,
2893 !!(o->o_expflags & EXP_FLAG_GLOB),
2895 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2898 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2899 o->data + (int)(uintptr_t)list[i] + string_start,
2900 o->data + (int)(uintptr_t)list[i] + string_start);
2904 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2906 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2910 # define debug_print_list(prefix, o, n) ((void)0)
2913 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2914 * in list[n] so that it points past last stored byte so far.
2915 * It returns n+1. */
2916 static int o_save_ptr_helper(o_string *o, int n)
2918 char **list = (char**)o->data;
2922 if (!o->has_empty_slot) {
2923 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2924 string_len = o->length - string_start;
2925 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2926 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2927 /* list[n] points to string_start, make space for 16 more pointers */
2928 o->maxlen += 0x10 * sizeof(list[0]);
2929 o->data = xrealloc(o->data, o->maxlen + 1);
2930 list = (char**)o->data;
2931 memmove(list + n + 0x10, list + n, string_len);
2932 o->length += 0x10 * sizeof(list[0]);
2934 debug_printf_list("list[%d]=%d string_start=%d\n",
2935 n, string_len, string_start);
2938 /* We have empty slot at list[n], reuse without growth */
2939 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2940 string_len = o->length - string_start;
2941 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2942 n, string_len, string_start);
2943 o->has_empty_slot = 0;
2945 o->has_quoted_part = 0;
2946 list[n] = (char*)(uintptr_t)string_len;
2950 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2951 static int o_get_last_ptr(o_string *o, int n)
2953 char **list = (char**)o->data;
2954 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2956 return ((int)(uintptr_t)list[n-1]) + string_start;
2959 #if ENABLE_HUSH_BRACE_EXPANSION
2960 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2961 * first, it processes even {a} (no commas), second,
2962 * I didn't manage to make it return strings when they don't match
2963 * existing files. Need to re-implement it.
2967 static int glob_needed(const char *s)
2976 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2982 /* Return pointer to next closing brace or to comma */
2983 static const char *next_brace_sub(const char *cp)
2987 while (*cp != '\0') {
2994 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3000 return *cp != '\0' ? cp : NULL;
3002 /* Recursive brace globber. Note: may garble pattern[]. */
3003 static int glob_brace(char *pattern, o_string *o, int n)
3005 char *new_pattern_buf;
3012 debug_printf_glob("glob_brace('%s')\n", pattern);
3018 if (*begin == '{') {
3019 /* Find the first sub-pattern and at the same time
3020 * find the rest after the closing brace */
3021 next = next_brace_sub(begin);
3023 /* An illegal expression */
3027 /* "{abc}" with no commas - illegal
3028 * brace expr, disregard and skip it */
3034 if (*begin == '\\' && begin[1] != '\0')
3038 debug_printf_glob("begin:%s\n", begin);
3039 debug_printf_glob("next:%s\n", next);
3041 /* Now find the end of the whole brace expression */
3043 while (*rest != '}') {
3044 rest = next_brace_sub(rest);
3046 /* An illegal expression */
3049 debug_printf_glob("rest:%s\n", rest);
3051 rest_len = strlen(++rest) + 1;
3053 /* We are sure the brace expression is well-formed */
3055 /* Allocate working buffer large enough for our work */
3056 new_pattern_buf = xmalloc(strlen(pattern));
3058 /* We have a brace expression. BEGIN points to the opening {,
3059 * NEXT points past the terminator of the first element, and REST
3060 * points past the final }. We will accumulate result names from
3061 * recursive runs for each brace alternative in the buffer using
3066 /* Construct the new glob expression */
3069 mempcpy(new_pattern_buf,
3070 /* We know the prefix for all sub-patterns */
3071 pattern, begin - pattern),
3075 /* Note: glob_brace() may garble new_pattern_buf[].
3076 * That's why we re-copy prefix every time (1st memcpy above).
3078 n = glob_brace(new_pattern_buf, o, n);
3080 /* We saw the last entry */
3084 next = next_brace_sub(next);
3086 free(new_pattern_buf);
3094 memset(&globdata, 0, sizeof(globdata));
3095 gr = glob(pattern, 0, NULL, &globdata);
3096 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3098 if (gr == GLOB_NOMATCH) {
3099 globfree(&globdata);
3100 /* NB: garbles parameter */
3101 unbackslash(pattern);
3102 o_addstr_with_NUL(o, pattern);
3103 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3104 return o_save_ptr_helper(o, n);
3106 if (gr == GLOB_NOSPACE)
3107 bb_error_msg_and_die(bb_msg_memory_exhausted);
3108 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3109 * but we didn't specify it. Paranoia again. */
3110 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3112 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3113 char **argv = globdata.gl_pathv;
3115 o_addstr_with_NUL(o, *argv);
3116 n = o_save_ptr_helper(o, n);
3122 globfree(&globdata);
3126 /* Performs globbing on last list[],
3127 * saving each result as a new list[].
3129 static int perform_glob(o_string *o, int n)
3131 char *pattern, *copy;
3133 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3135 return o_save_ptr_helper(o, n);
3136 pattern = o->data + o_get_last_ptr(o, n);
3137 debug_printf_glob("glob pattern '%s'\n", pattern);
3138 if (!glob_needed(pattern)) {
3139 /* unbackslash last string in o in place, fix length */
3140 o->length = unbackslash(pattern) - o->data;
3141 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3142 return o_save_ptr_helper(o, n);
3145 copy = xstrdup(pattern);
3146 /* "forget" pattern in o */
3147 o->length = pattern - o->data;
3148 n = glob_brace(copy, o, n);
3151 debug_print_list("perform_glob returning", o, n);
3155 #else /* !HUSH_BRACE_EXPANSION */
3158 static int glob_needed(const char *s)
3167 if (*s == '*' || *s == '[' || *s == '?')
3173 /* Performs globbing on last list[],
3174 * saving each result as a new list[].
3176 static int perform_glob(o_string *o, int n)
3182 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3184 return o_save_ptr_helper(o, n);
3185 pattern = o->data + o_get_last_ptr(o, n);
3186 debug_printf_glob("glob pattern '%s'\n", pattern);
3187 if (!glob_needed(pattern)) {
3189 /* unbackslash last string in o in place, fix length */
3190 o->length = unbackslash(pattern) - o->data;
3191 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3192 return o_save_ptr_helper(o, n);
3195 memset(&globdata, 0, sizeof(globdata));
3196 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3197 * If we glob "*.\*" and don't find anything, we need
3198 * to fall back to using literal "*.*", but GLOB_NOCHECK
3199 * will return "*.\*"!
3201 gr = glob(pattern, 0, NULL, &globdata);
3202 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3204 if (gr == GLOB_NOMATCH) {
3205 globfree(&globdata);
3208 if (gr == GLOB_NOSPACE)
3209 bb_error_msg_and_die(bb_msg_memory_exhausted);
3210 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3211 * but we didn't specify it. Paranoia again. */
3212 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3214 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3215 char **argv = globdata.gl_pathv;
3216 /* "forget" pattern in o */
3217 o->length = pattern - o->data;
3219 o_addstr_with_NUL(o, *argv);
3220 n = o_save_ptr_helper(o, n);
3226 globfree(&globdata);
3228 debug_print_list("perform_glob returning", o, n);
3232 #endif /* !HUSH_BRACE_EXPANSION */
3234 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3235 * Otherwise, just finish current list[] and start new */
3236 static int o_save_ptr(o_string *o, int n)
3238 if (o->o_expflags & EXP_FLAG_GLOB) {
3239 /* If o->has_empty_slot, list[n] was already globbed
3240 * (if it was requested back then when it was filled)
3241 * so don't do that again! */
3242 if (!o->has_empty_slot)
3243 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3245 return o_save_ptr_helper(o, n);
3248 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3249 static char **o_finalize_list(o_string *o, int n)
3254 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3256 debug_print_list("finalized", o, n);
3257 debug_printf_expand("finalized n:%d\n", n);
3258 list = (char**)o->data;
3259 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3263 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3268 static void free_pipe_list(struct pipe *pi);
3270 /* Returns pi->next - next pipe in the list */
3271 static struct pipe *free_pipe(struct pipe *pi)
3276 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3277 for (i = 0; i < pi->num_cmds; i++) {
3278 struct command *command;
3279 struct redir_struct *r, *rnext;
3281 command = &pi->cmds[i];
3282 debug_printf_clean(" command %d:\n", i);
3283 if (command->argv) {
3287 for (a = 0, p = command->argv; *p; a++, p++) {
3288 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3291 free_strings(command->argv);
3292 //command->argv = NULL;
3294 /* not "else if": on syntax error, we may have both! */
3295 if (command->group) {
3296 debug_printf_clean(" begin group (cmd_type:%d)\n",
3298 free_pipe_list(command->group);
3299 debug_printf_clean(" end group\n");
3300 //command->group = NULL;
3302 /* else is crucial here.
3303 * If group != NULL, child_func is meaningless */
3304 #if ENABLE_HUSH_FUNCTIONS
3305 else if (command->child_func) {
3306 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3307 command->child_func->parent_cmd = NULL;
3311 free(command->group_as_string);
3312 //command->group_as_string = NULL;
3314 for (r = command->redirects; r; r = rnext) {
3315 debug_printf_clean(" redirect %d%s",
3316 r->rd_fd, redir_table[r->rd_type].descrip);
3317 /* guard against the case >$FOO, where foo is unset or blank */
3318 if (r->rd_filename) {
3319 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3320 free(r->rd_filename);
3321 //r->rd_filename = NULL;
3323 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3327 //command->redirects = NULL;
3329 free(pi->cmds); /* children are an array, they get freed all at once */
3333 //pi->cmdtext = NULL;
3341 static void free_pipe_list(struct pipe *pi)
3345 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3347 debug_printf_clean("pipe followup code %d\n", pi->followup);
3353 /*** Parsing routines ***/
3355 #ifndef debug_print_tree
3356 static void debug_print_tree(struct pipe *pi, int lvl)
3358 static const char *const PIPE[] = {
3364 static const char *RES[] = {
3365 [RES_NONE ] = "NONE" ,
3368 [RES_THEN ] = "THEN" ,
3369 [RES_ELIF ] = "ELIF" ,
3370 [RES_ELSE ] = "ELSE" ,
3373 # if ENABLE_HUSH_LOOPS
3374 [RES_FOR ] = "FOR" ,
3375 [RES_WHILE] = "WHILE",
3376 [RES_UNTIL] = "UNTIL",
3378 [RES_DONE ] = "DONE" ,
3380 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3383 # if ENABLE_HUSH_CASE
3384 [RES_CASE ] = "CASE" ,
3385 [RES_CASE_IN ] = "CASE_IN" ,
3386 [RES_MATCH] = "MATCH",
3387 [RES_CASE_BODY] = "CASE_BODY",
3388 [RES_ESAC ] = "ESAC" ,
3390 [RES_XXXX ] = "XXXX" ,
3391 [RES_SNTX ] = "SNTX" ,
3393 static const char *const CMDTYPE[] = {
3397 # if ENABLE_HUSH_FUNCTIONS
3406 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3407 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3409 while (prn < pi->num_cmds) {
3410 struct command *command = &pi->cmds[prn];
3411 char **argv = command->argv;
3413 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3415 command->assignment_cnt);
3416 if (command->group) {
3417 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3418 CMDTYPE[command->cmd_type],
3421 , " group_as_string:", command->group_as_string
3426 debug_print_tree(command->group, lvl+1);
3430 if (argv) while (*argv) {
3431 fdprintf(2, " '%s'", *argv);
3441 #endif /* debug_print_tree */
3443 static struct pipe *new_pipe(void)
3446 pi = xzalloc(sizeof(struct pipe));
3447 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3451 /* Command (member of a pipe) is complete, or we start a new pipe
3452 * if ctx->command is NULL.
3453 * No errors possible here.
3455 static int done_command(struct parse_context *ctx)
3457 /* The command is really already in the pipe structure, so
3458 * advance the pipe counter and make a new, null command. */
3459 struct pipe *pi = ctx->pipe;
3460 struct command *command = ctx->command;
3462 #if 0 /* Instead we emit error message at run time */
3463 if (ctx->pending_redirect) {
3464 /* For example, "cmd >" (no filename to redirect to) */
3465 syntax_error("invalid redirect");
3466 ctx->pending_redirect = NULL;
3471 if (IS_NULL_CMD(command)) {
3472 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3476 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3477 //debug_print_tree(ctx->list_head, 20);
3479 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3482 /* Only real trickiness here is that the uncommitted
3483 * command structure is not counted in pi->num_cmds. */
3484 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3485 ctx->command = command = &pi->cmds[pi->num_cmds];
3487 memset(command, 0, sizeof(*command));
3489 command->lineno = G.lineno;
3491 return pi->num_cmds; /* used only for 0/nonzero check */
3494 static void done_pipe(struct parse_context *ctx, pipe_style type)
3498 debug_printf_parse("done_pipe entered, followup %d\n", type);
3499 /* Close previous command */
3500 not_null = done_command(ctx);
3502 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3503 ctx->ctx_inverted = 0;
3504 ctx->pipe->res_word = ctx->ctx_res_w;
3506 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3507 /* Necessary since && and || have precedence over &:
3508 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3509 * in a backgrounded subshell.
3512 struct command *command;
3514 /* Is this actually this construct, all pipes end with && or ||? */
3515 pi = ctx->list_head;
3516 while (pi != ctx->pipe) {
3517 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3522 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3523 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3524 pi = xzalloc(sizeof(*pi));
3525 pi->followup = PIPE_BG;
3527 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3528 command = &pi->cmds[0];
3529 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3530 command->cmd_type = CMD_NORMAL;
3531 command->group = ctx->list_head;
3533 command->group_as_string = xstrndup(
3534 ctx->as_string.data,
3535 ctx->as_string.length - 1 /* do not copy last char, "&" */
3538 /* Replace all pipes in ctx with one newly created */
3539 ctx->list_head = ctx->pipe = pi;
3542 ctx->pipe->followup = type;
3545 /* Without this check, even just <enter> on command line generates
3546 * tree of three NOPs (!). Which is harmless but annoying.
3547 * IOW: it is safe to do it unconditionally. */
3550 || ctx->ctx_res_w == RES_FI
3552 #if ENABLE_HUSH_LOOPS
3553 || ctx->ctx_res_w == RES_DONE
3554 || ctx->ctx_res_w == RES_FOR
3555 || ctx->ctx_res_w == RES_IN
3557 #if ENABLE_HUSH_CASE
3558 || ctx->ctx_res_w == RES_ESAC
3562 debug_printf_parse("done_pipe: adding new pipe: "
3563 "not_null:%d ctx->ctx_res_w:%d\n",
3564 not_null, ctx->ctx_res_w);
3566 ctx->pipe->next = new_p;
3568 /* RES_THEN, RES_DO etc are "sticky" -
3569 * they remain set for pipes inside if/while.
3570 * This is used to control execution.
3571 * RES_FOR and RES_IN are NOT sticky (needed to support
3572 * cases where variable or value happens to match a keyword):
3574 #if ENABLE_HUSH_LOOPS
3575 if (ctx->ctx_res_w == RES_FOR
3576 || ctx->ctx_res_w == RES_IN)
3577 ctx->ctx_res_w = RES_NONE;
3579 #if ENABLE_HUSH_CASE
3580 if (ctx->ctx_res_w == RES_MATCH)
3581 ctx->ctx_res_w = RES_CASE_BODY;
3582 if (ctx->ctx_res_w == RES_CASE)
3583 ctx->ctx_res_w = RES_CASE_IN;
3585 ctx->command = NULL; /* trick done_command below */
3586 /* Create the memory for command, roughly:
3587 * ctx->pipe->cmds = new struct command;
3588 * ctx->command = &ctx->pipe->cmds[0];
3591 //debug_print_tree(ctx->list_head, 10);
3593 debug_printf_parse("done_pipe return\n");
3596 static void initialize_context(struct parse_context *ctx)
3598 memset(ctx, 0, sizeof(*ctx));
3599 ctx->pipe = ctx->list_head = new_pipe();
3600 /* Create the memory for command, roughly:
3601 * ctx->pipe->cmds = new struct command;
3602 * ctx->command = &ctx->pipe->cmds[0];
3607 /* If a reserved word is found and processed, parse context is modified
3608 * and 1 is returned.
3611 struct reserved_combo {
3614 unsigned char assignment_flag;
3618 FLAG_END = (1 << RES_NONE ),
3620 FLAG_IF = (1 << RES_IF ),
3621 FLAG_THEN = (1 << RES_THEN ),
3622 FLAG_ELIF = (1 << RES_ELIF ),
3623 FLAG_ELSE = (1 << RES_ELSE ),
3624 FLAG_FI = (1 << RES_FI ),
3626 # if ENABLE_HUSH_LOOPS
3627 FLAG_FOR = (1 << RES_FOR ),
3628 FLAG_WHILE = (1 << RES_WHILE),
3629 FLAG_UNTIL = (1 << RES_UNTIL),
3630 FLAG_DO = (1 << RES_DO ),
3631 FLAG_DONE = (1 << RES_DONE ),
3632 FLAG_IN = (1 << RES_IN ),
3634 # if ENABLE_HUSH_CASE
3635 FLAG_MATCH = (1 << RES_MATCH),
3636 FLAG_ESAC = (1 << RES_ESAC ),
3638 FLAG_START = (1 << RES_XXXX ),
3641 static const struct reserved_combo* match_reserved_word(o_string *word)
3643 /* Mostly a list of accepted follow-up reserved words.
3644 * FLAG_END means we are done with the sequence, and are ready
3645 * to turn the compound list into a command.
3646 * FLAG_START means the word must start a new compound list.
3648 static const struct reserved_combo reserved_list[] = {
3650 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3651 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3652 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3653 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3654 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3655 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3657 # if ENABLE_HUSH_LOOPS
3658 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3659 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3660 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3661 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3662 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3663 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3665 # if ENABLE_HUSH_CASE
3666 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3667 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3670 const struct reserved_combo *r;
3672 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3673 if (strcmp(word->data, r->literal) == 0)
3678 /* Return 0: not a keyword, 1: keyword
3680 static int reserved_word(o_string *word, struct parse_context *ctx)
3682 # if ENABLE_HUSH_CASE
3683 static const struct reserved_combo reserved_match = {
3684 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3687 const struct reserved_combo *r;
3689 if (word->has_quoted_part)
3691 r = match_reserved_word(word);
3695 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3696 # if ENABLE_HUSH_CASE
3697 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3698 /* "case word IN ..." - IN part starts first MATCH part */
3699 r = &reserved_match;
3702 if (r->flag == 0) { /* '!' */
3703 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3704 syntax_error("! ! command");
3705 ctx->ctx_res_w = RES_SNTX;
3707 ctx->ctx_inverted = 1;
3710 if (r->flag & FLAG_START) {
3711 struct parse_context *old;
3713 old = xmemdup(ctx, sizeof(*ctx));
3714 debug_printf_parse("push stack %p\n", old);
3715 initialize_context(ctx);
3717 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3718 syntax_error_at(word->data);
3719 ctx->ctx_res_w = RES_SNTX;
3722 /* "{...} fi" is ok. "{...} if" is not
3724 * if { echo foo; } then { echo bar; } fi */
3725 if (ctx->command->group)
3726 done_pipe(ctx, PIPE_SEQ);
3729 ctx->ctx_res_w = r->res;
3730 ctx->old_flag = r->flag;
3731 word->o_assignment = r->assignment_flag;
3732 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3734 if (ctx->old_flag & FLAG_END) {
3735 struct parse_context *old;
3737 done_pipe(ctx, PIPE_SEQ);
3738 debug_printf_parse("pop stack %p\n", ctx->stack);
3740 old->command->group = ctx->list_head;
3741 old->command->cmd_type = CMD_NORMAL;
3743 /* At this point, the compound command's string is in
3744 * ctx->as_string... except for the leading keyword!
3745 * Consider this example: "echo a | if true; then echo a; fi"
3746 * ctx->as_string will contain "true; then echo a; fi",
3747 * with "if " remaining in old->as_string!
3751 int len = old->as_string.length;
3752 /* Concatenate halves */
3753 o_addstr(&old->as_string, ctx->as_string.data);
3754 o_free_unsafe(&ctx->as_string);
3755 /* Find where leading keyword starts in first half */
3756 str = old->as_string.data + len;
3757 if (str > old->as_string.data)
3758 str--; /* skip whitespace after keyword */
3759 while (str > old->as_string.data && isalpha(str[-1]))
3761 /* Ugh, we're done with this horrid hack */
3762 old->command->group_as_string = xstrdup(str);
3763 debug_printf_parse("pop, remembering as:'%s'\n",
3764 old->command->group_as_string);
3767 *ctx = *old; /* physical copy */
3772 #endif /* HAS_KEYWORDS */
3774 /* Word is complete, look at it and update parsing context.
3775 * Normal return is 0. Syntax errors return 1.
3776 * Note: on return, word is reset, but not o_free'd!
3778 static int done_word(o_string *word, struct parse_context *ctx)
3780 struct command *command = ctx->command;
3782 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3783 if (word->length == 0 && !word->has_quoted_part) {
3784 debug_printf_parse("done_word return 0: true null, ignored\n");
3788 if (ctx->pending_redirect) {
3789 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3790 * only if run as "bash", not "sh" */
3791 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3793 * ...the word that follows the redirection operator
3794 * shall be subjected to tilde expansion, parameter expansion,
3795 * command substitution, arithmetic expansion, and quote
3796 * removal. Pathname expansion shall not be performed
3797 * on the word by a non-interactive shell; an interactive
3798 * shell may perform it, but shall do so only when
3799 * the expansion would result in one word."
3801 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3802 /* Cater for >\file case:
3803 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3804 * Same with heredocs:
3805 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3807 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3808 unbackslash(ctx->pending_redirect->rd_filename);
3809 /* Is it <<"HEREDOC"? */
3810 if (word->has_quoted_part) {
3811 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3814 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3815 ctx->pending_redirect = NULL;
3818 # if ENABLE_HUSH_CASE
3819 if (ctx->ctx_dsemicolon
3820 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3822 /* already done when ctx_dsemicolon was set to 1: */
3823 /* ctx->ctx_res_w = RES_MATCH; */
3824 ctx->ctx_dsemicolon = 0;
3827 if (!command->argv /* if it's the first word... */
3828 # if ENABLE_HUSH_LOOPS
3829 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3830 && ctx->ctx_res_w != RES_IN
3832 # if ENABLE_HUSH_CASE
3833 && ctx->ctx_res_w != RES_CASE
3836 int reserved = reserved_word(word, ctx);
3837 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3839 o_reset_to_empty_unquoted(word);
3840 debug_printf_parse("done_word return %d\n",
3841 (ctx->ctx_res_w == RES_SNTX));
3842 return (ctx->ctx_res_w == RES_SNTX);
3845 if (strcmp(word->data, "[[") == 0) {
3846 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3852 if (command->group) {
3853 /* "{ echo foo; } echo bar" - bad */
3854 syntax_error_at(word->data);
3855 debug_printf_parse("done_word return 1: syntax error, "
3856 "groups and arglists don't mix\n");
3860 /* If this word wasn't an assignment, next ones definitely
3861 * can't be assignments. Even if they look like ones. */
3862 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3863 && word->o_assignment != WORD_IS_KEYWORD
3865 word->o_assignment = NOT_ASSIGNMENT;
3867 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3868 command->assignment_cnt++;
3869 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3871 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3872 word->o_assignment = MAYBE_ASSIGNMENT;
3874 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3875 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3876 debug_print_strings("word appended to argv", command->argv);
3879 #if ENABLE_HUSH_LOOPS
3880 if (ctx->ctx_res_w == RES_FOR) {
3881 if (word->has_quoted_part
3882 || !is_well_formed_var_name(command->argv[0], '\0')
3884 /* bash says just "not a valid identifier" */
3885 syntax_error("not a valid identifier in for");
3888 /* Force FOR to have just one word (variable name) */
3889 /* NB: basically, this makes hush see "for v in ..."
3890 * syntax as if it is "for v; in ...". FOR and IN become
3891 * two pipe structs in parse tree. */
3892 done_pipe(ctx, PIPE_SEQ);
3895 #if ENABLE_HUSH_CASE
3896 /* Force CASE to have just one word */
3897 if (ctx->ctx_res_w == RES_CASE) {
3898 done_pipe(ctx, PIPE_SEQ);
3902 o_reset_to_empty_unquoted(word);
3904 debug_printf_parse("done_word return 0\n");
3909 /* Peek ahead in the input to find out if we have a "&n" construct,
3910 * as in "2>&1", that represents duplicating a file descriptor.
3912 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3913 * REDIRFD_SYNTAX_ERR if syntax error,
3914 * REDIRFD_TO_FILE if no & was seen,
3915 * or the number found.
3918 #define parse_redir_right_fd(as_string, input) \
3919 parse_redir_right_fd(input)
3921 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3927 return REDIRFD_TO_FILE;
3929 ch = i_getch(input); /* get the & */
3930 nommu_addchr(as_string, ch);
3933 ch = i_getch(input);
3934 nommu_addchr(as_string, ch);
3935 return REDIRFD_CLOSE;
3939 while (ch != EOF && isdigit(ch)) {
3940 d = d*10 + (ch-'0');
3942 ch = i_getch(input);
3943 nommu_addchr(as_string, ch);
3948 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3950 bb_error_msg("ambiguous redirect");
3951 return REDIRFD_SYNTAX_ERR;
3954 /* Return code is 0 normal, 1 if a syntax error is detected
3956 static int parse_redirect(struct parse_context *ctx,
3959 struct in_str *input)
3961 struct command *command = ctx->command;
3962 struct redir_struct *redir;
3963 struct redir_struct **redirp;
3966 dup_num = REDIRFD_TO_FILE;
3967 if (style != REDIRECT_HEREDOC) {
3968 /* Check for a '>&1' type redirect */
3969 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3970 if (dup_num == REDIRFD_SYNTAX_ERR)
3973 int ch = i_peek(input);
3974 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3975 if (dup_num) { /* <<-... */
3976 ch = i_getch(input);
3977 nommu_addchr(&ctx->as_string, ch);
3982 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3983 int ch = i_peek(input);
3985 /* >|FILE redirect ("clobbering" >).
3986 * Since we do not support "set -o noclobber" yet,
3987 * >| and > are the same for now. Just eat |.
3989 ch = i_getch(input);
3990 nommu_addchr(&ctx->as_string, ch);
3994 /* Create a new redir_struct and append it to the linked list */
3995 redirp = &command->redirects;
3996 while ((redir = *redirp) != NULL) {
3997 redirp = &(redir->next);
3999 *redirp = redir = xzalloc(sizeof(*redir));
4000 /* redir->next = NULL; */
4001 /* redir->rd_filename = NULL; */
4002 redir->rd_type = style;
4003 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4005 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4006 redir_table[style].descrip);
4008 redir->rd_dup = dup_num;
4009 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4010 /* Erik had a check here that the file descriptor in question
4011 * is legit; I postpone that to "run time"
4012 * A "-" representation of "close me" shows up as a -3 here */
4013 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4014 redir->rd_fd, redir->rd_dup);
4016 #if 0 /* Instead we emit error message at run time */
4017 if (ctx->pending_redirect) {
4018 /* For example, "cmd > <file" */
4019 syntax_error("invalid redirect");
4022 /* Set ctx->pending_redirect, so we know what to do at the
4023 * end of the next parsed word. */
4024 ctx->pending_redirect = redir;
4029 /* If a redirect is immediately preceded by a number, that number is
4030 * supposed to tell which file descriptor to redirect. This routine
4031 * looks for such preceding numbers. In an ideal world this routine
4032 * needs to handle all the following classes of redirects...
4033 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4034 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4035 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4036 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4038 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4040 * ... If n is quoted, the number shall not be recognized as part of
4041 * the redirection expression. For example:
4043 * writes the character 2 into file a"
4044 * We are getting it right by setting ->has_quoted_part on any \<char>
4046 * A -1 return means no valid number was found,
4047 * the caller should use the appropriate default for this redirection.
4049 static int redirect_opt_num(o_string *o)
4053 if (o->data == NULL)
4055 num = bb_strtou(o->data, NULL, 10);
4056 if (errno || num < 0)
4058 o_reset_to_empty_unquoted(o);
4063 #define fetch_till_str(as_string, input, word, skip_tabs) \
4064 fetch_till_str(input, word, skip_tabs)
4066 static char *fetch_till_str(o_string *as_string,
4067 struct in_str *input,
4071 o_string heredoc = NULL_O_STRING;
4073 int prev = 0; /* not \ */
4079 ch = i_getch(input);
4081 nommu_addchr(as_string, ch);
4082 if (ch == '\n' || ch == EOF) {
4084 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4085 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4086 heredoc.data[past_EOL] = '\0';
4087 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4088 return heredoc.data;
4091 /* This is a new line.
4092 * Remember position and backslash-escaping status.
4094 o_addchr(&heredoc, ch);
4097 past_EOL = heredoc.length;
4098 /* Get 1st char of next line, possibly skipping leading tabs */
4100 ch = i_getch(input);
4102 nommu_addchr(as_string, ch);
4103 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4104 /* If this immediately ended the line,
4105 * go back to end-of-line checks.
4108 goto check_heredoc_end;
4113 o_free_unsafe(&heredoc);
4116 o_addchr(&heredoc, ch);
4117 nommu_addchr(as_string, ch);
4118 if (prev == '\\' && ch == '\\')
4119 /* Correctly handle foo\\<eol> (not a line cont.) */
4120 prev = 0; /* not \ */
4126 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4127 * and load them all. There should be exactly heredoc_cnt of them.
4129 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4131 struct pipe *pi = ctx->list_head;
4133 while (pi && heredoc_cnt) {
4135 struct command *cmd = pi->cmds;
4137 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4139 cmd->argv ? cmd->argv[0] : "NONE");
4140 for (i = 0; i < pi->num_cmds; i++) {
4141 struct redir_struct *redir = cmd->redirects;
4143 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4144 i, cmd->argv ? cmd->argv[0] : "NONE");
4146 if (redir->rd_type == REDIRECT_HEREDOC) {
4149 redir->rd_type = REDIRECT_HEREDOC2;
4150 /* redir->rd_dup is (ab)used to indicate <<- */
4151 p = fetch_till_str(&ctx->as_string, input,
4152 redir->rd_filename, redir->rd_dup);
4154 syntax_error("unexpected EOF in here document");
4157 free(redir->rd_filename);
4158 redir->rd_filename = p;
4161 redir = redir->next;
4168 /* Should be 0. If it isn't, it's a parse error */
4170 bb_error_msg_and_die("heredoc BUG 2");
4176 static int run_list(struct pipe *pi);
4178 #define parse_stream(pstring, input, end_trigger) \
4179 parse_stream(input, end_trigger)
4181 static struct pipe *parse_stream(char **pstring,
4182 struct in_str *input,
4186 #if !ENABLE_HUSH_FUNCTIONS
4187 #define parse_group(dest, ctx, input, ch) \
4188 parse_group(ctx, input, ch)
4190 static int parse_group(o_string *dest, struct parse_context *ctx,
4191 struct in_str *input, int ch)
4193 /* dest contains characters seen prior to ( or {.
4194 * Typically it's empty, but for function defs,
4195 * it contains function name (without '()'). */
4196 struct pipe *pipe_list;
4198 struct command *command = ctx->command;
4200 debug_printf_parse("parse_group entered\n");
4201 #if ENABLE_HUSH_FUNCTIONS
4202 if (ch == '(' && !dest->has_quoted_part) {
4204 if (done_word(dest, ctx))
4207 goto skip; /* (... */
4208 if (command->argv[1]) { /* word word ... (... */
4209 syntax_error_unexpected_ch('(');
4212 /* it is "word(..." or "word (..." */
4214 ch = i_getch(input);
4215 while (ch == ' ' || ch == '\t');
4217 syntax_error_unexpected_ch(ch);
4220 nommu_addchr(&ctx->as_string, ch);
4222 ch = i_getch(input);
4223 while (ch == ' ' || ch == '\t' || ch == '\n');
4225 syntax_error_unexpected_ch(ch);
4228 nommu_addchr(&ctx->as_string, ch);
4229 command->cmd_type = CMD_FUNCDEF;
4234 #if 0 /* Prevented by caller */
4235 if (command->argv /* word [word]{... */
4236 || dest->length /* word{... */
4237 || dest->has_quoted_part /* ""{... */
4240 debug_printf_parse("parse_group return 1: "
4241 "syntax error, groups and arglists don't mix\n");
4246 #if ENABLE_HUSH_FUNCTIONS
4252 command->cmd_type = CMD_SUBSHELL;
4254 /* bash does not allow "{echo...", requires whitespace */
4256 if (ch != ' ' && ch != '\t' && ch != '\n'
4257 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4259 syntax_error_unexpected_ch(ch);
4263 ch = i_getch(input);
4264 nommu_addchr(&ctx->as_string, ch);
4270 # define as_string NULL
4272 char *as_string = NULL;
4274 pipe_list = parse_stream(&as_string, input, endch);
4277 o_addstr(&ctx->as_string, as_string);
4279 /* empty ()/{} or parse error? */
4280 if (!pipe_list || pipe_list == ERR_PTR) {
4281 /* parse_stream already emitted error msg */
4284 debug_printf_parse("parse_group return 1: "
4285 "parse_stream returned %p\n", pipe_list);
4288 command->group = pipe_list;
4290 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4291 command->group_as_string = as_string;
4292 debug_printf_parse("end of group, remembering as:'%s'\n",
4293 command->group_as_string);
4297 debug_printf_parse("parse_group return 0\n");
4299 /* command remains "open", available for possible redirects */
4302 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4307 ch = i_getch(input);
4310 ch2 = i_peek(input);
4313 /* backslash+newline, skip it */
4318 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4326 ch2 = i_peek2(input);
4329 /* backslash+newline, skip it */
4335 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4336 /* Subroutines for copying $(...) and `...` things */
4337 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4339 static int add_till_single_quote(o_string *dest, struct in_str *input)
4342 int ch = i_getch(input);
4344 syntax_error_unterm_ch('\'');
4352 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4353 static int add_till_double_quote(o_string *dest, struct in_str *input)
4356 int ch = i_getch(input);
4358 syntax_error_unterm_ch('"');
4363 if (ch == '\\') { /* \x. Copy both chars. */
4365 ch = i_getch(input);
4369 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4374 //if (ch == '$') ...
4377 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4379 * "Within the backquoted style of command substitution, backslash
4380 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4381 * The search for the matching backquote shall be satisfied by the first
4382 * backquote found without a preceding backslash; during this search,
4383 * if a non-escaped backquote is encountered within a shell comment,
4384 * a here-document, an embedded command substitution of the $(command)
4385 * form, or a quoted string, undefined results occur. A single-quoted
4386 * or double-quoted string that begins, but does not end, within the
4387 * "`...`" sequence produces undefined results."
4389 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4391 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4394 int ch = i_getch(input);
4398 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4399 ch = i_getch(input);
4403 && (!in_dquote || ch != '"')
4405 o_addchr(dest, '\\');
4409 syntax_error_unterm_ch('`');
4415 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4416 * quoting and nested ()s.
4417 * "With the $(command) style of command substitution, all characters
4418 * following the open parenthesis to the matching closing parenthesis
4419 * constitute the command. Any valid shell script can be used for command,
4420 * except a script consisting solely of redirections which produces
4421 * unspecified results."
4423 * echo $(echo '(TEST)' BEST) (TEST) BEST
4424 * echo $(echo 'TEST)' BEST) TEST) BEST
4425 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4427 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4428 * can contain arbitrary constructs, just like $(cmd).
4429 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4430 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4432 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4433 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4436 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4437 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4438 char end_char2 = end_ch >> 8;
4440 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4443 ch = i_getch(input);
4445 syntax_error_unterm_ch(end_ch);
4449 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4455 /* we look for closing )) of $((EXPR)) */
4456 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4457 i_getch(input); /* eat second ')' */
4462 if (ch == '(' || ch == '{') {
4463 ch = (ch == '(' ? ')' : '}');
4464 if (!add_till_closing_bracket(dest, input, ch))
4470 if (!add_till_single_quote(dest, input))
4476 if (!add_till_double_quote(dest, input))
4482 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4488 /* \x. Copy verbatim. Important for \(, \) */
4489 ch = i_getch(input);
4491 syntax_error_unterm_ch(')');
4496 /* "backslash+newline", ignore both */
4497 o_delchr(dest); /* undo insertion of '\' */
4507 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4509 /* Return code: 0 for OK, 1 for syntax error */
4511 #define parse_dollar(as_string, dest, input, quote_mask) \
4512 parse_dollar(dest, input, quote_mask)
4513 #define as_string NULL
4515 static int parse_dollar(o_string *as_string,
4517 struct in_str *input, unsigned char quote_mask)
4519 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4521 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4523 ch = i_getch(input);
4524 nommu_addchr(as_string, ch);
4526 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4528 debug_printf_parse(": '%c'\n", ch);
4529 o_addchr(dest, ch | quote_mask);
4531 ch = i_peek_and_eat_bkslash_nl(input);
4532 if (!isalnum(ch) && ch != '_') {
4533 /* End of variable name reached */
4536 ch = i_getch(input);
4537 nommu_addchr(as_string, ch);
4539 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4540 } else if (isdigit(ch)) {
4542 ch = i_getch(input);
4543 nommu_addchr(as_string, ch);
4544 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4545 debug_printf_parse(": '%c'\n", ch);
4546 o_addchr(dest, ch | quote_mask);
4547 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4548 } else switch (ch) {
4550 case '!': /* last bg pid */
4551 case '?': /* last exit code */
4552 case '#': /* number of args */
4553 case '*': /* args */
4554 case '@': /* args */
4555 goto make_one_char_var;
4559 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4561 ch = i_getch(input); /* eat '{' */
4562 nommu_addchr(as_string, ch);
4564 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4565 /* It should be ${?}, or ${#var},
4566 * or even ${?+subst} - operator acting on a special variable,
4567 * or the beginning of variable name.
4570 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4573 syntax_error_unterm_str("${name}");
4574 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4577 nommu_addchr(as_string, ch);
4581 /* It's possible to just call add_till_closing_bracket() at this point.
4582 * However, this regresses some of our testsuite cases
4583 * which check invalid constructs like ${%}.
4584 * Oh well... let's check that the var name part is fine... */
4590 debug_printf_parse(": '%c'\n", ch);
4592 ch = i_getch(input);
4593 nommu_addchr(as_string, ch);
4597 if (!isalnum(ch) && ch != '_') {
4599 unsigned char last_ch;
4600 /* handle parameter expansions
4601 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4603 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4604 if (len_single_ch != '#'
4605 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4606 || i_peek(input) != '}'
4608 goto bad_dollar_syntax;
4610 /* else: it's "length of C" ${#C} op,
4611 * where C is a single char
4612 * special var name, e.g. ${#!}.
4615 /* Eat everything until closing '}' (or ':') */
4619 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4621 /* It's ${var:N[:M]} thing */
4622 end_ch = '}' * 0x100 + ':';
4624 if (BASH_PATTERN_SUBST
4627 /* It's ${var/[/]pattern[/repl]} thing */
4628 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4630 nommu_addchr(as_string, '/');
4633 end_ch = '}' * 0x100 + '/';
4639 #if ENABLE_HUSH_DOLLAR_OPS
4640 last_ch = add_till_closing_bracket(dest, input, end_ch);
4641 if (last_ch == 0) /* error? */
4644 #error Simple code to only allow ${var} is not implemented
4647 o_addstr(as_string, dest->data + pos);
4648 o_addchr(as_string, last_ch);
4651 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4652 && (end_ch & 0xff00)
4654 /* close the first block: */
4655 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4656 /* while parsing N from ${var:N[:M]}
4657 * or pattern from ${var/[/]pattern[/repl]} */
4658 if ((end_ch & 0xff) == last_ch) {
4659 /* got ':' or '/'- parse the rest */
4664 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4665 /* it's ${var:N} - emulate :999999999 */
4666 o_addstr(dest, "999999999");
4667 } /* else: it's ${var/[/]pattern} */
4671 len_single_ch = 0; /* it can't be ${#C} op */
4673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4676 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4680 ch = i_getch(input);
4681 nommu_addchr(as_string, ch);
4682 # if ENABLE_FEATURE_SH_MATH
4683 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4684 ch = i_getch(input);
4685 nommu_addchr(as_string, ch);
4686 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4687 o_addchr(dest, /*quote_mask |*/ '+');
4690 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4691 return 0; /* error */
4693 o_addstr(as_string, dest->data + pos);
4694 o_addchr(as_string, ')');
4695 o_addchr(as_string, ')');
4697 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4701 # if ENABLE_HUSH_TICK
4702 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4703 o_addchr(dest, quote_mask | '`');
4706 if (!add_till_closing_bracket(dest, input, ')'))
4707 return 0; /* error */
4709 o_addstr(as_string, dest->data + pos);
4710 o_addchr(as_string, ')');
4712 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4718 ch = i_getch(input);
4719 nommu_addchr(as_string, ch);
4720 ch = i_peek_and_eat_bkslash_nl(input);
4721 if (isalnum(ch)) { /* it's $_name or $_123 */
4726 /* TODO: $_ and $-: */
4727 /* $_ Shell or shell script name; or last argument of last command
4728 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4729 * but in command's env, set to full pathname used to invoke it */
4730 /* $- Option flags set by set builtin or shell options (-i etc) */
4732 o_addQchr(dest, '$');
4734 debug_printf_parse("parse_dollar return 1 (ok)\n");
4740 # if BASH_PATTERN_SUBST
4741 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4742 encode_string(dest, input, dquote_end, process_bkslash)
4744 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4745 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4746 encode_string(dest, input, dquote_end)
4748 #define as_string NULL
4752 # if BASH_PATTERN_SUBST
4753 /* all parameters are needed, no macro tricks */
4755 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4756 encode_string(as_string, dest, input, dquote_end)
4759 static int encode_string(o_string *as_string,
4761 struct in_str *input,
4763 int process_bkslash)
4765 #if !BASH_PATTERN_SUBST
4766 const int process_bkslash = 1;
4772 ch = i_getch(input);
4774 nommu_addchr(as_string, ch);
4775 if (ch == dquote_end) { /* may be only '"' or EOF */
4776 debug_printf_parse("encode_string return 1 (ok)\n");
4779 /* note: can't move it above ch == dquote_end check! */
4781 syntax_error_unterm_ch('"');
4782 return 0; /* error */
4786 next = i_peek(input);
4788 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4789 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4790 if (process_bkslash && ch == '\\') {
4792 syntax_error("\\<eof>");
4796 * "The backslash retains its special meaning [in "..."]
4797 * only when followed by one of the following characters:
4798 * $, `, ", \, or <newline>. A double quote may be quoted
4799 * within double quotes by preceding it with a backslash."
4800 * NB: in (unquoted) heredoc, above does not apply to ",
4801 * therefore we check for it by "next == dquote_end" cond.
4803 if (next == dquote_end || strchr("$`\\\n", next)) {
4804 ch = i_getch(input); /* eat next */
4806 goto again; /* skip \<newline> */
4807 } /* else: ch remains == '\\', and we double it below: */
4808 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4809 nommu_addchr(as_string, ch);
4813 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4814 debug_printf_parse("encode_string return 0: "
4815 "parse_dollar returned 0 (error)\n");
4820 #if ENABLE_HUSH_TICK
4822 //unsigned pos = dest->length;
4823 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4824 o_addchr(dest, 0x80 | '`');
4825 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4826 return 0; /* error */
4827 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4828 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4832 o_addQchr(dest, ch);
4838 * Scan input until EOF or end_trigger char.
4839 * Return a list of pipes to execute, or NULL on EOF
4840 * or if end_trigger character is met.
4841 * On syntax error, exit if shell is not interactive,
4842 * reset parsing machinery and start parsing anew,
4843 * or return ERR_PTR.
4845 static struct pipe *parse_stream(char **pstring,
4846 struct in_str *input,
4849 struct parse_context ctx;
4850 o_string dest = NULL_O_STRING;
4853 /* Single-quote triggers a bypass of the main loop until its mate is
4854 * found. When recursing, quote state is passed in via dest->o_expflags.
4856 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4857 end_trigger ? end_trigger : 'X');
4860 /* If very first arg is "" or '', dest.data may end up NULL.
4861 * Preventing this: */
4862 o_addchr(&dest, '\0');
4865 /* We used to separate words on $IFS here. This was wrong.
4866 * $IFS is used only for word splitting when $var is expanded,
4867 * here we should use blank chars as separators, not $IFS
4870 if (MAYBE_ASSIGNMENT != 0)
4871 dest.o_assignment = MAYBE_ASSIGNMENT;
4872 initialize_context(&ctx);
4875 const char *is_blank;
4876 const char *is_special;
4880 redir_type redir_style;
4882 ch = i_getch(input);
4883 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4884 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4889 syntax_error_unterm_str("here document");
4892 if (end_trigger == ')') {
4893 syntax_error_unterm_ch('(');
4896 if (end_trigger == '}') {
4897 syntax_error_unterm_ch('{');
4901 if (done_word(&dest, &ctx)) {
4905 done_pipe(&ctx, PIPE_SEQ);
4907 /* If we got nothing... */
4908 /* (this makes bare "&" cmd a no-op.
4909 * bash says: "syntax error near unexpected token '&'") */
4910 if (pi->num_cmds == 0
4911 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4917 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4919 *pstring = ctx.as_string.data;
4921 o_free_unsafe(&ctx.as_string);
4924 debug_printf_parse("parse_stream return %p\n", pi);
4927 nommu_addchr(&ctx.as_string, ch);
4931 next = i_peek(input);
4933 is_special = "{}<>;&|()#'" /* special outside of "str" */
4934 "\\$\"" IF_HUSH_TICK("`") /* always special */
4935 SPECIAL_VAR_SYMBOL_STR;
4936 /* Are { and } special here? */
4937 if (ctx.command->argv /* word [word]{... - non-special */
4938 || dest.length /* word{... - non-special */
4939 || dest.has_quoted_part /* ""{... - non-special */
4940 || (next != ';' /* }; - special */
4941 && next != ')' /* }) - special */
4942 && next != '(' /* {( - special */
4943 && next != '&' /* }& and }&& ... - special */
4944 && next != '|' /* }|| ... - special */
4945 && !strchr(defifs, next) /* {word - non-special */
4948 /* They are not special, skip "{}" */
4951 is_special = strchr(is_special, ch);
4952 is_blank = strchr(defifs, ch);
4954 if (!is_special && !is_blank) { /* ordinary char */
4956 o_addQchr(&dest, ch);
4957 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4958 || dest.o_assignment == WORD_IS_KEYWORD)
4960 && is_well_formed_var_name(dest.data, '=')
4962 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4963 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4969 if (done_word(&dest, &ctx)) {
4973 /* Is this a case when newline is simply ignored?
4975 * "cmd | <newline> cmd ..."
4976 * "case ... in <newline> word) ..."
4978 if (IS_NULL_CMD(ctx.command)
4979 && dest.length == 0 && !dest.has_quoted_part
4981 /* This newline can be ignored. But...
4982 * Without check #1, interactive shell
4983 * ignores even bare <newline>,
4984 * and shows the continuation prompt:
4985 * ps1_prompt$ <enter>
4986 * ps2> _ <=== wrong, should be ps1
4987 * Without check #2, "cmd & <newline>"
4988 * is similarly mistreated.
4989 * (BTW, this makes "cmd & cmd"
4990 * and "cmd && cmd" non-orthogonal.
4991 * Really, ask yourself, why
4992 * "cmd && <newline>" doesn't start
4993 * cmd but waits for more input?
4994 * The only reason is that it might be
4995 * a "cmd1 && <nl> cmd2 &" construct,
4996 * cmd1 may need to run in BG).
4998 struct pipe *pi = ctx.list_head;
4999 if (pi->num_cmds != 0 /* check #1 */
5000 && pi->followup != PIPE_BG /* check #2 */
5005 /* Treat newline as a command separator. */
5006 done_pipe(&ctx, PIPE_SEQ);
5007 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5009 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5014 dest.o_assignment = MAYBE_ASSIGNMENT;
5015 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5017 /* note: if (is_blank) continue;
5018 * will still trigger for us */
5022 /* "cmd}" or "cmd }..." without semicolon or &:
5023 * } is an ordinary char in this case, even inside { cmd; }
5024 * Pathological example: { ""}; } should exec "}" cmd
5027 if (dest.length != 0 /* word} */
5028 || dest.has_quoted_part /* ""} */
5032 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5033 /* Generally, there should be semicolon: "cmd; }"
5034 * However, bash allows to omit it if "cmd" is
5035 * a group. Examples:
5038 * { echo 0 >&2 | { echo 1; } }
5039 * { while false; do :; done }
5040 * { case a in b) ;; esac }
5042 if (ctx.command->group)
5046 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5047 /* Can't be an end of {cmd}, skip the check */
5048 goto skip_end_trigger;
5049 /* else: } does terminate a group */
5052 if (end_trigger && end_trigger == ch
5053 && (ch != ';' || heredoc_cnt == 0)
5054 #if ENABLE_HUSH_CASE
5056 || ctx.ctx_res_w != RES_MATCH
5057 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5062 /* This is technically valid:
5063 * { cat <<HERE; }; echo Ok
5067 * but we don't support this.
5068 * We require heredoc to be in enclosing {}/(),
5071 syntax_error_unterm_str("here document");
5074 if (done_word(&dest, &ctx)) {
5077 done_pipe(&ctx, PIPE_SEQ);
5078 dest.o_assignment = MAYBE_ASSIGNMENT;
5079 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5080 /* Do we sit outside of any if's, loops or case's? */
5082 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5086 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5088 *pstring = ctx.as_string.data;
5090 o_free_unsafe(&ctx.as_string);
5092 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5093 /* Example: bare "{ }", "()" */
5094 G.last_exitcode = 2; /* bash compat */
5095 syntax_error_unexpected_ch(ch);
5098 debug_printf_parse("parse_stream return %p: "
5099 "end_trigger char found\n",
5102 return ctx.list_head;
5109 /* Catch <, > before deciding whether this word is
5110 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5113 redir_fd = redirect_opt_num(&dest);
5114 if (done_word(&dest, &ctx)) {
5117 redir_style = REDIRECT_OVERWRITE;
5119 redir_style = REDIRECT_APPEND;
5120 ch = i_getch(input);
5121 nommu_addchr(&ctx.as_string, ch);
5124 else if (next == '(') {
5125 syntax_error(">(process) not supported");
5129 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5131 continue; /* back to top of while (1) */
5133 redir_fd = redirect_opt_num(&dest);
5134 if (done_word(&dest, &ctx)) {
5137 redir_style = REDIRECT_INPUT;
5139 redir_style = REDIRECT_HEREDOC;
5141 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5142 ch = i_getch(input);
5143 nommu_addchr(&ctx.as_string, ch);
5144 } else if (next == '>') {
5145 redir_style = REDIRECT_IO;
5146 ch = i_getch(input);
5147 nommu_addchr(&ctx.as_string, ch);
5150 else if (next == '(') {
5151 syntax_error("<(process) not supported");
5155 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5157 continue; /* back to top of while (1) */
5159 if (dest.length == 0 && !dest.has_quoted_part) {
5160 /* skip "#comment" */
5161 /* note: we do not add it to &ctx.as_string */
5163 * comment inside $() goes to the next \n, even inside quoted string (!):
5164 * cmd "$(cmd2 #comment)" - syntax error
5165 * cmd "`cmd2 #comment`" - ok
5166 * We accept both (comment ends where command subst ends, in both cases).
5171 nommu_addchr(&ctx.as_string, '\n');
5174 ch = i_getch(input);
5178 continue; /* back to top of while (1) */
5183 /* It's "\<newline>" */
5185 /* Remove trailing '\' from ctx.as_string */
5186 ctx.as_string.data[--ctx.as_string.length] = '\0';
5188 ch = i_getch(input); /* eat it */
5189 continue; /* back to top of while (1) */
5194 if (dest.o_assignment == MAYBE_ASSIGNMENT
5195 /* check that we are not in word in "a=1 2>word b=1": */
5196 && !ctx.pending_redirect
5198 /* ch is a special char and thus this word
5199 * cannot be an assignment */
5200 dest.o_assignment = NOT_ASSIGNMENT;
5201 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5204 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5207 case SPECIAL_VAR_SYMBOL:
5208 /* Convert raw ^C to corresponding special variable reference */
5209 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5210 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5213 /* non-comment #: "echo a#b" etc */
5214 o_addchr(&dest, ch);
5218 syntax_error("\\<eof>");
5221 ch = i_getch(input);
5222 /* note: ch != '\n' (that case does not reach this place) */
5223 o_addchr(&dest, '\\');
5224 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5225 o_addchr(&dest, ch);
5226 nommu_addchr(&ctx.as_string, ch);
5227 /* Example: echo Hello \2>file
5228 * we need to know that word 2 is quoted */
5229 dest.has_quoted_part = 1;
5232 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5233 debug_printf_parse("parse_stream parse error: "
5234 "parse_dollar returned 0 (error)\n");
5239 dest.has_quoted_part = 1;
5240 if (next == '\'' && !ctx.pending_redirect) {
5241 insert_empty_quoted_str_marker:
5242 nommu_addchr(&ctx.as_string, next);
5243 i_getch(input); /* eat second ' */
5244 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5245 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5248 ch = i_getch(input);
5250 syntax_error_unterm_ch('\'');
5253 nommu_addchr(&ctx.as_string, ch);
5256 if (ch == SPECIAL_VAR_SYMBOL) {
5257 /* Convert raw ^C to corresponding special variable reference */
5258 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5259 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5261 o_addqchr(&dest, ch);
5266 dest.has_quoted_part = 1;
5267 if (next == '"' && !ctx.pending_redirect)
5268 goto insert_empty_quoted_str_marker;
5269 if (dest.o_assignment == NOT_ASSIGNMENT)
5270 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5271 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5273 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5275 #if ENABLE_HUSH_TICK
5277 USE_FOR_NOMMU(unsigned pos;)
5279 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5280 o_addchr(&dest, '`');
5281 USE_FOR_NOMMU(pos = dest.length;)
5282 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5285 o_addstr(&ctx.as_string, dest.data + pos);
5286 o_addchr(&ctx.as_string, '`');
5288 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5289 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5294 #if ENABLE_HUSH_CASE
5297 if (done_word(&dest, &ctx)) {
5300 done_pipe(&ctx, PIPE_SEQ);
5301 #if ENABLE_HUSH_CASE
5302 /* Eat multiple semicolons, detect
5303 * whether it means something special */
5308 ch = i_getch(input);
5309 nommu_addchr(&ctx.as_string, ch);
5310 if (ctx.ctx_res_w == RES_CASE_BODY) {
5311 ctx.ctx_dsemicolon = 1;
5312 ctx.ctx_res_w = RES_MATCH;
5318 /* We just finished a cmd. New one may start
5319 * with an assignment */
5320 dest.o_assignment = MAYBE_ASSIGNMENT;
5321 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5324 if (done_word(&dest, &ctx)) {
5328 ch = i_getch(input);
5329 nommu_addchr(&ctx.as_string, ch);
5330 done_pipe(&ctx, PIPE_AND);
5332 done_pipe(&ctx, PIPE_BG);
5336 if (done_word(&dest, &ctx)) {
5339 #if ENABLE_HUSH_CASE
5340 if (ctx.ctx_res_w == RES_MATCH)
5341 break; /* we are in case's "word | word)" */
5343 if (next == '|') { /* || */
5344 ch = i_getch(input);
5345 nommu_addchr(&ctx.as_string, ch);
5346 done_pipe(&ctx, PIPE_OR);
5348 /* we could pick up a file descriptor choice here
5349 * with redirect_opt_num(), but bash doesn't do it.
5350 * "echo foo 2| cat" yields "foo 2". */
5355 #if ENABLE_HUSH_CASE
5356 /* "case... in [(]word)..." - skip '(' */
5357 if (ctx.ctx_res_w == RES_MATCH
5358 && ctx.command->argv == NULL /* not (word|(... */
5359 && dest.length == 0 /* not word(... */
5360 && dest.has_quoted_part == 0 /* not ""(... */
5366 if (parse_group(&dest, &ctx, input, ch) != 0) {
5371 #if ENABLE_HUSH_CASE
5372 if (ctx.ctx_res_w == RES_MATCH)
5376 /* proper use of this character is caught by end_trigger:
5377 * if we see {, we call parse_group(..., end_trigger='}')
5378 * and it will match } earlier (not here). */
5379 G.last_exitcode = 2;
5380 syntax_error_unexpected_ch(ch);
5384 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5389 G.last_exitcode = 1;
5392 struct parse_context *pctx;
5393 IF_HAS_KEYWORDS(struct parse_context *p2;)
5395 /* Clean up allocated tree.
5396 * Sample for finding leaks on syntax error recovery path.
5397 * Run it from interactive shell, watch pmap `pidof hush`.
5398 * while if false; then false; fi; do break; fi
5399 * Samples to catch leaks at execution:
5400 * while if (true | { true;}); then echo ok; fi; do break; done
5401 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5405 /* Update pipe/command counts,
5406 * otherwise freeing may miss some */
5407 done_pipe(pctx, PIPE_SEQ);
5408 debug_printf_clean("freeing list %p from ctx %p\n",
5409 pctx->list_head, pctx);
5410 debug_print_tree(pctx->list_head, 0);
5411 free_pipe_list(pctx->list_head);
5412 debug_printf_clean("freed list %p\n", pctx->list_head);
5414 o_free_unsafe(&pctx->as_string);
5416 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5420 IF_HAS_KEYWORDS(pctx = p2;)
5421 } while (HAS_KEYWORDS && pctx);
5434 /*** Execution routines ***/
5436 /* Expansion can recurse, need forward decls: */
5437 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5438 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5439 #define expand_string_to_string(str, do_unbackslash) \
5440 expand_string_to_string(str)
5442 static char *expand_string_to_string(const char *str, int do_unbackslash);
5443 #if ENABLE_HUSH_TICK
5444 static int process_command_subs(o_string *dest, const char *s);
5447 /* expand_strvec_to_strvec() takes a list of strings, expands
5448 * all variable references within and returns a pointer to
5449 * a list of expanded strings, possibly with larger number
5450 * of strings. (Think VAR="a b"; echo $VAR).
5451 * This new list is allocated as a single malloc block.
5452 * NULL-terminated list of char* pointers is at the beginning of it,
5453 * followed by strings themselves.
5454 * Caller can deallocate entire list by single free(list). */
5456 /* A horde of its helpers come first: */
5458 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5460 while (--len >= 0) {
5463 #if ENABLE_HUSH_BRACE_EXPANSION
5464 if (c == '{' || c == '}') {
5465 /* { -> \{, } -> \} */
5467 /* And now we want to add { or } and continue:
5470 * luckily, just falling through achieves this.
5476 /* \z -> \\\z; \<eol> -> \\<eol> */
5481 o_addchr(o, *str++);
5487 /* Store given string, finalizing the word and starting new one whenever
5488 * we encounter IFS char(s). This is used for expanding variable values.
5489 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5490 * Return in *ended_with_ifs:
5491 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5493 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5495 int last_is_ifs = 0;
5500 if (!*str) /* EOL - do not finalize word */
5502 word_len = strcspn(str, G.ifs);
5504 /* We have WORD_LEN leading non-IFS chars */
5505 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5506 o_addblock(output, str, word_len);
5508 /* Protect backslashes against globbing up :)
5509 * Example: "v='\*'; echo b$v" prints "b\*"
5510 * (and does not try to glob on "*")
5512 o_addblock_duplicate_backslash(output, str, word_len);
5513 /*/ Why can't we do it easier? */
5514 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5515 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5519 if (!*str) /* EOL - do not finalize word */
5523 /* We know str here points to at least one IFS char */
5525 str += strspn(str, G.ifs); /* skip IFS chars */
5526 if (!*str) /* EOL - do not finalize word */
5529 /* Start new word... but not always! */
5530 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5531 if (output->has_quoted_part
5532 /* Case "v=' a'; echo $v":
5533 * here nothing precedes the space in $v expansion,
5534 * therefore we should not finish the word
5535 * (IOW: if there *is* word to finalize, only then do it):
5537 || (n > 0 && output->data[output->length - 1])
5539 o_addchr(output, '\0');
5540 debug_print_list("expand_on_ifs", output, n);
5541 n = o_save_ptr(output, n);
5546 *ended_with_ifs = last_is_ifs;
5547 debug_print_list("expand_on_ifs[1]", output, n);
5551 /* Helper to expand $((...)) and heredoc body. These act as if
5552 * they are in double quotes, with the exception that they are not :).
5553 * Just the rules are similar: "expand only $var and `cmd`"
5555 * Returns malloced string.
5556 * As an optimization, we return NULL if expansion is not needed.
5558 #if !BASH_PATTERN_SUBST
5559 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5560 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5561 encode_then_expand_string(str)
5563 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5565 #if !BASH_PATTERN_SUBST
5566 enum { do_unbackslash = 1 };
5569 struct in_str input;
5570 o_string dest = NULL_O_STRING;
5572 if (!strchr(str, '$')
5573 && !strchr(str, '\\')
5574 #if ENABLE_HUSH_TICK
5575 && !strchr(str, '`')
5581 /* We need to expand. Example:
5582 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5584 setup_string_in_str(&input, str);
5585 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5586 //TODO: error check (encode_string returns 0 on error)?
5587 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5588 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5589 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5590 o_free_unsafe(&dest);
5594 #if ENABLE_FEATURE_SH_MATH
5595 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5597 arith_state_t math_state;
5601 math_state.lookupvar = get_local_var_value;
5602 math_state.setvar = set_local_var_from_halves;
5603 //math_state.endofname = endofname;
5604 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5605 res = arith(&math_state, exp_str ? exp_str : arg);
5608 *errmsg_p = math_state.errmsg;
5609 if (math_state.errmsg)
5610 msg_and_die_if_script(math_state.errmsg);
5615 #if BASH_PATTERN_SUBST
5616 /* ${var/[/]pattern[/repl]} helpers */
5617 static char *strstr_pattern(char *val, const char *pattern, int *size)
5620 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5621 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5628 /* Optimization: if "*pat" did not match the start of "string",
5629 * we know that "tring", "ring" etc will not match too:
5631 if (pattern[0] == '*')
5636 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5638 char *result = NULL;
5639 unsigned res_len = 0;
5640 unsigned repl_len = strlen(repl);
5644 char *s = strstr_pattern(val, pattern, &size);
5648 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5649 strcpy(mempcpy(result + res_len, val, s - val), repl);
5650 res_len += (s - val) + repl_len;
5651 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5657 if (*val && result) {
5658 result = xrealloc(result, res_len + strlen(val) + 1);
5659 strcpy(result + res_len, val);
5660 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5662 debug_printf_varexp("result:'%s'\n", result);
5665 #endif /* BASH_PATTERN_SUBST */
5668 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5670 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5672 const char *val = NULL;
5673 char *to_be_freed = NULL;
5678 char exp_save = exp_save; /* for compiler */
5679 char *exp_saveptr; /* points to expansion operator */
5680 char *exp_word = exp_word; /* for compiler */
5683 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5685 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5687 first_char = arg[0] = arg0 & 0x7f;
5690 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5691 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5692 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5693 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5695 /* It must be length operator: ${#var} */
5699 /* Maybe handle parameter expansion */
5700 if (exp_saveptr /* if 2nd char is one of expansion operators */
5701 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5703 /* ${?:0}, ${#[:]%0} etc */
5704 exp_saveptr = var + 1;
5706 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5707 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5709 exp_op = exp_save = *exp_saveptr;
5711 exp_word = exp_saveptr + 1;
5712 if (exp_op == ':') {
5713 exp_op = *exp_word++;
5714 //TODO: try ${var:} and ${var:bogus} in non-bash config
5716 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5718 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5723 *exp_saveptr = '\0';
5724 } /* else: it's not an expansion op, but bare ${var} */
5727 /* Look up the variable in question */
5728 if (isdigit(var[0])) {
5729 /* parse_dollar should have vetted var for us */
5730 int n = xatoi_positive(var);
5731 if (n < G.global_argc)
5732 val = G.global_argv[n];
5733 /* else val remains NULL: $N with too big N */
5737 val = utoa(G.root_pid);
5739 case '!': /* bg pid */
5740 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5742 case '?': /* exitcode */
5743 val = utoa(G.last_exitcode);
5745 case '#': /* argc */
5746 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5749 val = get_local_var_value(var);
5753 /* Handle any expansions */
5754 if (exp_op == 'L') {
5755 reinit_unicode_for_hush();
5756 debug_printf_expand("expand: length(%s)=", val);
5757 val = utoa(val ? unicode_strlen(val) : 0);
5758 debug_printf_expand("%s\n", val);
5759 } else if (exp_op) {
5760 if (exp_op == '%' || exp_op == '#') {
5761 /* Standard-mandated substring removal ops:
5762 * ${parameter%word} - remove smallest suffix pattern
5763 * ${parameter%%word} - remove largest suffix pattern
5764 * ${parameter#word} - remove smallest prefix pattern
5765 * ${parameter##word} - remove largest prefix pattern
5767 * Word is expanded to produce a glob pattern.
5768 * Then var's value is matched to it and matching part removed.
5770 if (val && val[0]) {
5774 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5775 if (exp_op == *exp_word) /* ## or %% */
5777 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5779 exp_word = exp_exp_word;
5780 /* HACK ALERT. We depend here on the fact that
5781 * G.global_argv and results of utoa and get_local_var_value
5782 * are actually in writable memory:
5783 * scan_and_match momentarily stores NULs there. */
5785 loc = scan_and_match(t, exp_word, scan_flags);
5786 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5787 // exp_op, t, exp_word, loc);
5789 if (loc) { /* match was found */
5790 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5791 val = loc; /* take right part */
5793 val = to_be_freed = xstrndup(val, loc - val); /* left */
5797 #if BASH_PATTERN_SUBST
5798 else if (exp_op == '/' || exp_op == '\\') {
5799 /* It's ${var/[/]pattern[/repl]} thing.
5800 * Note that in encoded form it has TWO parts:
5801 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5802 * and if // is used, it is encoded as \:
5803 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5805 /* Empty variable always gives nothing: */
5806 // "v=''; echo ${v/*/w}" prints "", not "w"
5807 if (val && val[0]) {
5808 /* pattern uses non-standard expansion.
5809 * repl should be unbackslashed and globbed
5810 * by the usual expansion rules:
5812 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5813 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5814 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5815 * v='a bz'; echo ${v/a*z/\z} prints "z"
5816 * (note that a*z _pattern_ is never globbed!)
5818 char *pattern, *repl, *t;
5819 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5821 pattern = xstrdup(exp_word);
5822 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5823 *p++ = SPECIAL_VAR_SYMBOL;
5825 p = strchr(p, SPECIAL_VAR_SYMBOL);
5827 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5828 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5829 /* HACK ALERT. We depend here on the fact that
5830 * G.global_argv and results of utoa and get_local_var_value
5831 * are actually in writable memory:
5832 * replace_pattern momentarily stores NULs there. */
5834 to_be_freed = replace_pattern(t,
5836 (repl ? repl : exp_word),
5838 if (to_be_freed) /* at least one replace happened */
5844 #endif /* BASH_PATTERN_SUBST */
5845 else if (exp_op == ':') {
5846 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5847 /* It's ${var:N[:M]} bashism.
5848 * Note that in encoded form it has TWO parts:
5849 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5854 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5857 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5858 *p++ = SPECIAL_VAR_SYMBOL;
5860 p = strchr(p, SPECIAL_VAR_SYMBOL);
5862 len = expand_and_evaluate_arith(exp_word, &errmsg);
5865 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5867 /* negative beg counts from the end */
5868 beg = (arith_t)strlen(val) + beg;
5869 if (beg < 0) /* ${v: -999999} is "" */
5872 debug_printf_varexp("from val:'%s'\n", val);
5874 /* in bash, len=-n means strlen()-n */
5875 len = (arith_t)strlen(val) - beg + len;
5876 if (len < 0) /* bash compat */
5877 msg_and_die_if_script("%s: substring expression < 0", var);
5879 if (len <= 0 || !val || beg >= strlen(val)) {
5883 /* Paranoia. What if user entered 9999999999999
5884 * which fits in arith_t but not int? */
5887 val = to_be_freed = xstrndup(val + beg, len);
5889 debug_printf_varexp("val:'%s'\n", val);
5890 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5891 msg_and_die_if_script("malformed ${%s:...}", var);
5894 } else { /* one of "-=+?" */
5895 /* Standard-mandated substitution ops:
5896 * ${var?word} - indicate error if unset
5897 * If var is unset, word (or a message indicating it is unset
5898 * if word is null) is written to standard error
5899 * and the shell exits with a non-zero exit status.
5900 * Otherwise, the value of var is substituted.
5901 * ${var-word} - use default value
5902 * If var is unset, word is substituted.
5903 * ${var=word} - assign and use default value
5904 * If var is unset, word is assigned to var.
5905 * In all cases, final value of var is substituted.
5906 * ${var+word} - use alternative value
5907 * If var is unset, null is substituted.
5908 * Otherwise, word is substituted.
5910 * Word is subjected to tilde expansion, parameter expansion,
5911 * command substitution, and arithmetic expansion.
5912 * If word is not needed, it is not expanded.
5914 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5915 * but also treat null var as if it is unset.
5917 int use_word = (!val || ((exp_save == ':') && !val[0]));
5919 use_word = !use_word;
5920 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5921 (exp_save == ':') ? "true" : "false", use_word);
5923 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5925 exp_word = to_be_freed;
5926 if (exp_op == '?') {
5927 /* mimic bash message */
5928 msg_and_die_if_script("%s: %s",
5932 : "parameter null or not set"
5933 /* ash has more specific messages, a-la: */
5934 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
5936 //TODO: how interactive bash aborts expansion mid-command?
5941 if (exp_op == '=') {
5942 /* ${var=[word]} or ${var:=[word]} */
5943 if (isdigit(var[0]) || var[0] == '#') {
5944 /* mimic bash message */
5945 msg_and_die_if_script("$%s: cannot assign in this way", var);
5948 char *new_var = xasprintf("%s=%s", var, val);
5949 set_local_var(new_var, /*flag:*/ 0);
5953 } /* one of "-=+?" */
5955 *exp_saveptr = exp_save;
5961 *to_be_freed_pp = to_be_freed;
5965 /* Expand all variable references in given string, adding words to list[]
5966 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5967 * to be filled). This routine is extremely tricky: has to deal with
5968 * variables/parameters with whitespace, $* and $@, and constructs like
5969 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5970 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5972 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5973 * expansion of right-hand side of assignment == 1-element expand.
5975 char cant_be_null = 0; /* only bit 0x80 matters */
5976 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5979 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5980 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5981 debug_print_list("expand_vars_to_list", output, n);
5982 n = o_save_ptr(output, n);
5983 debug_print_list("expand_vars_to_list[0]", output, n);
5985 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5987 char *to_be_freed = NULL;
5988 const char *val = NULL;
5989 #if ENABLE_HUSH_TICK
5990 o_string subst_result = NULL_O_STRING;
5992 #if ENABLE_FEATURE_SH_MATH
5993 char arith_buf[sizeof(arith_t)*3 + 2];
5997 o_addchr(output, '\0');
5998 n = o_save_ptr(output, n);
6002 o_addblock(output, arg, p - arg);
6003 debug_print_list("expand_vars_to_list[1]", output, n);
6005 p = strchr(p, SPECIAL_VAR_SYMBOL);
6007 /* Fetch special var name (if it is indeed one of them)
6008 * and quote bit, force the bit on if singleword expansion -
6009 * important for not getting v=$@ expand to many words. */
6010 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6012 /* Is this variable quoted and thus expansion can't be null?
6013 * "$@" is special. Even if quoted, it can still
6014 * expand to nothing (not even an empty string),
6015 * thus it is excluded. */
6016 if ((first_ch & 0x7f) != '@')
6017 cant_be_null |= first_ch;
6019 switch (first_ch & 0x7f) {
6020 /* Highest bit in first_ch indicates that var is double-quoted */
6024 if (!G.global_argv[1])
6027 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6028 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6029 while (G.global_argv[i]) {
6030 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
6031 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6032 if (G.global_argv[i++][0] && G.global_argv[i]) {
6033 /* this argv[] is not empty and not last:
6034 * put terminating NUL, start new word */
6035 o_addchr(output, '\0');
6036 debug_print_list("expand_vars_to_list[2]", output, n);
6037 n = o_save_ptr(output, n);
6038 debug_print_list("expand_vars_to_list[3]", output, n);
6042 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6043 * and in this case should treat it like '$*' - see 'else...' below */
6044 if (first_ch == ('@'|0x80) /* quoted $@ */
6045 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6048 o_addQstr(output, G.global_argv[i]);
6049 if (++i >= G.global_argc)
6051 o_addchr(output, '\0');
6052 debug_print_list("expand_vars_to_list[4]", output, n);
6053 n = o_save_ptr(output, n);
6055 } else { /* quoted $* (or v="$@" case): add as one word */
6057 o_addQstr(output, G.global_argv[i]);
6058 if (!G.global_argv[++i])
6061 o_addchr(output, G.ifs[0]);
6063 output->has_quoted_part = 1;
6067 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6068 /* "Empty variable", used to make "" etc to not disappear */
6069 output->has_quoted_part = 1;
6071 cant_be_null = 0x80;
6073 case SPECIAL_VAR_QUOTED_SVS:
6074 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6076 val = SPECIAL_VAR_SYMBOL_STR;
6078 #if ENABLE_HUSH_TICK
6079 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6080 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6082 /* Can't just stuff it into output o_string,
6083 * expanded result may need to be globbed
6085 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6086 G.last_exitcode = process_command_subs(&subst_result, arg);
6087 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6088 val = subst_result.data;
6091 #if ENABLE_FEATURE_SH_MATH
6092 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6095 arg++; /* skip '+' */
6096 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6097 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6098 res = expand_and_evaluate_arith(arg, NULL);
6099 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6100 sprintf(arith_buf, ARITH_FMT, res);
6106 val = expand_one_var(&to_be_freed, arg, &p);
6107 IF_HUSH_TICK(store_val:)
6108 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6109 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6110 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6111 if (val && val[0]) {
6112 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6115 } else { /* quoted $VAR, val will be appended below */
6116 output->has_quoted_part = 1;
6117 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6118 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6121 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6123 if (val && val[0]) {
6124 o_addQstr(output, val);
6128 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6129 * Do the check to avoid writing to a const string. */
6130 if (*p != SPECIAL_VAR_SYMBOL)
6131 *p = SPECIAL_VAR_SYMBOL;
6133 #if ENABLE_HUSH_TICK
6134 o_free(&subst_result);
6137 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6141 o_addchr(output, '\0');
6142 n = o_save_ptr(output, n);
6144 debug_print_list("expand_vars_to_list[a]", output, n);
6145 /* this part is literal, and it was already pre-quoted
6146 * if needed (much earlier), do not use o_addQstr here! */
6147 o_addstr_with_NUL(output, arg);
6148 debug_print_list("expand_vars_to_list[b]", output, n);
6149 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6150 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6153 /* allow to reuse list[n] later without re-growth */
6154 output->has_empty_slot = 1;
6156 o_addchr(output, '\0');
6162 static char **expand_variables(char **argv, unsigned expflags)
6166 o_string output = NULL_O_STRING;
6168 output.o_expflags = expflags;
6172 n = expand_vars_to_list(&output, n, *argv);
6175 debug_print_list("expand_variables", &output, n);
6177 /* output.data (malloced in one block) gets returned in "list" */
6178 list = o_finalize_list(&output, n);
6179 debug_print_strings("expand_variables[1]", list);
6183 static char **expand_strvec_to_strvec(char **argv)
6185 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6189 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6191 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6195 /* Used for expansion of right hand of assignments,
6196 * $((...)), heredocs, variable espansion parts.
6198 * NB: should NOT do globbing!
6199 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6201 static char *expand_string_to_string(const char *str, int do_unbackslash)
6203 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6204 const int do_unbackslash = 1;
6206 char *argv[2], **list;
6208 debug_printf_expand("string_to_string<='%s'\n", str);
6209 /* This is generally an optimization, but it also
6210 * handles "", which otherwise trips over !list[0] check below.
6211 * (is this ever happens that we actually get str="" here?)
6213 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6214 //TODO: Can use on strings with \ too, just unbackslash() them?
6215 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6216 return xstrdup(str);
6219 argv[0] = (char*)str;
6221 list = expand_variables(argv, do_unbackslash
6222 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6223 : EXP_FLAG_SINGLEWORD
6226 if (!list[0] || list[1])
6227 bb_error_msg_and_die("BUG in varexp2");
6228 /* actually, just move string 2*sizeof(char*) bytes back */
6229 overlapping_strcpy((char*)list, list[0]);
6231 unbackslash((char*)list);
6232 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6236 #if ENABLE_HUSH_CASE
6237 static char* expand_strvec_to_string(char **argv)
6241 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6242 /* Convert all NULs to spaces */
6247 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6248 bb_error_msg_and_die("BUG in varexp3");
6249 /* bash uses ' ' regardless of $IFS contents */
6254 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6255 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6260 static char **expand_assignments(char **argv, int count)
6265 G.expanded_assignments = p = NULL;
6266 /* Expand assignments into one string each */
6267 for (i = 0; i < count; i++) {
6268 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6270 G.expanded_assignments = NULL;
6275 static void switch_off_special_sigs(unsigned mask)
6278 while ((mask >>= 1) != 0) {
6282 #if ENABLE_HUSH_TRAP
6284 if (G_traps[sig] && !G_traps[sig][0])
6285 /* trap is '', has to remain SIG_IGN */
6288 G_traps[sig] = NULL;
6291 /* We are here only if no trap or trap was not '' */
6292 install_sighandler(sig, SIG_DFL);
6298 void re_execute_shell(char ***to_free, const char *s,
6299 char *g_argv0, char **g_argv,
6300 char **builtin_argv) NORETURN;
6302 static void reset_traps_to_defaults(void)
6304 /* This function is always called in a child shell
6305 * after fork (not vfork, NOMMU doesn't use this function).
6307 IF_HUSH_TRAP(unsigned sig;)
6310 /* Child shells are not interactive.
6311 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6312 * Testcase: (while :; do :; done) + ^Z should background.
6313 * Same goes for SIGTERM, SIGHUP, SIGINT.
6315 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6316 if (!G_traps && !mask)
6317 return; /* already no traps and no special sigs */
6319 /* Switch off special sigs */
6320 switch_off_special_sigs(mask);
6321 # if ENABLE_HUSH_JOB
6322 G_fatal_sig_mask = 0;
6324 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6325 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6326 * remain set in G.special_sig_mask */
6328 # if ENABLE_HUSH_TRAP
6332 /* Reset all sigs to default except ones with empty traps */
6333 for (sig = 0; sig < NSIG; sig++) {
6335 continue; /* no trap: nothing to do */
6336 if (!G_traps[sig][0])
6337 continue; /* empty trap: has to remain SIG_IGN */
6338 /* sig has non-empty trap, reset it: */
6340 G_traps[sig] = NULL;
6341 /* There is no signal for trap 0 (EXIT) */
6344 install_sighandler(sig, pick_sighandler(sig));
6351 static void re_execute_shell(char ***to_free, const char *s,
6352 char *g_argv0, char **g_argv,
6353 char **builtin_argv) NORETURN;
6354 static void re_execute_shell(char ***to_free, const char *s,
6355 char *g_argv0, char **g_argv,
6356 char **builtin_argv)
6358 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6359 /* delims + 2 * (number of bytes in printed hex numbers) */
6360 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6361 char *heredoc_argv[4];
6362 struct variable *cur;
6363 # if ENABLE_HUSH_FUNCTIONS
6364 struct function *funcp;
6368 unsigned long long empty_trap_mask;
6370 if (!g_argv0) { /* heredoc */
6371 argv = heredoc_argv;
6372 argv[0] = (char *) G.argv0_for_re_execing;
6373 argv[1] = (char *) "-<";
6374 argv[2] = (char *) s;
6376 pp = &argv[3]; /* used as pointer to empty environment */
6382 if (pp) while (*pp++)
6385 empty_trap_mask = 0;
6388 for (sig = 1; sig < NSIG; sig++) {
6389 if (G_traps[sig] && !G_traps[sig][0])
6390 empty_trap_mask |= 1LL << sig;
6394 sprintf(param_buf, NOMMU_HACK_FMT
6395 , (unsigned) G.root_pid
6396 , (unsigned) G.root_ppid
6397 , (unsigned) G.last_bg_pid
6398 , (unsigned) G.last_exitcode
6401 IF_HUSH_LOOPS(, G.depth_of_loop)
6403 # undef NOMMU_HACK_FMT
6404 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6405 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6408 for (cur = G.top_var; cur; cur = cur->next) {
6409 if (!cur->flg_export || cur->flg_read_only)
6412 # if ENABLE_HUSH_FUNCTIONS
6413 for (funcp = G.top_func; funcp; funcp = funcp->next)
6419 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6420 *pp++ = (char *) G.argv0_for_re_execing;
6422 for (cur = G.top_var; cur; cur = cur->next) {
6423 if (strcmp(cur->varstr, hush_version_str) == 0)
6425 if (cur->flg_read_only) {
6426 *pp++ = (char *) "-R";
6427 *pp++ = cur->varstr;
6428 } else if (!cur->flg_export) {
6429 *pp++ = (char *) "-V";
6430 *pp++ = cur->varstr;
6433 # if ENABLE_HUSH_FUNCTIONS
6434 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6435 *pp++ = (char *) "-F";
6436 *pp++ = funcp->name;
6437 *pp++ = funcp->body_as_string;
6440 /* We can pass activated traps here. Say, -Tnn:trap_string
6442 * However, POSIX says that subshells reset signals with traps
6444 * I tested bash-3.2 and it not only does that with true subshells
6445 * of the form ( list ), but with any forked children shells.
6446 * I set trap "echo W" WINCH; and then tried:
6448 * { echo 1; sleep 20; echo 2; } &
6449 * while true; do echo 1; sleep 20; echo 2; break; done &
6450 * true | { echo 1; sleep 20; echo 2; } | cat
6452 * In all these cases sending SIGWINCH to the child shell
6453 * did not run the trap. If I add trap "echo V" WINCH;
6454 * _inside_ group (just before echo 1), it works.
6456 * I conclude it means we don't need to pass active traps here.
6458 *pp++ = (char *) "-c";
6461 while (*++builtin_argv)
6462 *pp++ = *builtin_argv;
6463 *pp++ = (char *) "";
6468 /* *pp = NULL; - is already there */
6472 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6473 /* Don't propagate SIG_IGN to the child */
6474 if (SPECIAL_JOBSTOP_SIGS != 0)
6475 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6476 execve(bb_busybox_exec_path, argv, pp);
6477 /* Fallback. Useful for init=/bin/hush usage etc */
6478 if (argv[0][0] == '/')
6479 execve(argv[0], argv, pp);
6480 xfunc_error_retval = 127;
6481 bb_error_msg_and_die("can't re-execute the shell");
6483 #endif /* !BB_MMU */
6486 static int run_and_free_list(struct pipe *pi);
6488 /* Executing from string: eval, sh -c '...'
6489 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6490 * end_trigger controls how often we stop parsing
6491 * NUL: parse all, execute, return
6492 * ';': parse till ';' or newline, execute, repeat till EOF
6494 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6496 /* Why we need empty flag?
6497 * An obscure corner case "false; ``; echo $?":
6498 * empty command in `` should still set $? to 0.
6499 * But we can't just set $? to 0 at the start,
6500 * this breaks "false; echo `echo $?`" case.
6504 struct pipe *pipe_list;
6506 #if ENABLE_HUSH_INTERACTIVE
6507 if (end_trigger == ';')
6508 inp->promptmode = 0; /* PS1 */
6510 pipe_list = parse_stream(NULL, inp, end_trigger);
6511 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6512 /* If we are in "big" script
6513 * (not in `cmd` or something similar)...
6515 if (pipe_list == ERR_PTR && end_trigger == ';') {
6516 /* Discard cached input (rest of line) */
6517 int ch = inp->last_char;
6518 while (ch != EOF && ch != '\n') {
6519 //bb_error_msg("Discarded:'%c'", ch);
6524 /* This stream isn't empty */
6528 if (!pipe_list && empty)
6529 G.last_exitcode = 0;
6532 debug_print_tree(pipe_list, 0);
6533 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6534 run_and_free_list(pipe_list);
6536 if (G_flag_return_in_progress == 1)
6541 static void parse_and_run_string(const char *s)
6543 struct in_str input;
6544 setup_string_in_str(&input, s);
6545 parse_and_run_stream(&input, '\0');
6548 static void parse_and_run_file(FILE *f)
6550 struct in_str input;
6557 setup_file_in_str(&input, f);
6558 parse_and_run_stream(&input, ';');
6564 #if ENABLE_HUSH_TICK
6565 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6570 char **to_free = NULL;
6574 pid = BB_MMU ? xfork() : xvfork();
6575 if (pid == 0) { /* child */
6576 disable_restore_tty_pgrp_on_exit();
6577 /* Process substitution is not considered to be usual
6578 * 'command execution'.
6579 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6586 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6587 close(channel[0]); /* NB: close _first_, then move fd! */
6588 xmove_fd(channel[1], 1);
6589 /* Prevent it from trying to handle ctrl-z etc */
6590 IF_HUSH_JOB(G.run_list_level = 1;)
6591 # if ENABLE_HUSH_TRAP
6592 /* Awful hack for `trap` or $(trap).
6594 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6595 * contains an example where "trap" is executed in a subshell:
6597 * save_traps=$(trap)
6599 * eval "$save_traps"
6601 * Standard does not say that "trap" in subshell shall print
6602 * parent shell's traps. It only says that its output
6603 * must have suitable form, but then, in the above example
6604 * (which is not supposed to be normative), it implies that.
6606 * bash (and probably other shell) does implement it
6607 * (traps are reset to defaults, but "trap" still shows them),
6608 * but as a result, "trap" logic is hopelessly messed up:
6611 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6612 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6613 * # true | trap <--- trap is in subshell - no output (ditto)
6614 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6615 * trap -- 'echo Ho' SIGWINCH
6616 * # echo `(trap)` <--- in subshell in subshell - output
6617 * trap -- 'echo Ho' SIGWINCH
6618 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6619 * trap -- 'echo Ho' SIGWINCH
6621 * The rules when to forget and when to not forget traps
6622 * get really complex and nonsensical.
6624 * Our solution: ONLY bare $(trap) or `trap` is special.
6626 s = skip_whitespace(s);
6627 if (is_prefixed_with(s, "trap")
6628 && skip_whitespace(s + 4)[0] == '\0'
6630 static const char *const argv[] = { NULL, NULL };
6631 builtin_trap((char**)argv);
6632 fflush_all(); /* important */
6637 reset_traps_to_defaults();
6638 parse_and_run_string(s);
6639 _exit(G.last_exitcode);
6641 /* We re-execute after vfork on NOMMU. This makes this script safe:
6642 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6643 * huge=`cat BIG` # was blocking here forever
6646 re_execute_shell(&to_free,
6656 # if ENABLE_HUSH_FAST
6658 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6659 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6660 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6662 enable_restore_tty_pgrp_on_exit();
6667 return remember_FILE(xfdopen_for_read(channel[0]));
6670 /* Return code is exit status of the process that is run. */
6671 static int process_command_subs(o_string *dest, const char *s)
6674 struct in_str pipe_str;
6676 int status, ch, eol_cnt;
6678 fp = generate_stream_from_string(s, &pid);
6680 /* Now send results of command back into original context */
6681 setup_file_in_str(&pipe_str, fp);
6683 while ((ch = i_getch(&pipe_str)) != EOF) {
6689 o_addchr(dest, '\n');
6692 o_addQchr(dest, ch);
6695 debug_printf("done reading from `cmd` pipe, closing it\n");
6696 fclose_and_forget(fp);
6697 /* We need to extract exitcode. Test case
6698 * "true; echo `sleep 1; false` $?"
6700 safe_waitpid(pid, &status, 0);
6701 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6702 return WEXITSTATUS(status);
6704 #endif /* ENABLE_HUSH_TICK */
6707 static void setup_heredoc(struct redir_struct *redir)
6709 struct fd_pair pair;
6712 /* the _body_ of heredoc (misleading field name) */
6713 const char *heredoc = redir->rd_filename;
6720 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6721 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6725 len = strlen(heredoc);
6727 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6729 xmove_fd(pair.rd, redir->rd_fd);
6731 /* Try writing without forking. Newer kernels have
6732 * dynamically growing pipes. Must use non-blocking write! */
6735 written = write(pair.wr, heredoc, len);
6746 ndelay_off(pair.wr);
6748 /* Okay, pipe buffer was not big enough */
6749 /* Note: we must not create a stray child (bastard? :)
6750 * for the unsuspecting parent process. Child creates a grandchild
6751 * and exits before parent execs the process which consumes heredoc
6752 * (that exec happens after we return from this function) */
6759 disable_restore_tty_pgrp_on_exit();
6760 pid = BB_MMU ? xfork() : xvfork();
6764 close(redir->rd_fd); /* read side of the pipe */
6766 full_write(pair.wr, heredoc, len); /* may loop or block */
6769 /* Delegate blocking writes to another process */
6770 xmove_fd(pair.wr, STDOUT_FILENO);
6771 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6775 #if ENABLE_HUSH_FAST
6777 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6779 enable_restore_tty_pgrp_on_exit();
6785 wait(NULL); /* wait till child has died */
6791 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6792 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6795 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6797 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6798 sq[i].orig_fd = orig;
6799 sq[i].moved_to = moved;
6800 sq[i+1].orig_fd = -1; /* end marker */
6804 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6810 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6811 /* If we collide with an already moved fd... */
6812 if (fd == sq[i].moved_to) {
6813 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6814 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6815 if (sq[i].moved_to < 0) /* what? */
6819 if (fd == sq[i].orig_fd) {
6820 /* Example: echo Hello >/dev/null 1>&2 */
6821 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6826 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6827 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6828 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6829 if (moved_to < 0 && errno != EBADF)
6831 return append_squirrel(sq, i, fd, moved_to);
6834 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6839 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6840 /* If we collide with an already moved fd... */
6841 if (fd == sq[i].orig_fd) {
6843 * "echo 3>FILE 3>&- 3>FILE"
6844 * "echo 3>&- 3>FILE"
6845 * No need for last redirect to insert
6846 * another "need to close 3" indicator.
6848 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6853 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6854 return append_squirrel(sq, i, fd, -1);
6857 /* fd: redirect wants this fd to be used (e.g. 3>file).
6858 * Move all conflicting internally used fds,
6859 * and remember them so that we can restore them later.
6861 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6863 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6866 #if ENABLE_HUSH_INTERACTIVE
6867 if (fd == G.interactive_fd) {
6868 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6869 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6870 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6871 return 1; /* "we closed fd" */
6874 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6875 * (1) Redirect in a forked child. No need to save FILEs' fds,
6876 * we aren't going to use them anymore, ok to trash.
6877 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6878 * but how are we doing to restore them?
6879 * "fileno(fd) = new_fd" can't be done.
6884 /* If this one of script's fds? */
6885 if (save_FILEs_on_redirect(fd, avoid_fd))
6886 return 1; /* yes. "we closed fd" */
6888 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6889 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6890 return 0; /* "we did not close fd" */
6893 static void restore_redirects(struct squirrel *sq)
6897 for (i = 0; sq[i].orig_fd >= 0; i++) {
6898 if (sq[i].moved_to >= 0) {
6899 /* We simply die on error */
6900 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6901 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6903 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6904 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6905 close(sq[i].orig_fd);
6911 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6913 restore_redirected_FILEs();
6916 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6917 static void close_saved_fds_and_FILE_fds(void)
6919 if (G_interactive_fd)
6920 close(G_interactive_fd);
6921 close_all_FILE_list();
6925 static int internally_opened_fd(int fd, struct squirrel *sq)
6929 #if ENABLE_HUSH_INTERACTIVE
6930 if (fd == G.interactive_fd)
6933 /* If this one of script's fds? */
6934 if (fd_in_FILEs(fd))
6937 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6938 if (fd == sq[i].moved_to)
6944 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6945 * and stderr if they are redirected. */
6946 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6948 struct redir_struct *redir;
6950 for (redir = prog->redirects; redir; redir = redir->next) {
6954 if (redir->rd_type == REDIRECT_HEREDOC2) {
6955 /* "rd_fd<<HERE" case */
6956 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6957 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6959 debug_printf_parse("set heredoc '%s'\n",
6960 redir->rd_filename);
6961 setup_heredoc(redir);
6965 if (redir->rd_dup == REDIRFD_TO_FILE) {
6966 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6970 if (redir->rd_filename == NULL) {
6973 * "cmd >" (no filename)
6974 * "cmd > <file" (2nd redirect starts too early)
6976 syntax_error("invalid redirect");
6979 mode = redir_table[redir->rd_type].mode;
6980 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6981 newfd = open_or_warn(p, mode);
6984 /* Error message from open_or_warn can be lost
6985 * if stderr has been redirected, but bash
6986 * and ash both lose it as well
6987 * (though zsh doesn't!)
6991 if (newfd == redir->rd_fd && sqp) {
6992 /* open() gave us precisely the fd we wanted.
6993 * This means that this fd was not busy
6994 * (not opened to anywhere).
6995 * Remember to close it on restore:
6997 *sqp = add_squirrel_closed(*sqp, newfd);
6998 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7001 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7002 newfd = redir->rd_dup;
7005 if (newfd == redir->rd_fd)
7008 /* if "N>FILE": move newfd to redir->rd_fd */
7009 /* if "N>&M": dup newfd to redir->rd_fd */
7010 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7012 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7013 if (newfd == REDIRFD_CLOSE) {
7014 /* "N>&-" means "close me" */
7016 /* ^^^ optimization: saving may already
7017 * have closed it. If not... */
7018 close(redir->rd_fd);
7020 /* Sometimes we do another close on restore, getting EBADF.
7021 * Consider "echo 3>FILE 3>&-"
7022 * first redirect remembers "need to close 3",
7023 * and second redirect closes 3! Restore code then closes 3 again.
7026 /* if newfd is a script fd or saved fd, simulate EBADF */
7027 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7029 //bb_perror_msg_and_die("can't duplicate file descriptor");
7030 newfd = -1; /* same effect as code above */
7032 xdup2(newfd, redir->rd_fd);
7033 if (redir->rd_dup == REDIRFD_TO_FILE)
7034 /* "rd_fd > FILE" */
7036 /* else: "rd_fd > rd_dup" */
7042 static char *find_in_path(const char *arg)
7045 const char *PATH = get_local_var_value("PATH");
7051 const char *end = strchrnul(PATH, ':');
7052 int sz = end - PATH; /* must be int! */
7056 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7058 /* We have xxx::yyyy in $PATH,
7059 * it means "use current dir" */
7062 if (access(ret, F_OK) == 0)
7075 static const struct built_in_command *find_builtin_helper(const char *name,
7076 const struct built_in_command *x,
7077 const struct built_in_command *end)
7080 if (strcmp(name, x->b_cmd) != 0) {
7084 debug_printf_exec("found builtin '%s'\n", name);
7089 static const struct built_in_command *find_builtin1(const char *name)
7091 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7093 static const struct built_in_command *find_builtin(const char *name)
7095 const struct built_in_command *x = find_builtin1(name);
7098 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7101 #if ENABLE_HUSH_FUNCTIONS
7102 static struct function **find_function_slot(const char *name)
7104 struct function **funcpp = &G.top_func;
7106 if (strcmp(name, (*funcpp)->name) == 0) {
7109 funcpp = &(*funcpp)->next;
7114 static const struct function *find_function(const char *name)
7116 const struct function *funcp = *find_function_slot(name);
7118 debug_printf_exec("found function '%s'\n", name);
7122 /* Note: takes ownership on name ptr */
7123 static struct function *new_function(char *name)
7125 struct function **funcpp = find_function_slot(name);
7126 struct function *funcp = *funcpp;
7128 if (funcp != NULL) {
7129 struct command *cmd = funcp->parent_cmd;
7130 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7132 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7134 /* Note: if !funcp->body, do not free body_as_string!
7135 * This is a special case of "-F name body" function:
7136 * body_as_string was not malloced! */
7138 free_pipe_list(funcp->body);
7140 free(funcp->body_as_string);
7144 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7145 cmd->argv[0] = funcp->name;
7146 cmd->group = funcp->body;
7148 cmd->group_as_string = funcp->body_as_string;
7152 debug_printf_exec("remembering new function '%s'\n", name);
7153 funcp = *funcpp = xzalloc(sizeof(*funcp));
7154 /*funcp->next = NULL;*/
7161 # if ENABLE_HUSH_UNSET
7162 static void unset_func(const char *name)
7164 struct function **funcpp = find_function_slot(name);
7165 struct function *funcp = *funcpp;
7167 if (funcp != NULL) {
7168 debug_printf_exec("freeing function '%s'\n", funcp->name);
7169 *funcpp = funcp->next;
7170 /* funcp is unlinked now, deleting it.
7171 * Note: if !funcp->body, the function was created by
7172 * "-F name body", do not free ->body_as_string
7173 * and ->name as they were not malloced. */
7175 free_pipe_list(funcp->body);
7178 free(funcp->body_as_string);
7187 #define exec_function(to_free, funcp, argv) \
7188 exec_function(funcp, argv)
7190 static void exec_function(char ***to_free,
7191 const struct function *funcp,
7192 char **argv) NORETURN;
7193 static void exec_function(char ***to_free,
7194 const struct function *funcp,
7200 argv[0] = G.global_argv[0];
7201 G.global_argv = argv;
7202 G.global_argc = n = 1 + string_array_len(argv + 1);
7204 // Example when we are here: "cmd | func"
7205 // func will run with saved-redirect fds open.
7206 // $ f() { echo /proc/self/fd/*; }
7208 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7209 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7212 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7213 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7214 // They are CLOEXEC so external programs won't see them, but
7215 // for "more correctness" we might want to close those extra fds here:
7216 //? close_saved_fds_and_FILE_fds();
7218 /* "we are in function, ok to use return" */
7219 G_flag_return_in_progress = -1;
7220 IF_HUSH_LOCAL(G.func_nest_level++;)
7222 /* On MMU, funcp->body is always non-NULL */
7223 n = run_list(funcp->body);
7227 //? close_saved_fds_and_FILE_fds();
7229 //TODO: check whether "true | func_with_return" works
7231 re_execute_shell(to_free,
7232 funcp->body_as_string,
7239 static int run_function(const struct function *funcp, char **argv)
7245 save_and_replace_G_args(&sv, argv);
7247 /* "we are in function, ok to use return" */
7248 sv_flg = G_flag_return_in_progress;
7249 G_flag_return_in_progress = -1;
7250 IF_HUSH_LOCAL(G.func_nest_level++;)
7252 /* On MMU, funcp->body is always non-NULL */
7255 /* Function defined by -F */
7256 parse_and_run_string(funcp->body_as_string);
7257 rc = G.last_exitcode;
7261 rc = run_list(funcp->body);
7264 # if ENABLE_HUSH_LOCAL
7266 struct variable *var;
7267 struct variable **var_pp;
7269 var_pp = &G.top_var;
7270 while ((var = *var_pp) != NULL) {
7271 if (var->func_nest_level < G.func_nest_level) {
7272 var_pp = &var->next;
7276 if (var->flg_export)
7277 bb_unsetenv(var->varstr);
7278 /* Remove from global list */
7279 *var_pp = var->next;
7285 G.func_nest_level--;
7288 G_flag_return_in_progress = sv_flg;
7290 restore_G_args(&sv, argv);
7294 #endif /* ENABLE_HUSH_FUNCTIONS */
7298 #define exec_builtin(to_free, x, argv) \
7299 exec_builtin(x, argv)
7301 #define exec_builtin(to_free, x, argv) \
7302 exec_builtin(to_free, argv)
7304 static void exec_builtin(char ***to_free,
7305 const struct built_in_command *x,
7306 char **argv) NORETURN;
7307 static void exec_builtin(char ***to_free,
7308 const struct built_in_command *x,
7314 //? close_saved_fds_and_FILE_fds();
7315 rcode = x->b_function(argv);
7320 /* On NOMMU, we must never block!
7321 * Example: { sleep 99 | read line; } & echo Ok
7323 re_execute_shell(to_free,
7332 static void execvp_or_die(char **argv) NORETURN;
7333 static void execvp_or_die(char **argv)
7336 debug_printf_exec("execing '%s'\n", argv[0]);
7337 /* Don't propagate SIG_IGN to the child */
7338 if (SPECIAL_JOBSTOP_SIGS != 0)
7339 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7340 execvp(argv[0], argv);
7342 if (errno == EACCES) e = 126;
7343 if (errno == ENOENT) e = 127;
7344 bb_perror_msg("can't execute '%s'", argv[0]);
7348 #if ENABLE_HUSH_MODE_X
7349 static void dump_cmd_in_x_mode(char **argv)
7351 if (G_x_mode && argv) {
7352 /* We want to output the line in one write op */
7360 len += strlen(argv[n++]) + 1;
7366 p += sprintf(p, " %s", argv[n++]);
7374 # define dump_cmd_in_x_mode(argv) ((void)0)
7377 #if ENABLE_HUSH_COMMAND
7378 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7387 char *path = getenv("PATH");
7388 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
7390 _exit(1); /* PROG was not found */
7392 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7394 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
7400 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
7404 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7405 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7406 #define pseudo_exec(nommu_save, command, argv_expanded) \
7407 pseudo_exec(command, argv_expanded)
7410 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7412 * Don't exit() here. If you don't exec, use _exit instead.
7413 * The at_exit handlers apparently confuse the calling process,
7414 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7416 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7417 char **argv, int assignment_cnt,
7418 char **argv_expanded) NORETURN;
7419 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7420 char **argv, int assignment_cnt,
7421 char **argv_expanded)
7423 const struct built_in_command *x;
7425 #if ENABLE_HUSH_COMMAND
7429 new_env = expand_assignments(argv, assignment_cnt);
7430 dump_cmd_in_x_mode(new_env);
7432 if (!argv[assignment_cnt]) {
7433 /* Case when we are here: ... | var=val | ...
7434 * (note that we do not exit early, i.e., do not optimize out
7435 * expand_assignments(): think about ... | var=`sleep 1` | ...
7437 free_strings(new_env);
7438 _exit(EXIT_SUCCESS);
7442 set_vars_and_save_old(new_env);
7443 free(new_env); /* optional */
7444 /* we can also destroy set_vars_and_save_old's return value,
7447 nommu_save->new_env = new_env;
7448 nommu_save->old_vars = set_vars_and_save_old(new_env);
7451 if (argv_expanded) {
7452 argv = argv_expanded;
7454 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7456 nommu_save->argv = argv;
7459 dump_cmd_in_x_mode(argv);
7461 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7462 if (strchr(argv[0], '/') != NULL)
7466 #if ENABLE_HUSH_FUNCTIONS
7467 /* Check if the command matches any functions (this goes before bltins) */
7469 const struct function *funcp = find_function(argv[0]);
7471 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7476 #if ENABLE_HUSH_COMMAND
7477 /* "command BAR": run BAR without looking it up among functions
7478 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7479 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7481 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7486 if (p[0] != '-' || !p[1])
7487 continue; /* bash allows "command command command [-OPT] BAR" */
7495 if (p[0] != '-' || !p[1])
7497 continue; /* next arg is also -opts, process it too */
7503 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7508 # if ENABLE_HUSH_FUNCTIONS
7509 if (opt_vV && find_function(argv[0]))
7510 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7514 /* Check if the command matches any of the builtins.
7515 * Depending on context, this might be redundant. But it's
7516 * easier to waste a few CPU cycles than it is to figure out
7517 * if this is one of those cases.
7519 /* Why "BB_MMU ? :" difference in logic? -
7520 * On NOMMU, it is more expensive to re-execute shell
7521 * just in order to run echo or test builtin.
7522 * It's better to skip it here and run corresponding
7523 * non-builtin later. */
7524 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7526 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7527 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7530 #if ENABLE_FEATURE_SH_STANDALONE
7531 /* Check if the command matches any busybox applets */
7533 int a = find_applet_by_name(argv[0]);
7535 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
7536 # if BB_MMU /* see above why on NOMMU it is not allowed */
7537 if (APPLET_IS_NOEXEC(a)) {
7538 /* Do not leak open fds from opened script files etc.
7539 * Testcase: interactive "ls -l /proc/self/fd"
7540 * should not show tty fd open.
7542 close_saved_fds_and_FILE_fds();
7543 //FIXME: should also close saved redir fds
7544 /* Without this, "rm -i FILE" can't be ^C'ed: */
7545 switch_off_special_sigs(G.special_sig_mask);
7546 debug_printf_exec("running applet '%s'\n", argv[0]);
7547 run_noexec_applet_and_exit(a, argv[0], argv);
7550 /* Re-exec ourselves */
7551 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7552 /* Don't propagate SIG_IGN to the child */
7553 if (SPECIAL_JOBSTOP_SIGS != 0)
7554 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7555 execv(bb_busybox_exec_path, argv);
7556 /* If they called chroot or otherwise made the binary no longer
7557 * executable, fall through */
7562 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7565 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
7566 execvp_or_die(argv);
7569 /* Called after [v]fork() in run_pipe
7571 static void pseudo_exec(nommu_save_t *nommu_save,
7572 struct command *command,
7573 char **argv_expanded) NORETURN;
7574 static void pseudo_exec(nommu_save_t *nommu_save,
7575 struct command *command,
7576 char **argv_expanded)
7578 if (command->argv) {
7579 pseudo_exec_argv(nommu_save, command->argv,
7580 command->assignment_cnt, argv_expanded);
7583 if (command->group) {
7584 /* Cases when we are here:
7587 * ... | ( list ) | ...
7588 * ... | { list } | ...
7592 debug_printf_exec("pseudo_exec: run_list\n");
7593 reset_traps_to_defaults();
7594 rcode = run_list(command->group);
7595 /* OK to leak memory by not calling free_pipe_list,
7596 * since this process is about to exit */
7599 re_execute_shell(&nommu_save->argv_from_re_execing,
7600 command->group_as_string,
7607 /* Case when we are here: ... | >file */
7608 debug_printf_exec("pseudo_exec'ed null command\n");
7609 _exit(EXIT_SUCCESS);
7613 static const char *get_cmdtext(struct pipe *pi)
7619 /* This is subtle. ->cmdtext is created only on first backgrounding.
7620 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7621 * On subsequent bg argv is trashed, but we won't use it */
7625 argv = pi->cmds[0].argv;
7627 pi->cmdtext = xzalloc(1);
7632 len += strlen(*argv) + 1;
7636 argv = pi->cmds[0].argv;
7638 p = stpcpy(p, *argv);
7645 static void remove_job_from_table(struct pipe *pi)
7647 struct pipe *prev_pipe;
7649 if (pi == G.job_list) {
7650 G.job_list = pi->next;
7652 prev_pipe = G.job_list;
7653 while (prev_pipe->next != pi)
7654 prev_pipe = prev_pipe->next;
7655 prev_pipe->next = pi->next;
7659 G.last_jobid = G.job_list->jobid;
7662 static void delete_finished_job(struct pipe *pi)
7664 remove_job_from_table(pi);
7668 static void clean_up_last_dead_job(void)
7670 if (G.job_list && !G.job_list->alive_cmds)
7671 delete_finished_job(G.job_list);
7674 static void insert_job_into_table(struct pipe *pi)
7676 struct pipe *job, **jobp;
7679 clean_up_last_dead_job();
7681 /* Find the end of the list, and find next job ID to use */
7684 while ((job = *jobp) != NULL) {
7691 /* Create a new job struct at the end */
7692 job = *jobp = xmemdup(pi, sizeof(*pi));
7694 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7695 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7696 for (i = 0; i < pi->num_cmds; i++) {
7697 job->cmds[i].pid = pi->cmds[i].pid;
7698 /* all other fields are not used and stay zero */
7700 job->cmdtext = xstrdup(get_cmdtext(pi));
7702 if (G_interactive_fd)
7703 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7704 G.last_jobid = job->jobid;
7708 static int job_exited_or_stopped(struct pipe *pi)
7712 if (pi->alive_cmds != pi->stopped_cmds)
7715 /* All processes in fg pipe have exited or stopped */
7719 rcode = pi->cmds[i].cmd_exitcode;
7720 /* usually last process gives overall exitstatus,
7721 * but with "set -o pipefail", last *failed* process does */
7722 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7725 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7729 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7736 dead = WIFEXITED(status) || WIFSIGNALED(status);
7739 if (WIFSTOPPED(status))
7740 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7741 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7742 if (WIFSIGNALED(status))
7743 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7744 childpid, WTERMSIG(status), WEXITSTATUS(status));
7745 if (WIFEXITED(status))
7746 debug_printf_jobs("pid %d exited, exitcode %d\n",
7747 childpid, WEXITSTATUS(status));
7749 /* Were we asked to wait for a fg pipe? */
7751 i = fg_pipe->num_cmds;
7756 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7757 if (fg_pipe->cmds[i].pid != childpid)
7761 fg_pipe->cmds[i].pid = 0;
7762 fg_pipe->alive_cmds--;
7763 ex = WEXITSTATUS(status);
7764 /* bash prints killer signal's name for *last*
7765 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7766 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7768 if (WIFSIGNALED(status)) {
7769 int sig = WTERMSIG(status);
7770 if (i == fg_pipe->num_cmds-1)
7771 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7772 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7773 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7774 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7775 * Maybe we need to use sig | 128? */
7778 fg_pipe->cmds[i].cmd_exitcode = ex;
7780 fg_pipe->stopped_cmds++;
7782 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7783 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7784 rcode = job_exited_or_stopped(fg_pipe);
7786 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7787 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7788 * and "killall -STOP cat" */
7789 if (G_interactive_fd) {
7791 if (fg_pipe->alive_cmds != 0)
7792 insert_job_into_table(fg_pipe);
7796 if (fg_pipe->alive_cmds == 0)
7799 /* There are still running processes in the fg_pipe */
7802 /* It wasn't in fg_pipe, look for process in bg pipes */
7806 /* We were asked to wait for bg or orphaned children */
7807 /* No need to remember exitcode in this case */
7808 for (pi = G.job_list; pi; pi = pi->next) {
7809 for (i = 0; i < pi->num_cmds; i++) {
7810 if (pi->cmds[i].pid == childpid)
7811 goto found_pi_and_prognum;
7814 /* Happens when shell is used as init process (init=/bin/sh) */
7815 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7816 return -1; /* this wasn't a process from fg_pipe */
7818 found_pi_and_prognum:
7821 int rcode = WEXITSTATUS(status);
7822 if (WIFSIGNALED(status))
7823 rcode = 128 + WTERMSIG(status);
7824 pi->cmds[i].cmd_exitcode = rcode;
7825 if (G.last_bg_pid == pi->cmds[i].pid)
7826 G.last_bg_pid_exitcode = rcode;
7827 pi->cmds[i].pid = 0;
7829 if (!pi->alive_cmds) {
7830 if (G_interactive_fd) {
7831 printf(JOB_STATUS_FORMAT, pi->jobid,
7832 "Done", pi->cmdtext);
7833 delete_finished_job(pi);
7836 * bash deletes finished jobs from job table only in interactive mode,
7837 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7838 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7839 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7840 * We only retain one "dead" job, if it's the single job on the list.
7841 * This covers most of real-world scenarios where this is useful.
7843 if (pi != G.job_list)
7844 delete_finished_job(pi);
7852 return -1; /* this wasn't a process from fg_pipe */
7855 /* Check to see if any processes have exited -- if they have,
7856 * figure out why and see if a job has completed.
7858 * If non-NULL fg_pipe: wait for its completion or stop.
7859 * Return its exitcode or zero if stopped.
7861 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7862 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7863 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7864 * or 0 if no children changed status.
7866 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7867 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7868 * or 0 if no children changed status.
7870 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7876 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7878 attributes = WUNTRACED;
7879 if (fg_pipe == NULL)
7880 attributes |= WNOHANG;
7883 #if ENABLE_HUSH_FAST
7884 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7885 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7886 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7887 /* There was neither fork nor SIGCHLD since last waitpid */
7888 /* Avoid doing waitpid syscall if possible */
7889 if (!G.we_have_children) {
7893 if (fg_pipe == NULL) { /* is WNOHANG set? */
7894 /* We have children, but they did not exit
7895 * or stop yet (we saw no SIGCHLD) */
7898 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7902 /* Do we do this right?
7903 * bash-3.00# sleep 20 | false
7905 * [3]+ Stopped sleep 20 | false
7906 * bash-3.00# echo $?
7907 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7908 * [hush 1.14.0: yes we do it right]
7912 #if ENABLE_HUSH_FAST
7914 i = G.count_SIGCHLD;
7916 childpid = waitpid(-1, &status, attributes);
7917 if (childpid <= 0) {
7918 if (childpid && errno != ECHILD)
7919 bb_perror_msg("waitpid");
7920 #if ENABLE_HUSH_FAST
7921 else { /* Until next SIGCHLD, waitpid's are useless */
7922 G.we_have_children = (childpid == 0);
7923 G.handled_SIGCHLD = i;
7924 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7927 /* ECHILD (no children), or 0 (no change in children status) */
7931 rcode = process_wait_result(fg_pipe, childpid, status);
7933 /* fg_pipe exited or stopped */
7936 if (childpid == waitfor_pid) {
7937 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7938 rcode = WEXITSTATUS(status);
7939 if (WIFSIGNALED(status))
7940 rcode = 128 + WTERMSIG(status);
7941 if (WIFSTOPPED(status))
7942 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7943 rcode = 128 + WSTOPSIG(status);
7945 break; /* "wait PID" called us, give it exitcode+1 */
7947 /* This wasn't one of our processes, or */
7948 /* fg_pipe still has running processes, do waitpid again */
7949 } /* while (waitpid succeeds)... */
7955 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7958 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7959 if (G_saved_tty_pgrp) {
7960 /* Job finished, move the shell to the foreground */
7961 p = getpgrp(); /* our process group id */
7962 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7963 tcsetpgrp(G_interactive_fd, p);
7969 /* Start all the jobs, but don't wait for anything to finish.
7972 * Return code is normally -1, when the caller has to wait for children
7973 * to finish to determine the exit status of the pipe. If the pipe
7974 * is a simple builtin command, however, the action is done by the
7975 * time run_pipe returns, and the exit code is provided as the
7978 * Returns -1 only if started some children. IOW: we have to
7979 * mask out retvals of builtins etc with 0xff!
7981 * The only case when we do not need to [v]fork is when the pipe
7982 * is single, non-backgrounded, non-subshell command. Examples:
7983 * cmd ; ... { list } ; ...
7984 * cmd && ... { list } && ...
7985 * cmd || ... { list } || ...
7986 * If it is, then we can run cmd as a builtin, NOFORK,
7987 * or (if SH_STANDALONE) an applet, and we can run the { list }
7988 * with run_list. If it isn't one of these, we fork and exec cmd.
7990 * Cases when we must fork:
7991 * non-single: cmd | cmd
7992 * backgrounded: cmd & { list } &
7993 * subshell: ( list ) [&]
7995 #if !ENABLE_HUSH_MODE_X
7996 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7997 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7999 static int redirect_and_varexp_helper(char ***new_env_p,
8000 struct variable **old_vars_p,
8001 struct command *command,
8002 struct squirrel **sqp,
8003 char **argv_expanded)
8005 /* setup_redirects acts on file descriptors, not FILEs.
8006 * This is perfect for work that comes after exec().
8007 * Is it really safe for inline use? Experimentally,
8008 * things seem to work. */
8009 int rcode = setup_redirects(command, sqp);
8011 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8012 *new_env_p = new_env;
8013 dump_cmd_in_x_mode(new_env);
8014 dump_cmd_in_x_mode(argv_expanded);
8016 *old_vars_p = set_vars_and_save_old(new_env);
8020 static NOINLINE int run_pipe(struct pipe *pi)
8022 static const char *const null_ptr = NULL;
8026 struct command *command;
8027 char **argv_expanded;
8029 struct squirrel *squirrel = NULL;
8032 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8035 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8036 * Result should be 3 lines: q w e, qwe, q w e
8038 G.ifs = get_local_var_value("IFS");
8042 IF_HUSH_JOB(pi->pgrp = -1;)
8043 pi->stopped_cmds = 0;
8044 command = &pi->cmds[0];
8045 argv_expanded = NULL;
8047 if (pi->num_cmds != 1
8048 || pi->followup == PIPE_BG
8049 || command->cmd_type == CMD_SUBSHELL
8056 debug_printf_exec(": group:%p argv:'%s'\n",
8057 command->group, command->argv ? command->argv[0] : "NONE");
8059 if (command->group) {
8060 #if ENABLE_HUSH_FUNCTIONS
8061 if (command->cmd_type == CMD_FUNCDEF) {
8062 /* "executing" func () { list } */
8063 struct function *funcp;
8065 funcp = new_function(command->argv[0]);
8066 /* funcp->name is already set to argv[0] */
8067 funcp->body = command->group;
8069 funcp->body_as_string = command->group_as_string;
8070 command->group_as_string = NULL;
8072 command->group = NULL;
8073 command->argv[0] = NULL;
8074 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8075 funcp->parent_cmd = command;
8076 command->child_func = funcp;
8078 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8080 return EXIT_SUCCESS;
8084 debug_printf("non-subshell group\n");
8085 rcode = 1; /* exitcode if redir failed */
8086 if (setup_redirects(command, &squirrel) == 0) {
8087 debug_printf_exec(": run_list\n");
8088 rcode = run_list(command->group) & 0xff;
8090 restore_redirects(squirrel);
8091 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8093 debug_printf_exec("run_pipe: return %d\n", rcode);
8097 argv = command->argv ? command->argv : (char **) &null_ptr;
8099 const struct built_in_command *x;
8100 #if ENABLE_HUSH_FUNCTIONS
8101 const struct function *funcp;
8105 char **new_env = NULL;
8106 struct variable *old_vars = NULL;
8110 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8113 if (argv[command->assignment_cnt] == NULL) {
8114 /* Assignments, but no command */
8115 /* Ensure redirects take effect (that is, create files).
8116 * Try "a=t >file" */
8117 #if 0 /* A few cases in testsuite fail with this code. FIXME */
8118 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
8119 /* Set shell variables */
8123 if (set_local_var(*argv, /*flag:*/ 0)) {
8124 /* assignment to readonly var / putenv error? */
8130 /* Redirect error sets $? to 1. Otherwise,
8131 * if evaluating assignment value set $?, retain it.
8132 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8134 rcode = G.last_exitcode;
8135 /* Exit, _skipping_ variable restoring code: */
8136 goto clean_up_and_ret0;
8138 #else /* Older, bigger, but more correct code */
8140 rcode = setup_redirects(command, &squirrel);
8141 restore_redirects(squirrel);
8142 /* Set shell variables */
8144 bb_putchar_stderr('+');
8146 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8148 fprintf(stderr, " %s", p);
8149 debug_printf_exec("set shell var:'%s'->'%s'\n",
8151 if (set_local_var(p, /*flag:*/ 0)) {
8152 /* assignment to readonly var / putenv error? */
8158 bb_putchar_stderr('\n');
8159 /* Redirect error sets $? to 1. Otherwise,
8160 * if evaluating assignment value set $?, retain it.
8161 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8163 rcode = G.last_exitcode;
8164 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8166 debug_printf_exec("run_pipe: return %d\n", rcode);
8171 /* Expand the rest into (possibly) many strings each */
8173 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8174 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8178 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8181 /* if someone gives us an empty string: `cmd with empty output` */
8182 if (!argv_expanded[0]) {
8183 free(argv_expanded);
8185 return G.last_exitcode;
8188 #if ENABLE_HUSH_FUNCTIONS
8189 /* Check if argv[0] matches any functions (this goes before bltins) */
8190 funcp = find_function(argv_expanded[0]);
8194 x = find_builtin(argv_expanded[0]);
8197 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8198 debug_printf("exec with redirects only\n");
8199 rcode = setup_redirects(command, NULL);
8200 /* rcode=1 can be if redir file can't be opened */
8201 goto clean_up_and_ret1;
8204 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8207 debug_printf_exec(": builtin '%s' '%s'...\n",
8208 x->b_cmd, argv_expanded[1]);
8210 rcode = x->b_function(argv_expanded) & 0xff;
8213 #if ENABLE_HUSH_FUNCTIONS
8215 # if ENABLE_HUSH_LOCAL
8216 struct variable **sv;
8217 sv = G.shadowed_vars_pp;
8218 G.shadowed_vars_pp = &old_vars;
8220 debug_printf_exec(": function '%s' '%s'...\n",
8221 funcp->name, argv_expanded[1]);
8222 rcode = run_function(funcp, argv_expanded) & 0xff;
8223 # if ENABLE_HUSH_LOCAL
8224 G.shadowed_vars_pp = sv;
8230 unset_vars(new_env);
8232 /* clean_up_and_ret0: */
8233 restore_redirects(squirrel);
8235 * Try "usleep 99999999" + ^C + "echo $?"
8236 * with FEATURE_SH_NOFORK=y.
8239 /* It was builtin or nofork.
8240 * if this would be a real fork/execed program,
8241 * it should have died if a fatal sig was received.
8242 * But OTOH, there was no separate process,
8243 * the sig was sent to _shell_, not to non-existing
8245 * Let's just handle ^C only, this one is obvious:
8246 * we aren't ok with exitcode 0 when ^C was pressed
8247 * during builtin/nofork.
8249 if (sigismember(&G.pending_set, SIGINT))
8250 rcode = 128 + SIGINT;
8253 free(argv_expanded);
8254 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8256 debug_printf_exec("run_pipe return %d\n", rcode);
8260 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
8261 int n = find_applet_by_name(argv_expanded[0]);
8262 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8263 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8265 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8266 argv_expanded[0], argv_expanded[1]);
8268 * Note: signals (^C) can't interrupt here.
8269 * We remember them and they will be acted upon
8270 * after applet returns.
8271 * This makes applets which can run for a long time
8272 * and/or wait for user input ineligible for NOFORK:
8273 * for example, "yes" or "rm" (rm -i waits for input).
8275 rcode = run_nofork_applet(n, argv_expanded);
8277 goto clean_up_and_ret;
8280 /* It is neither builtin nor applet. We must fork. */
8284 /* NB: argv_expanded may already be created, and that
8285 * might include `cmd` runs! Do not rerun it! We *must*
8286 * use argv_expanded if it's non-NULL */
8288 /* Going to fork a child per each pipe member */
8293 while (cmd_no < pi->num_cmds) {
8294 struct fd_pair pipefds;
8296 volatile nommu_save_t nommu_save;
8297 nommu_save.new_env = NULL;
8298 nommu_save.old_vars = NULL;
8299 nommu_save.argv = NULL;
8300 nommu_save.argv_from_re_execing = NULL;
8302 command = &pi->cmds[cmd_no];
8304 if (command->argv) {
8305 debug_printf_exec(": pipe member '%s' '%s'...\n",
8306 command->argv[0], command->argv[1]);
8308 debug_printf_exec(": pipe member with no argv\n");
8311 /* pipes are inserted between pairs of commands */
8314 if (cmd_no < pi->num_cmds)
8315 xpiped_pair(pipefds);
8319 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8322 command->pid = BB_MMU ? fork() : vfork();
8323 if (!command->pid) { /* child */
8325 disable_restore_tty_pgrp_on_exit();
8326 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8328 /* Every child adds itself to new process group
8329 * with pgid == pid_of_first_child_in_pipe */
8330 if (G.run_list_level == 1 && G_interactive_fd) {
8333 if (pgrp < 0) /* true for 1st process only */
8335 if (setpgid(0, pgrp) == 0
8336 && pi->followup != PIPE_BG
8337 && G_saved_tty_pgrp /* we have ctty */
8339 /* We do it in *every* child, not just first,
8341 tcsetpgrp(G_interactive_fd, pgrp);
8345 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8346 /* 1st cmd in backgrounded pipe
8347 * should have its stdin /dev/null'ed */
8349 if (open(bb_dev_null, O_RDONLY))
8350 xopen("/", O_RDONLY);
8352 xmove_fd(next_infd, 0);
8354 xmove_fd(pipefds.wr, 1);
8357 /* Like bash, explicit redirects override pipes,
8358 * and the pipe fd (fd#1) is available for dup'ing:
8359 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8360 * of cmd1 goes into pipe.
8362 if (setup_redirects(command, NULL)) {
8363 /* Happens when redir file can't be opened:
8364 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8366 * hush: can't open '/qwe/rty': No such file or directory
8368 * (echo BAR is not executed, it hits _exit(1) below)
8373 /* Stores to nommu_save list of env vars putenv'ed
8374 * (NOMMU, on MMU we don't need that) */
8375 /* cast away volatility... */
8376 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8377 /* pseudo_exec() does not return */
8380 /* parent or error */
8381 #if ENABLE_HUSH_FAST
8383 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8385 enable_restore_tty_pgrp_on_exit();
8387 /* Clean up after vforked child */
8388 free(nommu_save.argv);
8389 free(nommu_save.argv_from_re_execing);
8390 unset_vars(nommu_save.new_env);
8391 add_vars(nommu_save.old_vars);
8393 free(argv_expanded);
8394 argv_expanded = NULL;
8395 if (command->pid < 0) { /* [v]fork failed */
8396 /* Clearly indicate, was it fork or vfork */
8397 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8401 /* Second and next children need to know pid of first one */
8403 pi->pgrp = command->pid;
8409 if (cmd_no < pi->num_cmds)
8411 /* Pass read (output) pipe end to next iteration */
8412 next_infd = pipefds.rd;
8415 if (!pi->alive_cmds) {
8417 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8422 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8426 /* NB: called by pseudo_exec, and therefore must not modify any
8427 * global data until exec/_exit (we can be a child after vfork!) */
8428 static int run_list(struct pipe *pi)
8430 #if ENABLE_HUSH_CASE
8431 char *case_word = NULL;
8433 #if ENABLE_HUSH_LOOPS
8434 struct pipe *loop_top = NULL;
8435 char **for_lcur = NULL;
8436 char **for_list = NULL;
8438 smallint last_followup;
8440 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8441 smalluint cond_code = 0;
8443 enum { cond_code = 0 };
8446 smallint rword; /* RES_foo */
8447 smallint last_rword; /* ditto */
8450 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8453 #if ENABLE_HUSH_LOOPS
8454 /* Check syntax for "for" */
8457 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8458 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8460 /* current word is FOR or IN (BOLD in comments below) */
8461 if (cpipe->next == NULL) {
8462 syntax_error("malformed for");
8464 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8467 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8468 if (cpipe->next->res_word == RES_DO)
8470 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8471 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8472 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8474 syntax_error("malformed for");
8476 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8483 /* Past this point, all code paths should jump to ret: label
8484 * in order to return, no direct "return" statements please.
8485 * This helps to ensure that no memory is leaked. */
8493 last_rword = RES_XXXX;
8495 last_followup = PIPE_SEQ;
8496 rcode = G.last_exitcode;
8498 /* Go through list of pipes, (maybe) executing them. */
8499 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8501 int sv_errexit_depth;
8505 if (G_flag_return_in_progress == 1)
8508 IF_HAS_KEYWORDS(rword = pi->res_word;)
8509 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8510 rword, cond_code, last_rword);
8512 sv_errexit_depth = G.errexit_depth;
8515 rword == RES_IF || rword == RES_ELIF ||
8517 pi->followup != PIPE_SEQ
8521 #if ENABLE_HUSH_LOOPS
8522 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8523 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8525 /* start of a loop: remember where loop starts */
8530 /* Still in the same "if...", "then..." or "do..." branch? */
8531 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8532 if ((rcode == 0 && last_followup == PIPE_OR)
8533 || (rcode != 0 && last_followup == PIPE_AND)
8535 /* It is "<true> || CMD" or "<false> && CMD"
8536 * and we should not execute CMD */
8537 debug_printf_exec("skipped cmd because of || or &&\n");
8538 last_followup = pi->followup;
8539 goto dont_check_jobs_but_continue;
8542 last_followup = pi->followup;
8543 IF_HAS_KEYWORDS(last_rword = rword;)
8546 if (rword == RES_THEN) {
8547 /* if false; then ... fi has exitcode 0! */
8548 G.last_exitcode = rcode = EXIT_SUCCESS;
8549 /* "if <false> THEN cmd": skip cmd */
8553 if (rword == RES_ELSE || rword == RES_ELIF) {
8554 /* "if <true> then ... ELSE/ELIF cmd":
8555 * skip cmd and all following ones */
8560 #if ENABLE_HUSH_LOOPS
8561 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8563 /* first loop through for */
8565 static const char encoded_dollar_at[] ALIGN1 = {
8566 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8567 }; /* encoded representation of "$@" */
8568 static const char *const encoded_dollar_at_argv[] = {
8569 encoded_dollar_at, NULL
8570 }; /* argv list with one element: "$@" */
8573 vals = (char**)encoded_dollar_at_argv;
8574 if (pi->next->res_word == RES_IN) {
8575 /* if no variable values after "in" we skip "for" */
8576 if (!pi->next->cmds[0].argv) {
8577 G.last_exitcode = rcode = EXIT_SUCCESS;
8578 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8581 vals = pi->next->cmds[0].argv;
8582 } /* else: "for var; do..." -> assume "$@" list */
8583 /* create list of variable values */
8584 debug_print_strings("for_list made from", vals);
8585 for_list = expand_strvec_to_strvec(vals);
8586 for_lcur = for_list;
8587 debug_print_strings("for_list", for_list);
8590 /* "for" loop is over, clean up */
8596 /* Insert next value from for_lcur */
8597 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8598 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8601 if (rword == RES_IN) {
8602 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8604 if (rword == RES_DONE) {
8605 continue; /* "done" has no cmds too */
8608 #if ENABLE_HUSH_CASE
8609 if (rword == RES_CASE) {
8610 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8611 case_word = expand_strvec_to_string(pi->cmds->argv);
8612 unbackslash(case_word);
8615 if (rword == RES_MATCH) {
8618 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8619 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8621 /* all prev words didn't match, does this one match? */
8622 argv = pi->cmds->argv;
8624 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8625 /* TODO: which FNM_xxx flags to use? */
8626 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8627 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8629 if (cond_code == 0) { /* match! we will execute this branch */
8631 case_word = NULL; /* make future "word)" stop */
8638 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8639 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8641 continue; /* not matched yet, skip this pipe */
8643 if (rword == RES_ESAC) {
8644 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8646 /* "case" did not match anything: still set $? (to 0) */
8647 G.last_exitcode = rcode = EXIT_SUCCESS;
8651 /* Just pressing <enter> in shell should check for jobs.
8652 * OTOH, in non-interactive shell this is useless
8653 * and only leads to extra job checks */
8654 if (pi->num_cmds == 0) {
8655 if (G_interactive_fd)
8656 goto check_jobs_and_continue;
8660 /* After analyzing all keywords and conditions, we decided
8661 * to execute this pipe. NB: have to do checkjobs(NULL)
8662 * after run_pipe to collect any background children,
8663 * even if list execution is to be stopped. */
8664 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8665 #if ENABLE_HUSH_LOOPS
8666 G.flag_break_continue = 0;
8668 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8670 /* We ran a builtin, function, or group.
8671 * rcode is already known
8672 * and we don't need to wait for anything. */
8673 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8674 G.last_exitcode = rcode;
8675 check_and_run_traps();
8676 #if ENABLE_HUSH_LOOPS
8677 /* Was it "break" or "continue"? */
8678 if (G.flag_break_continue) {
8679 smallint fbc = G.flag_break_continue;
8680 /* We might fall into outer *loop*,
8681 * don't want to break it too */
8683 G.depth_break_continue--;
8684 if (G.depth_break_continue == 0)
8685 G.flag_break_continue = 0;
8686 /* else: e.g. "continue 2" should *break* once, *then* continue */
8687 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8688 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8689 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8692 /* "continue": simulate end of loop */
8697 if (G_flag_return_in_progress == 1) {
8698 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8701 } else if (pi->followup == PIPE_BG) {
8702 /* What does bash do with attempts to background builtins? */
8703 /* even bash 3.2 doesn't do that well with nested bg:
8704 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8705 * I'm NOT treating inner &'s as jobs */
8707 if (G.run_list_level == 1)
8708 insert_job_into_table(pi);
8710 /* Last command's pid goes to $! */
8711 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8712 G.last_bg_pid_exitcode = 0;
8713 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8714 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8715 rcode = EXIT_SUCCESS;
8719 if (G.run_list_level == 1 && G_interactive_fd) {
8720 /* Waits for completion, then fg's main shell */
8721 rcode = checkjobs_and_fg_shell(pi);
8722 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8726 /* This one just waits for completion */
8727 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8728 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8730 G.last_exitcode = rcode;
8731 check_and_run_traps();
8734 /* Handle "set -e" */
8735 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8736 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8737 if (G.errexit_depth == 0)
8740 G.errexit_depth = sv_errexit_depth;
8742 /* Analyze how result affects subsequent commands */
8744 if (rword == RES_IF || rword == RES_ELIF)
8747 check_jobs_and_continue:
8748 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8749 dont_check_jobs_but_continue: ;
8750 #if ENABLE_HUSH_LOOPS
8751 /* Beware of "while false; true; do ..."! */
8753 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8754 /* check for RES_DONE is needed for "while ...; do \n done" case */
8756 if (rword == RES_WHILE) {
8758 /* "while false; do...done" - exitcode 0 */
8759 G.last_exitcode = rcode = EXIT_SUCCESS;
8760 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8764 if (rword == RES_UNTIL) {
8766 debug_printf_exec(": until expr is true: breaking\n");
8777 #if ENABLE_HUSH_LOOPS
8782 #if ENABLE_HUSH_CASE
8786 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8790 /* Select which version we will use */
8791 static int run_and_free_list(struct pipe *pi)
8794 debug_printf_exec("run_and_free_list entered\n");
8795 if (!G.o_opt[OPT_O_NOEXEC]) {
8796 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8797 rcode = run_list(pi);
8799 /* free_pipe_list has the side effect of clearing memory.
8800 * In the long run that function can be merged with run_list,
8801 * but doing that now would hobble the debugging effort. */
8803 debug_printf_exec("run_and_free_list return %d\n", rcode);
8808 static void install_sighandlers(unsigned mask)
8810 sighandler_t old_handler;
8812 while ((mask >>= 1) != 0) {
8816 old_handler = install_sighandler(sig, pick_sighandler(sig));
8817 /* POSIX allows shell to re-enable SIGCHLD
8818 * even if it was SIG_IGN on entry.
8819 * Therefore we skip IGN check for it:
8823 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8824 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8826 //if (sig == SIGHUP) continue; - TODO?
8827 if (old_handler == SIG_IGN) {
8828 /* oops... restore back to IGN, and record this fact */
8829 install_sighandler(sig, old_handler);
8830 #if ENABLE_HUSH_TRAP
8832 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8834 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8840 /* Called a few times only (or even once if "sh -c") */
8841 static void install_special_sighandlers(void)
8845 /* Which signals are shell-special? */
8846 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8847 if (G_interactive_fd) {
8848 mask |= SPECIAL_INTERACTIVE_SIGS;
8849 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8850 mask |= SPECIAL_JOBSTOP_SIGS;
8852 /* Careful, do not re-install handlers we already installed */
8853 if (G.special_sig_mask != mask) {
8854 unsigned diff = mask & ~G.special_sig_mask;
8855 G.special_sig_mask = mask;
8856 install_sighandlers(diff);
8862 /* Set handlers to restore tty pgrp and exit */
8863 static void install_fatal_sighandlers(void)
8867 /* We will restore tty pgrp on these signals */
8869 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8870 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8871 + (1 << SIGBUS ) * HUSH_DEBUG
8872 + (1 << SIGSEGV) * HUSH_DEBUG
8873 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8875 /* bash 3.2 seems to handle these just like 'fatal' ones */
8878 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8879 * if we aren't interactive... but in this case
8880 * we never want to restore pgrp on exit, and this fn is not called
8882 /*+ (1 << SIGHUP )*/
8883 /*+ (1 << SIGTERM)*/
8884 /*+ (1 << SIGINT )*/
8886 G_fatal_sig_mask = mask;
8888 install_sighandlers(mask);
8892 static int set_mode(int state, char mode, const char *o_opt)
8897 G.o_opt[OPT_O_NOEXEC] = state;
8900 IF_HUSH_MODE_X(G_x_mode = state;)
8904 /* "set -+o" without parameter.
8905 * in bash, set -o produces this output:
8909 * We always use the second form.
8911 const char *p = o_opt_strings;
8914 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8920 idx = index_in_strings(o_opt_strings, o_opt);
8922 G.o_opt[idx] = state;
8926 G.o_opt[OPT_O_ERREXIT] = state;
8929 return EXIT_FAILURE;
8931 return EXIT_SUCCESS;
8934 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8935 int hush_main(int argc, char **argv)
8938 OPT_login = (1 << 0),
8942 unsigned builtin_argc;
8944 struct variable *cur_var;
8945 struct variable *shell_ver;
8948 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8949 G.last_exitcode = EXIT_SUCCESS;
8951 #if ENABLE_HUSH_FAST
8952 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8955 G.argv0_for_re_execing = argv[0];
8958 /* Deal with HUSH_VERSION */
8959 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8960 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8961 shell_ver = xzalloc(sizeof(*shell_ver));
8962 shell_ver->flg_export = 1;
8963 shell_ver->flg_read_only = 1;
8964 /* Code which handles ${var<op>...} needs writable values for all variables,
8965 * therefore we xstrdup: */
8966 shell_ver->varstr = xstrdup(hush_version_str);
8968 /* Create shell local variables from the values
8969 * currently living in the environment */
8970 G.top_var = shell_ver;
8971 cur_var = G.top_var;
8974 char *value = strchr(*e, '=');
8975 if (value) { /* paranoia */
8976 cur_var->next = xzalloc(sizeof(*cur_var));
8977 cur_var = cur_var->next;
8978 cur_var->varstr = *e;
8979 cur_var->max_len = strlen(*e);
8980 cur_var->flg_export = 1;
8984 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8985 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8986 putenv(shell_ver->varstr);
8989 set_pwd_var(SETFLAG_EXPORT);
8991 #if BASH_HOSTNAME_VAR
8992 /* Set (but not export) HOSTNAME unless already set */
8993 if (!get_local_var_value("HOSTNAME")) {
8996 set_local_var_from_halves("HOSTNAME", uts.nodename);
8998 /* bash also exports SHLVL and _,
8999 * and sets (but doesn't export) the following variables:
9001 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9002 * BASH_VERSION='3.2.0(1)-release'
9004 * MACHTYPE=i386-pc-linux-gnu
9006 * PPID=<NNNNN> - we also do it elsewhere
9017 * PIPESTATUS=([0]="0")
9018 * HISTFILE=/<xxx>/.bash_history
9022 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9024 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9036 if (BASH_LINENO_VAR) {
9037 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9038 set_local_var(p, /*flags*/ 0);
9039 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9043 #if ENABLE_FEATURE_EDITING
9044 G.line_input_state = new_line_input_t(FOR_SHELL);
9047 /* Initialize some more globals to non-zero values */
9048 cmdedit_update_prompt();
9050 die_func = restore_ttypgrp_and__exit;
9052 /* Shell is non-interactive at first. We need to call
9053 * install_special_sighandlers() if we are going to execute "sh <script>",
9054 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9055 * If we later decide that we are interactive, we run install_special_sighandlers()
9056 * in order to intercept (more) signals.
9060 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9061 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9064 opt = getopt(argc, argv, "+c:exinsl"
9067 # if ENABLE_HUSH_FUNCTIONS
9077 * sh ... -c 'script'
9078 * sh ... -c 'script' ARG0 [ARG1...]
9079 * On NOMMU, if builtin_argc != 0,
9080 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9081 * "" needs to be replaced with NULL
9082 * and BARGV vector fed to builtin function.
9083 * Note: the form without ARG0 never happens:
9084 * sh ... -c 'builtin' BARGV... ""
9087 G.root_pid = getpid();
9088 G.root_ppid = getppid();
9090 G.global_argv = argv + optind;
9091 G.global_argc = argc - optind;
9093 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9094 const struct built_in_command *x;
9096 install_special_sighandlers();
9097 x = find_builtin(optarg);
9098 if (x) { /* paranoia */
9099 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9100 G.global_argv += builtin_argc;
9101 G.global_argv[-1] = NULL; /* replace "" */
9103 G.last_exitcode = x->b_function(argv + optind - 1);
9107 if (!G.global_argv[0]) {
9108 /* -c 'script' (no params): prevent empty $0 */
9109 G.global_argv--; /* points to argv[i] of 'script' */
9110 G.global_argv[0] = argv[0];
9112 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
9113 install_special_sighandlers();
9114 parse_and_run_string(optarg);
9117 /* Well, we cannot just declare interactiveness,
9118 * we have to have some stuff (ctty, etc) */
9119 /* G_interactive_fd++; */
9122 /* "-s" means "read from stdin", but this is how we always
9123 * operate, so simply do nothing here. */
9129 case '<': /* "big heredoc" support */
9130 full_write1_str(optarg);
9133 unsigned long long empty_trap_mask;
9135 G.root_pid = bb_strtou(optarg, &optarg, 16);
9137 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9139 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9141 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
9143 builtin_argc = bb_strtou(optarg, &optarg, 16);
9145 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9146 if (empty_trap_mask != 0) {
9147 IF_HUSH_TRAP(int sig;)
9148 install_special_sighandlers();
9149 # if ENABLE_HUSH_TRAP
9150 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9151 for (sig = 1; sig < NSIG; sig++) {
9152 if (empty_trap_mask & (1LL << sig)) {
9153 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9154 install_sighandler(sig, SIG_IGN);
9159 # if ENABLE_HUSH_LOOPS
9161 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
9167 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9169 # if ENABLE_HUSH_FUNCTIONS
9171 struct function *funcp = new_function(optarg);
9172 /* funcp->name is already set to optarg */
9173 /* funcp->body is set to NULL. It's a special case. */
9174 funcp->body_as_string = argv[optind];
9183 if (set_mode(1, opt, NULL) == 0) /* no error */
9187 fprintf(stderr, "Usage: sh [FILE]...\n"
9188 " or: sh -c command [args]...\n\n");
9194 } /* option parsing loop */
9196 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9197 G.global_argc = argc - (optind - 1);
9198 G.global_argv = argv + (optind - 1);
9199 G.global_argv[0] = argv[0];
9202 G.root_pid = getpid();
9203 G.root_ppid = getppid();
9206 /* If we are login shell... */
9207 if (flags & OPT_login) {
9209 debug_printf("sourcing /etc/profile\n");
9210 input = fopen_for_read("/etc/profile");
9211 if (input != NULL) {
9212 remember_FILE(input);
9213 install_special_sighandlers();
9214 parse_and_run_file(input);
9215 fclose_and_forget(input);
9217 /* bash: after sourcing /etc/profile,
9218 * tries to source (in the given order):
9219 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9220 * stopping on first found. --noprofile turns this off.
9221 * bash also sources ~/.bash_logout on exit.
9222 * If called as sh, skips .bash_XXX files.
9226 if (G.global_argv[1]) {
9229 * "bash <script>" (which is never interactive (unless -i?))
9230 * sources $BASH_ENV here (without scanning $PATH).
9231 * If called as sh, does the same but with $ENV.
9232 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9236 debug_printf("running script '%s'\n", G.global_argv[0]);
9237 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9238 input = xfopen_for_read(G.global_argv[0]);
9239 xfunc_error_retval = 1;
9240 remember_FILE(input);
9241 install_special_sighandlers();
9242 parse_and_run_file(input);
9243 #if ENABLE_FEATURE_CLEAN_UP
9244 fclose_and_forget(input);
9249 /* Up to here, shell was non-interactive. Now it may become one.
9250 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9253 /* A shell is interactive if the '-i' flag was given,
9254 * or if all of the following conditions are met:
9256 * no arguments remaining or the -s flag given
9257 * standard input is a terminal
9258 * standard output is a terminal
9259 * Refer to Posix.2, the description of the 'sh' utility.
9262 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9263 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9264 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9265 if (G_saved_tty_pgrp < 0)
9266 G_saved_tty_pgrp = 0;
9268 /* try to dup stdin to high fd#, >= 255 */
9269 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9270 if (G_interactive_fd < 0) {
9271 /* try to dup to any fd */
9272 G_interactive_fd = dup(STDIN_FILENO);
9273 if (G_interactive_fd < 0) {
9275 G_interactive_fd = 0;
9276 G_saved_tty_pgrp = 0;
9279 // TODO: track & disallow any attempts of user
9280 // to (inadvertently) close/redirect G_interactive_fd
9282 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9283 if (G_interactive_fd) {
9284 close_on_exec_on(G_interactive_fd);
9286 if (G_saved_tty_pgrp) {
9287 /* If we were run as 'hush &', sleep until we are
9288 * in the foreground (tty pgrp == our pgrp).
9289 * If we get started under a job aware app (like bash),
9290 * make sure we are now in charge so we don't fight over
9291 * who gets the foreground */
9293 pid_t shell_pgrp = getpgrp();
9294 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9295 if (G_saved_tty_pgrp == shell_pgrp)
9297 /* send TTIN to ourself (should stop us) */
9298 kill(- shell_pgrp, SIGTTIN);
9302 /* Install more signal handlers */
9303 install_special_sighandlers();
9305 if (G_saved_tty_pgrp) {
9306 /* Set other signals to restore saved_tty_pgrp */
9307 install_fatal_sighandlers();
9308 /* Put ourselves in our own process group
9309 * (bash, too, does this only if ctty is available) */
9310 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9311 /* Grab control of the terminal */
9312 tcsetpgrp(G_interactive_fd, getpid());
9314 enable_restore_tty_pgrp_on_exit();
9316 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9318 const char *hp = get_local_var_value("HISTFILE");
9320 hp = get_local_var_value("HOME");
9322 hp = concat_path_file(hp, ".hush_history");
9327 G.line_input_state->hist_file = hp;
9328 //set_local_var(xasprintf("HISTFILE=%s", ...));
9330 # if ENABLE_FEATURE_SH_HISTFILESIZE
9331 hp = get_local_var_value("HISTFILESIZE");
9332 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9337 install_special_sighandlers();
9339 #elif ENABLE_HUSH_INTERACTIVE
9340 /* No job control compiled in, only prompt/line editing */
9341 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9342 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9343 if (G_interactive_fd < 0) {
9344 /* try to dup to any fd */
9345 G_interactive_fd = dup(STDIN_FILENO);
9346 if (G_interactive_fd < 0)
9348 G_interactive_fd = 0;
9351 if (G_interactive_fd) {
9352 close_on_exec_on(G_interactive_fd);
9354 install_special_sighandlers();
9356 /* We have interactiveness code disabled */
9357 install_special_sighandlers();
9360 * if interactive but not a login shell, sources ~/.bashrc
9361 * (--norc turns this off, --rcfile <file> overrides)
9364 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9365 /* note: ash and hush share this string */
9366 printf("\n\n%s %s\n"
9367 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9370 "hush - the humble shell"
9374 parse_and_run_file(stdin);
9377 hush_exit(G.last_exitcode);
9384 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9389 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9390 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9392 int argc = string_array_len(argv);
9393 return applet_main_func(argc, argv);
9396 #if ENABLE_HUSH_TEST || BASH_TEST2
9397 static int FAST_FUNC builtin_test(char **argv)
9399 return run_applet_main(argv, test_main);
9402 #if ENABLE_HUSH_ECHO
9403 static int FAST_FUNC builtin_echo(char **argv)
9405 return run_applet_main(argv, echo_main);
9408 #if ENABLE_HUSH_PRINTF
9409 static int FAST_FUNC builtin_printf(char **argv)
9411 return run_applet_main(argv, printf_main);
9415 #if ENABLE_HUSH_HELP
9416 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9418 const struct built_in_command *x;
9421 "Built-in commands:\n"
9422 "------------------\n");
9423 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9425 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9427 return EXIT_SUCCESS;
9431 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9432 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9434 show_history(G.line_input_state);
9435 return EXIT_SUCCESS;
9439 static char **skip_dash_dash(char **argv)
9442 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9447 static int FAST_FUNC builtin_cd(char **argv)
9451 argv = skip_dash_dash(argv);
9453 if (newdir == NULL) {
9454 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9455 * bash says "bash: cd: HOME not set" and does nothing
9458 const char *home = get_local_var_value("HOME");
9459 newdir = home ? home : "/";
9461 if (chdir(newdir)) {
9462 /* Mimic bash message exactly */
9463 bb_perror_msg("cd: %s", newdir);
9464 return EXIT_FAILURE;
9466 /* Read current dir (get_cwd(1) is inside) and set PWD.
9467 * Note: do not enforce exporting. If PWD was unset or unexported,
9468 * set it again, but do not export. bash does the same.
9470 set_pwd_var(/*flag:*/ 0);
9471 return EXIT_SUCCESS;
9474 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9477 return EXIT_SUCCESS;
9480 static int FAST_FUNC builtin_eval(char **argv)
9482 int rcode = EXIT_SUCCESS;
9484 argv = skip_dash_dash(argv);
9489 /* "The eval utility shall construct a command by
9490 * concatenating arguments together, separating
9491 * each with a <space> character."
9497 len += strlen(*pp) + 1;
9499 str = p = xmalloc(len);
9509 * eval "echo Hi; done" ("done" is syntax error):
9510 * "echo Hi" will not execute too.
9512 parse_and_run_string(str ? str : argv[0]);
9514 rcode = G.last_exitcode;
9519 static int FAST_FUNC builtin_exec(char **argv)
9521 argv = skip_dash_dash(argv);
9522 if (argv[0] == NULL)
9523 return EXIT_SUCCESS; /* bash does this */
9525 /* Careful: we can end up here after [v]fork. Do not restore
9526 * tty pgrp then, only top-level shell process does that */
9527 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9528 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9530 /* Saved-redirect fds, script fds and G_interactive_fd are still
9531 * open here. However, they are all CLOEXEC, and execv below
9532 * closes them. Try interactive "exec ls -l /proc/self/fd",
9533 * it should show no extra open fds in the "ls" process.
9534 * If we'd try to run builtins/NOEXECs, this would need improving.
9536 //close_saved_fds_and_FILE_fds();
9538 /* TODO: if exec fails, bash does NOT exit! We do.
9539 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9540 * and tcsetpgrp, and this is inherently racy.
9542 execvp_or_die(argv);
9545 static int FAST_FUNC builtin_exit(char **argv)
9547 debug_printf_exec("%s()\n", __func__);
9549 /* interactive bash:
9550 * # trap "echo EEE" EXIT
9553 * There are stopped jobs.
9554 * (if there are _stopped_ jobs, running ones don't count)
9557 * EEE (then bash exits)
9559 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9562 /* note: EXIT trap is run by hush_exit */
9563 argv = skip_dash_dash(argv);
9564 if (argv[0] == NULL)
9565 hush_exit(G.last_exitcode);
9566 /* mimic bash: exit 123abc == exit 255 + error msg */
9567 xfunc_error_retval = 255;
9568 /* bash: exit -2 == exit 254, no error msg */
9569 hush_exit(xatoi(argv[0]) & 0xff);
9572 #if ENABLE_HUSH_TYPE
9573 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9574 static int FAST_FUNC builtin_type(char **argv)
9576 int ret = EXIT_SUCCESS;
9582 if (0) {} /* make conditional compile easier below */
9583 /*else if (find_alias(*argv))
9584 type = "an alias";*/
9585 #if ENABLE_HUSH_FUNCTIONS
9586 else if (find_function(*argv))
9587 type = "a function";
9589 else if (find_builtin(*argv))
9590 type = "a shell builtin";
9591 else if ((path = find_in_path(*argv)) != NULL)
9594 bb_error_msg("type: %s: not found", *argv);
9599 printf("%s is %s\n", *argv, type);
9607 #if ENABLE_HUSH_READ
9608 /* Interruptibility of read builtin in bash
9609 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9611 * Empty trap makes read ignore corresponding signal, for any signal.
9614 * - terminates non-interactive shell;
9615 * - interrupts read in interactive shell;
9616 * if it has non-empty trap:
9617 * - executes trap and returns to command prompt in interactive shell;
9618 * - executes trap and returns to read in non-interactive shell;
9620 * - is ignored (does not interrupt) read in interactive shell;
9621 * - terminates non-interactive shell;
9622 * if it has non-empty trap:
9623 * - executes trap and returns to read;
9625 * - terminates shell (regardless of interactivity);
9626 * if it has non-empty trap:
9627 * - executes trap and returns to read;
9628 * SIGCHLD from children:
9629 * - does not interrupt read regardless of interactivity:
9630 * try: sleep 1 & read x; echo $x
9632 static int FAST_FUNC builtin_read(char **argv)
9639 char *opt_d = NULL; /* optimized out if !BASH */
9643 /* "!": do not abort on errors.
9644 * Option string must start with "sr" to match BUILTIN_READ_xxx
9646 read_flags = getopt32(argv,
9648 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9650 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9653 if (read_flags == (uint32_t)-1)
9654 return EXIT_FAILURE;
9656 ifs = get_local_var_value("IFS"); /* can be NULL */
9659 r = shell_builtin_read(set_local_var_from_halves,
9670 if ((uintptr_t)r == 1 && errno == EINTR) {
9671 unsigned sig = check_and_run_traps();
9676 if ((uintptr_t)r > 1) {
9677 bb_error_msg("%s", r);
9678 r = (char*)(uintptr_t)1;
9681 return (uintptr_t)r;
9685 #if ENABLE_HUSH_UMASK
9686 static int FAST_FUNC builtin_umask(char **argv)
9693 argv = skip_dash_dash(argv);
9695 mode_t old_mask = mask;
9697 /* numeric umasks are taken as-is */
9698 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9699 if (!isdigit(argv[0][0]))
9701 mask = bb_parse_mode(argv[0], mask);
9702 if (!isdigit(argv[0][0]))
9704 if ((unsigned)mask > 0777) {
9707 * bash: umask: 'q': invalid symbolic mode operator
9708 * bash: umask: 999: octal number out of range
9710 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9715 printf("%04o\n", (unsigned) mask);
9716 /* fall through and restore mask which we set to 0 */
9720 return !rc; /* rc != 0 - success */
9724 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9725 static void print_escaped(const char *s)
9730 const char *p = strchrnul(s, '\'');
9731 /* print 'xxxx', possibly just '' */
9732 printf("'%.*s'", (int)(p - s), s);
9737 /* s points to '; print "'''...'''" */
9739 do putchar('\''); while (*++s == '\'');
9745 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9746 static int helper_export_local(char **argv, unsigned flags)
9750 char *name_end = strchrnul(name, '=');
9752 /* So far we do not check that name is valid (TODO?) */
9754 if (*name_end == '\0') {
9755 struct variable *var, **vpp;
9757 vpp = get_ptr_to_local_var(name, name_end - name);
9758 var = vpp ? *vpp : NULL;
9760 if (flags & SETFLAG_UNEXPORT) {
9761 /* export -n NAME (without =VALUE) */
9763 var->flg_export = 0;
9764 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9766 } /* else: export -n NOT_EXISTING_VAR: no-op */
9769 if (flags & SETFLAG_EXPORT) {
9770 /* export NAME (without =VALUE) */
9772 var->flg_export = 1;
9773 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9774 putenv(var->varstr);
9778 if (flags & SETFLAG_MAKE_RO) {
9779 /* readonly NAME (without =VALUE) */
9781 var->flg_read_only = 1;
9785 # if ENABLE_HUSH_LOCAL
9786 /* Is this "local" bltin? */
9787 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9788 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9789 if (var && var->func_nest_level == lvl) {
9790 /* "local x=abc; ...; local x" - ignore second local decl */
9795 /* Exporting non-existing variable.
9796 * bash does not put it in environment,
9797 * but remembers that it is exported,
9798 * and does put it in env when it is set later.
9799 * We just set it to "" and export.
9801 /* Or, it's "local NAME" (without =VALUE).
9802 * bash sets the value to "".
9804 /* Or, it's "readonly NAME" (without =VALUE).
9805 * bash remembers NAME and disallows its creation
9808 name = xasprintf("%s=", name);
9810 /* (Un)exporting/making local NAME=VALUE */
9811 name = xstrdup(name);
9813 if (set_local_var(name, flags))
9814 return EXIT_FAILURE;
9816 return EXIT_SUCCESS;
9820 #if ENABLE_HUSH_EXPORT
9821 static int FAST_FUNC builtin_export(char **argv)
9823 unsigned opt_unexport;
9825 #if ENABLE_HUSH_EXPORT_N
9826 /* "!": do not abort on errors */
9827 opt_unexport = getopt32(argv, "!n");
9828 if (opt_unexport == (uint32_t)-1)
9829 return EXIT_FAILURE;
9836 if (argv[0] == NULL) {
9843 /* ash emits: export VAR='VAL'
9844 * bash: declare -x VAR="VAL"
9845 * we follow ash example */
9846 const char *s = *e++;
9847 const char *p = strchr(s, '=');
9849 if (!p) /* wtf? take next variable */
9852 printf("export %.*s", (int)(p - s) + 1, s);
9853 print_escaped(p + 1);
9857 /*fflush_all(); - done after each builtin anyway */
9859 return EXIT_SUCCESS;
9862 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9866 #if ENABLE_HUSH_LOCAL
9867 static int FAST_FUNC builtin_local(char **argv)
9869 if (G.func_nest_level == 0) {
9870 bb_error_msg("%s: not in a function", argv[0]);
9871 return EXIT_FAILURE; /* bash compat */
9874 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9878 #if ENABLE_HUSH_READONLY
9879 static int FAST_FUNC builtin_readonly(char **argv)
9882 if (*argv == NULL) {
9883 /* bash: readonly [-p]: list all readonly VARs
9884 * (-p has no effect in bash)
9887 for (e = G.top_var; e; e = e->next) {
9888 if (e->flg_read_only) {
9889 //TODO: quote value: readonly VAR='VAL'
9890 printf("readonly %s\n", e->varstr);
9893 return EXIT_SUCCESS;
9895 return helper_export_local(argv, SETFLAG_MAKE_RO);
9899 #if ENABLE_HUSH_UNSET
9900 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9901 static int FAST_FUNC builtin_unset(char **argv)
9906 /* "!": do not abort on errors */
9907 /* "+": stop at 1st non-option */
9908 opts = getopt32(argv, "!+vf");
9909 if (opts == (unsigned)-1)
9910 return EXIT_FAILURE;
9912 bb_error_msg("unset: -v and -f are exclusive");
9913 return EXIT_FAILURE;
9919 if (!(opts & 2)) { /* not -f */
9920 if (unset_local_var(*argv)) {
9921 /* unset <nonexistent_var> doesn't fail.
9922 * Error is when one tries to unset RO var.
9923 * Message was printed by unset_local_var. */
9927 # if ENABLE_HUSH_FUNCTIONS
9939 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9940 * built-in 'set' handler
9942 * set [-abCefhmnuvx] [-o option] [argument...]
9943 * set [+abCefhmnuvx] [+o option] [argument...]
9944 * set -- [argument...]
9947 * Implementations shall support the options in both their hyphen and
9948 * plus-sign forms. These options can also be specified as options to sh.
9950 * Write out all variables and their values: set
9951 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9952 * Turn on the -x and -v options: set -xv
9953 * Unset all positional parameters: set --
9954 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9955 * Set the positional parameters to the expansion of x, even if x expands
9956 * with a leading '-' or '+': set -- $x
9958 * So far, we only support "set -- [argument...]" and some of the short names.
9960 static int FAST_FUNC builtin_set(char **argv)
9963 char **pp, **g_argv;
9964 char *arg = *++argv;
9968 for (e = G.top_var; e; e = e->next)
9970 return EXIT_SUCCESS;
9974 if (strcmp(arg, "--") == 0) {
9978 if (arg[0] != '+' && arg[0] != '-')
9980 for (n = 1; arg[n]; ++n) {
9981 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9983 if (arg[n] == 'o' && argv[1])
9986 } while ((arg = *++argv) != NULL);
9987 /* Now argv[0] is 1st argument */
9990 return EXIT_SUCCESS;
9993 /* NB: G.global_argv[0] ($0) is never freed/changed */
9994 g_argv = G.global_argv;
9995 if (G.global_args_malloced) {
10001 G.global_args_malloced = 1;
10002 pp = xzalloc(sizeof(pp[0]) * 2);
10003 pp[0] = g_argv[0]; /* retain $0 */
10006 /* This realloc's G.global_argv */
10007 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10009 G.global_argc = 1 + string_array_len(pp + 1);
10011 return EXIT_SUCCESS;
10013 /* Nothing known, so abort */
10015 bb_error_msg("%s: %s: invalid option", "set", arg);
10016 return EXIT_FAILURE;
10020 static int FAST_FUNC builtin_shift(char **argv)
10023 argv = skip_dash_dash(argv);
10025 n = bb_strtou(argv[0], NULL, 10);
10026 if (errno || n < 0) {
10027 /* shared string with ash.c */
10028 bb_error_msg("Illegal number: %s", argv[0]);
10030 * ash aborts in this case.
10031 * bash prints error message and set $? to 1.
10032 * Interestingly, for "shift 99999" bash does not
10033 * print error message, but does set $? to 1
10034 * (and does no shifting at all).
10038 if (n >= 0 && n < G.global_argc) {
10039 if (G_global_args_malloced) {
10042 free(G.global_argv[m++]);
10044 G.global_argc -= n;
10045 memmove(&G.global_argv[1], &G.global_argv[n+1],
10046 G.global_argc * sizeof(G.global_argv[0]));
10047 return EXIT_SUCCESS;
10049 return EXIT_FAILURE;
10052 #if ENABLE_HUSH_GETOPTS
10053 static int FAST_FUNC builtin_getopts(char **argv)
10055 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10058 If a required argument is not found, and getopts is not silent,
10059 a question mark (?) is placed in VAR, OPTARG is unset, and a
10060 diagnostic message is printed. If getopts is silent, then a
10061 colon (:) is placed in VAR and OPTARG is set to the option
10064 Test that VAR is a valid variable name?
10066 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10069 const char *cp, *optstring, *var;
10070 int c, n, exitcode, my_opterr;
10073 optstring = *++argv;
10074 if (!optstring || !(var = *++argv)) {
10075 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10076 return EXIT_FAILURE;
10080 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10082 argv = G.global_argv;
10086 if (optstring[0] != ':') {
10087 cp = get_local_var_value("OPTERR");
10088 /* 0 if "OPTERR=0", 1 otherwise */
10089 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
10092 /* getopts stops on first non-option. Add "+" to force that */
10093 /*if (optstring[0] != '+')*/ {
10094 char *s = alloca(strlen(optstring) + 2);
10095 sprintf(s, "+%s", optstring);
10099 /* Naively, now we should just
10100 * cp = get_local_var_value("OPTIND");
10101 * optind = cp ? atoi(cp) : 0;
10103 * opterr = my_opterr;
10104 * c = getopt(string_array_len(argv), argv, optstring);
10105 * and be done? Not so fast...
10106 * Unlike normal getopt() usage in C programs, here
10107 * each successive call will (usually) have the same argv[] CONTENTS,
10108 * but not the ADDRESSES. Worse yet, it's possible that between
10109 * invocations of "getopts", there will be calls to shell builtins
10110 * which use getopt() internally. Example:
10111 * while getopts "abc" RES -a -bc -abc de; do
10114 * This would not work correctly: getopt() call inside "unset"
10115 * modifies internal libc state which is tracking position in
10116 * multi-option strings ("-abc"). At best, it can skip options
10117 * or return the same option infinitely. With glibc implementation
10118 * of getopt(), it would use outright invalid pointers and return
10119 * garbage even _without_ "unset" mangling internal state.
10121 * We resort to resetting getopt() state and calling it N times,
10122 * until we get Nth result (or failure).
10123 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10127 n = string_array_len(argv);
10130 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10131 c = getopt(n, argv, optstring);
10135 } while (count <= G.getopt_count);
10137 /* Set OPTIND. Prevent resetting of the magic counter! */
10138 set_local_var_from_halves("OPTIND", utoa(optind));
10139 G.getopt_count = count; /* "next time, give me N+1'th result" */
10140 GETOPT_RESET(); /* just in case */
10143 /* Always set or unset, never left as-is, even on exit/error:
10144 * "If no option was found, or if the option that was found
10145 * does not have an option-argument, OPTARG shall be unset."
10149 /* If ":optstring" and unknown option is seen,
10150 * it is stored to OPTARG.
10152 if (optstring[1] == ':') {
10158 set_local_var_from_halves("OPTARG", cp);
10160 unset_local_var("OPTARG");
10162 /* Convert -1 to "?" */
10163 exitcode = EXIT_SUCCESS;
10164 if (c < 0) { /* -1: end of options */
10165 exitcode = EXIT_FAILURE;
10171 set_local_var_from_halves(var, cbuf);
10177 static int FAST_FUNC builtin_source(char **argv)
10179 char *arg_path, *filename;
10182 char *args_need_save;
10183 #if ENABLE_HUSH_FUNCTIONS
10187 argv = skip_dash_dash(argv);
10188 filename = argv[0];
10190 /* bash says: "bash: .: filename argument required" */
10191 return 2; /* bash compat */
10194 if (!strchr(filename, '/')) {
10195 arg_path = find_in_path(filename);
10197 filename = arg_path;
10199 input = remember_FILE(fopen_or_warn(filename, "r"));
10202 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10203 /* POSIX: non-interactive shell should abort here,
10204 * not merely fail. So far no one complained :)
10206 return EXIT_FAILURE;
10209 #if ENABLE_HUSH_FUNCTIONS
10210 sv_flg = G_flag_return_in_progress;
10211 /* "we are inside sourced file, ok to use return" */
10212 G_flag_return_in_progress = -1;
10214 args_need_save = argv[1]; /* used as a boolean variable */
10215 if (args_need_save)
10216 save_and_replace_G_args(&sv, argv);
10218 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10219 G.last_exitcode = 0;
10220 parse_and_run_file(input);
10221 fclose_and_forget(input);
10223 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10224 restore_G_args(&sv, argv);
10225 #if ENABLE_HUSH_FUNCTIONS
10226 G_flag_return_in_progress = sv_flg;
10229 return G.last_exitcode;
10232 #if ENABLE_HUSH_TRAP
10233 static int FAST_FUNC builtin_trap(char **argv)
10239 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10244 /* No args: print all trapped */
10245 for (i = 0; i < NSIG; ++i) {
10247 printf("trap -- ");
10248 print_escaped(G_traps[i]);
10249 /* note: bash adds "SIG", but only if invoked
10250 * as "bash". If called as "sh", or if set -o posix,
10251 * then it prints short signal names.
10252 * We are printing short names: */
10253 printf(" %s\n", get_signame(i));
10256 /*fflush_all(); - done after each builtin anyway */
10257 return EXIT_SUCCESS;
10261 /* If first arg is a number: reset all specified signals */
10262 sig = bb_strtou(*argv, NULL, 10);
10266 ret = EXIT_SUCCESS;
10268 sighandler_t handler;
10270 sig = get_signum(*argv++);
10272 ret = EXIT_FAILURE;
10273 /* Mimic bash message exactly */
10274 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
10278 free(G_traps[sig]);
10279 G_traps[sig] = xstrdup(new_cmd);
10281 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
10282 get_signame(sig), sig, G_traps[sig]);
10284 /* There is no signal for 0 (EXIT) */
10289 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10291 /* We are removing trap handler */
10292 handler = pick_sighandler(sig);
10293 install_sighandler(sig, handler);
10298 if (!argv[1]) { /* no second arg */
10299 bb_error_msg("trap: invalid arguments");
10300 return EXIT_FAILURE;
10303 /* First arg is "-": reset all specified to default */
10304 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10305 /* Everything else: set arg as signal handler
10306 * (includes "" case, which ignores signal) */
10307 if (argv[0][0] == '-') {
10308 if (argv[0][1] == '\0') { /* "-" */
10309 /* new_cmd remains NULL: "reset these sigs" */
10312 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10315 /* else: "-something", no special meaning */
10320 goto process_sig_list;
10324 #if ENABLE_HUSH_JOB
10325 static struct pipe *parse_jobspec(const char *str)
10330 if (sscanf(str, "%%%u", &jobnum) != 1) {
10332 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10334 bb_error_msg("bad argument '%s'", str);
10337 /* It is "%%", "%+" or "%" - current job */
10338 jobnum = G.last_jobid;
10340 bb_error_msg("no current job");
10344 for (pi = G.job_list; pi; pi = pi->next) {
10345 if (pi->jobid == jobnum) {
10349 bb_error_msg("%u: no such job", jobnum);
10353 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10356 const char *status_string;
10358 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10359 for (job = G.job_list; job; job = job->next) {
10360 if (job->alive_cmds == job->stopped_cmds)
10361 status_string = "Stopped";
10363 status_string = "Running";
10365 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10368 clean_up_last_dead_job();
10370 return EXIT_SUCCESS;
10373 /* built-in 'fg' and 'bg' handler */
10374 static int FAST_FUNC builtin_fg_bg(char **argv)
10379 if (!G_interactive_fd)
10380 return EXIT_FAILURE;
10382 /* If they gave us no args, assume they want the last backgrounded task */
10384 for (pi = G.job_list; pi; pi = pi->next) {
10385 if (pi->jobid == G.last_jobid) {
10389 bb_error_msg("%s: no current job", argv[0]);
10390 return EXIT_FAILURE;
10393 pi = parse_jobspec(argv[1]);
10395 return EXIT_FAILURE;
10397 /* TODO: bash prints a string representation
10398 * of job being foregrounded (like "sleep 1 | cat") */
10399 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10400 /* Put the job into the foreground. */
10401 tcsetpgrp(G_interactive_fd, pi->pgrp);
10404 /* Restart the processes in the job */
10405 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10406 for (i = 0; i < pi->num_cmds; i++) {
10407 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10409 pi->stopped_cmds = 0;
10411 i = kill(- pi->pgrp, SIGCONT);
10413 if (errno == ESRCH) {
10414 delete_finished_job(pi);
10415 return EXIT_SUCCESS;
10417 bb_perror_msg("kill (SIGCONT)");
10420 if (argv[0][0] == 'f') {
10421 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10422 return checkjobs_and_fg_shell(pi);
10424 return EXIT_SUCCESS;
10428 #if ENABLE_HUSH_KILL
10429 static int FAST_FUNC builtin_kill(char **argv)
10433 # if ENABLE_HUSH_JOB
10434 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10442 if (argv[i][0] != '%')
10445 * "kill %N" - job kill
10446 * Converting to pgrp / pid kill
10448 pi = parse_jobspec(argv[i]);
10450 /* Eat bad jobspec */
10454 argv[j - 1] = argv[j];
10461 * In jobs started under job control, we signal
10462 * entire process group by kill -PGRP_ID.
10463 * This happens, f.e., in interactive shell.
10465 * Otherwise, we signal each child via
10466 * kill PID1 PID2 PID3.
10468 * sh -c 'sleep 1|sleep 1 & kill %1'
10469 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10470 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10472 n = G_interactive_fd ? 1 : pi->num_cmds;
10473 dst = alloca(n * sizeof(int)*4);
10475 if (G_interactive_fd)
10476 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10477 else for (j = 0; j < n; j++) {
10478 struct command *cmd = &pi->cmds[j];
10479 /* Skip exited members of the job */
10483 * kill_main has matching code to expect
10484 * leading space. Needed to not confuse
10485 * negative pids with "kill -SIGNAL_NO" syntax
10487 dst += sprintf(dst, " %u", (int)cmd->pid);
10490 } while (argv[++i]);
10494 if (argv[1] || ret == 0) {
10495 ret = run_applet_main(argv, kill_main);
10497 /* else: ret = 1, "kill %bad_jobspec" case */
10502 #if ENABLE_HUSH_WAIT
10503 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10504 #if !ENABLE_HUSH_JOB
10505 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10507 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10514 if (!sigisemptyset(&G.pending_set))
10517 /* waitpid is not interruptible by SA_RESTARTed
10518 * signals which we use. Thus, this ugly dance:
10521 /* Make sure possible SIGCHLD is stored in kernel's
10522 * pending signal mask before we call waitpid.
10523 * Or else we may race with SIGCHLD, lose it,
10524 * and get stuck in sigsuspend...
10526 sigfillset(&oldset); /* block all signals, remember old set */
10527 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10529 if (!sigisemptyset(&G.pending_set)) {
10530 /* Crap! we raced with some signal! */
10534 /*errno = 0; - checkjobs does this */
10535 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10536 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10537 debug_printf_exec("checkjobs:%d\n", ret);
10538 #if ENABLE_HUSH_JOB
10539 if (waitfor_pipe) {
10540 int rcode = job_exited_or_stopped(waitfor_pipe);
10541 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10544 sigprocmask(SIG_SETMASK, &oldset, NULL);
10549 /* if ECHILD, there are no children (ret is -1 or 0) */
10550 /* if ret == 0, no children changed state */
10551 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10552 if (errno == ECHILD || ret) {
10554 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10556 sigprocmask(SIG_SETMASK, &oldset, NULL);
10559 /* Wait for SIGCHLD or any other signal */
10560 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10561 /* Note: sigsuspend invokes signal handler */
10562 sigsuspend(&oldset);
10564 sigprocmask(SIG_SETMASK, &oldset, NULL);
10566 /* So, did we get a signal? */
10567 sig = check_and_run_traps();
10568 if (sig /*&& sig != SIGCHLD - always true */) {
10569 /* Do this for any (non-ignored) signal, not only for ^C */
10573 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10578 static int FAST_FUNC builtin_wait(char **argv)
10583 argv = skip_dash_dash(argv);
10584 if (argv[0] == NULL) {
10585 /* Don't care about wait results */
10586 /* Note 1: must wait until there are no more children */
10587 /* Note 2: must be interruptible */
10589 * $ sleep 3 & sleep 6 & wait
10590 * [1] 30934 sleep 3
10591 * [2] 30935 sleep 6
10594 * $ sleep 3 & sleep 6 & wait
10595 * [1] 30936 sleep 3
10596 * [2] 30937 sleep 6
10598 * ^C <-- after ~4 sec from keyboard
10601 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10605 pid_t pid = bb_strtou(*argv, NULL, 10);
10606 if (errno || pid <= 0) {
10607 #if ENABLE_HUSH_JOB
10608 if (argv[0][0] == '%') {
10609 struct pipe *wait_pipe;
10610 ret = 127; /* bash compat for bad jobspecs */
10611 wait_pipe = parse_jobspec(*argv);
10613 ret = job_exited_or_stopped(wait_pipe);
10615 ret = wait_for_child_or_signal(wait_pipe, 0);
10617 /* waiting on "last dead job" removes it */
10618 clean_up_last_dead_job();
10621 /* else: parse_jobspec() already emitted error msg */
10625 /* mimic bash message */
10626 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10627 ret = EXIT_FAILURE;
10628 continue; /* bash checks all argv[] */
10631 /* Do we have such child? */
10632 ret = waitpid(pid, &status, WNOHANG);
10636 if (errno == ECHILD) {
10637 if (pid == G.last_bg_pid) {
10638 /* "wait $!" but last bg task has already exited. Try:
10639 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10640 * In bash it prints exitcode 0, then 3.
10641 * In dash, it is 127.
10643 ret = G.last_bg_pid_exitcode;
10645 /* Example: "wait 1". mimic bash message */
10646 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10650 bb_perror_msg("wait %s", *argv);
10652 continue; /* bash checks all argv[] */
10655 /* Yes, and it still runs */
10656 ret = wait_for_child_or_signal(NULL, pid);
10658 /* Yes, and it just exited */
10659 process_wait_result(NULL, pid, status);
10660 ret = WEXITSTATUS(status);
10661 if (WIFSIGNALED(status))
10662 ret = 128 + WTERMSIG(status);
10670 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10671 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10674 def = bb_strtou(argv[1], NULL, 10);
10675 if (errno || def < def_min || argv[2]) {
10676 bb_error_msg("%s: bad arguments", argv[0]);
10684 #if ENABLE_HUSH_LOOPS
10685 static int FAST_FUNC builtin_break(char **argv)
10688 if (G.depth_of_loop == 0) {
10689 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10690 /* if we came from builtin_continue(), need to undo "= 1" */
10691 G.flag_break_continue = 0;
10692 return EXIT_SUCCESS; /* bash compat */
10694 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10696 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10697 if (depth == UINT_MAX)
10698 G.flag_break_continue = BC_BREAK;
10699 if (G.depth_of_loop < depth)
10700 G.depth_break_continue = G.depth_of_loop;
10702 return EXIT_SUCCESS;
10705 static int FAST_FUNC builtin_continue(char **argv)
10707 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10708 return builtin_break(argv);
10712 #if ENABLE_HUSH_FUNCTIONS
10713 static int FAST_FUNC builtin_return(char **argv)
10717 if (G_flag_return_in_progress != -1) {
10718 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10719 return EXIT_FAILURE; /* bash compat */
10722 G_flag_return_in_progress = 1;
10725 * out of range: wraps around at 256, does not error out
10726 * non-numeric param:
10727 * f() { false; return qwe; }; f; echo $?
10728 * bash: return: qwe: numeric argument required <== we do this
10729 * 255 <== we also do this
10731 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10736 #if ENABLE_HUSH_TIMES
10737 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10739 static const uint8_t times_tbl[] ALIGN1 = {
10740 ' ', offsetof(struct tms, tms_utime),
10741 '\n', offsetof(struct tms, tms_stime),
10742 ' ', offsetof(struct tms, tms_cutime),
10743 '\n', offsetof(struct tms, tms_cstime),
10750 clk_tck = bb_clk_tck();
10755 unsigned sec, frac;
10757 t = *(clock_t *)(((char *) &buf) + p[1]);
10759 frac = t % clk_tck;
10760 printf("%um%u.%03us%c",
10761 sec / 60, sec % 60,
10762 (frac * 1000) / clk_tck,
10767 return EXIT_SUCCESS;
10771 #if ENABLE_HUSH_MEMLEAK
10772 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10777 # ifdef M_TRIM_THRESHOLD
10778 /* Optional. Reduces probability of false positives */
10781 /* Crude attempt to find where "free memory" starts,
10782 * sans fragmentation. */
10784 l = (unsigned long)p;
10787 if (l < (unsigned long)p) l = (unsigned long)p;
10793 struct mallinfo mi = mallinfo();
10794 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10795 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10799 if (!G.memleak_value)
10800 G.memleak_value = l;
10802 l -= G.memleak_value;
10809 /* Exitcode is "how many kilobytes we leaked since 1st call" */