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
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
86 * [[ /bin/n* ]]; echo 0:$?
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
93 * add =~ regex match operator: STR =~ REGEX
96 //config: bool "hush (64 kb)"
99 //config: hush is a small shell. It handles the normal flow control
100 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101 //config: case/esac. Redirections, here documents, $((arithmetic))
102 //config: and functions are supported.
104 //config: It will compile and work on no-mmu systems.
106 //config: It does not handle select, aliases, tilde expansion,
107 //config: &>file and >&file redirection of stdout+stderr.
109 //config:config HUSH_BASH_COMPAT
110 //config: bool "bash-compatible extensions"
112 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
114 //config:config HUSH_BRACE_EXPANSION
115 //config: bool "Brace expansion"
117 //config: depends on HUSH_BASH_COMPAT
119 //config: Enable {abc,def} extension.
121 //config:config HUSH_LINENO_VAR
122 //config: bool "$LINENO variable"
124 //config: depends on HUSH_BASH_COMPAT
126 //config:config HUSH_BASH_SOURCE_CURDIR
127 //config: bool "'source' and '.' builtins search current directory after $PATH"
128 //config: default n # do not encourage non-standard behavior
129 //config: depends on HUSH_BASH_COMPAT
131 //config: This is not compliant with standards. Avoid if possible.
133 //config:config HUSH_INTERACTIVE
134 //config: bool "Interactive mode"
136 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
138 //config: Enable interactive mode (prompt and command editing).
139 //config: Without this, hush simply reads and executes commands
140 //config: from stdin just like a shell script from a file.
141 //config: No prompt, no PS1/PS2 magic shell variables.
143 //config:config HUSH_SAVEHISTORY
144 //config: bool "Save command history to .hush_history"
146 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
148 //config:config HUSH_JOB
149 //config: bool "Job control"
151 //config: depends on HUSH_INTERACTIVE
153 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154 //config: command (not entire shell), fg/bg builtins work. Without this option,
155 //config: "cmd &" still works by simply spawning a process and immediately
156 //config: prompting for next command (or executing next command in a script),
157 //config: but no separate process group is formed.
159 //config:config HUSH_TICK
160 //config: bool "Support process substitution"
162 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
164 //config: Enable `command` and $(command).
166 //config:config HUSH_IF
167 //config: bool "Support if/then/elif/else/fi"
169 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
171 //config:config HUSH_LOOPS
172 //config: bool "Support for, while and until loops"
174 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
176 //config:config HUSH_CASE
177 //config: bool "Support case ... esac statement"
179 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
181 //config: Enable case ... esac statement. +400 bytes.
183 //config:config HUSH_FUNCTIONS
184 //config: bool "Support funcname() { commands; } syntax"
186 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
188 //config: Enable support for shell functions. +800 bytes.
190 //config:config HUSH_LOCAL
191 //config: bool "local builtin"
193 //config: depends on HUSH_FUNCTIONS
195 //config: Enable support for local variables in functions.
197 //config:config HUSH_RANDOM_SUPPORT
198 //config: bool "Pseudorandom generator and $RANDOM variable"
200 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
202 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
205 //config:config HUSH_MODE_X
206 //config: bool "Support 'hush -x' option and 'set -x' command"
208 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
210 //config: This instructs hush to print commands before execution.
211 //config: Adds ~300 bytes.
213 //config:config HUSH_ECHO
214 //config: bool "echo builtin"
216 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
218 //config:config HUSH_PRINTF
219 //config: bool "printf builtin"
221 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
223 //config:config HUSH_TEST
224 //config: bool "test builtin"
226 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
228 //config:config HUSH_HELP
229 //config: bool "help builtin"
231 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
233 //config:config HUSH_EXPORT
234 //config: bool "export builtin"
236 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
238 //config:config HUSH_EXPORT_N
239 //config: bool "Support 'export -n' option"
241 //config: depends on HUSH_EXPORT
243 //config: export -n unexports variables. It is a bash extension.
245 //config:config HUSH_READONLY
246 //config: bool "readonly builtin"
248 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
250 //config: Enable support for read-only variables.
252 //config:config HUSH_KILL
253 //config: bool "kill builtin (supports kill %jobspec)"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_WAIT
258 //config: bool "wait builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_COMMAND
263 //config: bool "command builtin"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
267 //config:config HUSH_TRAP
268 //config: bool "trap builtin"
270 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272 //config:config HUSH_TYPE
273 //config: bool "type builtin"
275 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
277 //config:config HUSH_TIMES
278 //config: bool "times builtin"
280 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
282 //config:config HUSH_READ
283 //config: bool "read builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config:config HUSH_SET
288 //config: bool "set builtin"
290 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
292 //config:config HUSH_UNSET
293 //config: bool "unset builtin"
295 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
297 //config:config HUSH_ULIMIT
298 //config: bool "ulimit builtin"
300 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
302 //config:config HUSH_UMASK
303 //config: bool "umask builtin"
305 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
307 //config:config HUSH_GETOPTS
308 //config: bool "getopts builtin"
310 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
312 //config:config HUSH_MEMLEAK
313 //config: bool "memleak builtin (debugging)"
315 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
317 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
318 // APPLET_ODDNAME:name main location suid_type help
319 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
320 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
322 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
323 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
325 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
327 /* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
332 //usage:#define hush_trivial_usage
333 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
334 //usage:#define hush_full_usage "\n\n"
335 //usage: "Unix shell interpreter"
337 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
340 # include <malloc.h> /* for malloc_trim */
343 /* #include <dmalloc.h> */
345 # include <fnmatch.h>
347 #include <sys/times.h>
348 #include <sys/utsname.h> /* for setting $HOSTNAME */
350 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
352 #include "shell_common.h"
355 #if ENABLE_HUSH_RANDOM_SUPPORT
358 # define CLEAR_RANDOM_T(rnd) ((void)0)
360 #ifndef F_DUPFD_CLOEXEC
361 # define F_DUPFD_CLOEXEC F_DUPFD
364 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
368 /* So far, all bash compat is controlled by one config option */
369 /* Separate defines document which part of code implements what */
370 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
372 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
374 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
375 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
379 #define LEAK_HUNTING 0
380 #define BUILD_AS_NOMMU 0
381 /* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
386 /* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
392 #define ENABLE_HUSH_FAST 0
393 /* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
396 #define ENABLE_HUSH_DOLLAR_OPS 1
401 # undef USE_FOR_NOMMU
404 # define USE_FOR_NOMMU(...) __VA_ARGS__
405 # define USE_FOR_MMU(...)
408 #include "NUM_APPLETS.h"
410 /* STANDALONE does not make sense, and won't compile */
411 # undef CONFIG_FEATURE_SH_STANDALONE
412 # undef ENABLE_FEATURE_SH_STANDALONE
413 # undef IF_FEATURE_SH_STANDALONE
414 # undef IF_NOT_FEATURE_SH_STANDALONE
415 # define ENABLE_FEATURE_SH_STANDALONE 0
416 # define IF_FEATURE_SH_STANDALONE(...)
417 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
420 #if !ENABLE_HUSH_INTERACTIVE
421 # undef ENABLE_FEATURE_EDITING
422 # define ENABLE_FEATURE_EDITING 0
423 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
425 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
429 /* Do we support ANY keywords? */
430 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
431 # define HAS_KEYWORDS 1
432 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
433 # define IF_HAS_NO_KEYWORDS(...)
435 # define HAS_KEYWORDS 0
436 # define IF_HAS_KEYWORDS(...)
437 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
440 /* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
442 #define debug_printf(...) do {} while (0)
443 /* Finer-grained debug switches */
444 #define debug_printf_parse(...) do {} while (0)
445 #define debug_print_tree(a, b) do {} while (0)
446 #define debug_printf_exec(...) do {} while (0)
447 #define debug_printf_env(...) do {} while (0)
448 #define debug_printf_jobs(...) do {} while (0)
449 #define debug_printf_expand(...) do {} while (0)
450 #define debug_printf_varexp(...) do {} while (0)
451 #define debug_printf_glob(...) do {} while (0)
452 #define debug_printf_redir(...) do {} while (0)
453 #define debug_printf_list(...) do {} while (0)
454 #define debug_printf_subst(...) do {} while (0)
455 #define debug_printf_prompt(...) do {} while (0)
456 #define debug_printf_clean(...) do {} while (0)
458 #define ERR_PTR ((void*)(long)1)
460 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
462 #define _SPECIAL_VARS_STR "_*@$!?#"
463 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
464 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
465 #if BASH_PATTERN_SUBST
466 /* Support / and // replace ops */
467 /* Note that // is stored as \ in "encoded" string representation */
468 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
469 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
470 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
472 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
473 # define VAR_SUBST_OPS "%#:-=+?"
474 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
477 #define SPECIAL_VAR_SYMBOL_STR "\3"
478 #define SPECIAL_VAR_SYMBOL 3
479 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
480 #define SPECIAL_VAR_QUOTED_SVS 1
484 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
486 /* This supports saving pointers malloced in vfork child,
487 * to be freed in the parent.
490 typedef struct nommu_save_t {
491 struct variable *old_vars;
493 char **argv_from_re_execing;
506 #if ENABLE_HUSH_LOOPS
513 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
518 /* three pseudo-keywords support contrived "case" syntax: */
519 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
520 RES_MATCH , /* "word)" */
521 RES_CASE_BODY, /* "this command is inside CASE" */
528 typedef struct o_string {
530 int length; /* position where data is appended */
533 /* At least some part of the string was inside '' or "",
534 * possibly empty one: word"", wo''rd etc. */
535 smallint has_quoted_part;
536 smallint has_empty_slot;
537 smallint ended_in_ifs;
540 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
542 /* Protect newly added chars against globbing
543 * by prepending \ to *, ?, [, \ */
544 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
546 /* Used for initialization: o_string foo = NULL_O_STRING; */
547 #define NULL_O_STRING { NULL }
549 #ifndef debug_printf_parse
550 static const char *const assignment_flag[] = {
552 "DEFINITELY_ASSIGNMENT",
558 typedef struct in_str {
565 /* The descrip member of this structure is only used to make
566 * debugging output pretty */
567 static const struct {
569 signed char default_fd;
572 { O_RDONLY, 0, "<" },
573 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
574 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
575 { O_CREAT|O_RDWR, 1, "<>" },
576 { O_RDONLY, 0, "<<" },
577 /* Should not be needed. Bogus default_fd helps in debugging */
578 /* { O_RDONLY, 77, "<<" }, */
581 struct redir_struct {
582 struct redir_struct *next;
583 char *rd_filename; /* filename */
584 int rd_fd; /* fd to redirect */
585 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
587 smallint rd_type; /* (enum redir_type) */
588 /* note: for heredocs, rd_filename contains heredoc delimiter,
589 * and subsequently heredoc itself; and rd_dup is a bitmask:
590 * bit 0: do we need to trim leading tabs?
591 * bit 1: is heredoc quoted (<<'delim' syntax) ?
594 typedef enum redir_type {
596 REDIRECT_OVERWRITE = 1,
599 REDIRECT_HEREDOC = 4,
600 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
603 REDIRFD_SYNTAX_ERR = -2,
604 REDIRFD_TO_FILE = -1,
605 /* otherwise, rd_fd is redirected to rd_dup */
607 HEREDOC_SKIPTABS = 1,
613 pid_t pid; /* 0 if exited */
614 unsigned assignment_cnt; /* how many argv[i] are assignments? */
615 #if ENABLE_HUSH_LINENO_VAR
618 smallint cmd_type; /* CMD_xxx */
620 #define CMD_SUBSHELL 1
621 #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
622 /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
625 # define CMD_SINGLEWORD_NOGLOB 2
627 #if ENABLE_HUSH_FUNCTIONS
628 # define CMD_FUNCDEF 3
631 smalluint cmd_exitcode;
632 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
635 char *group_as_string;
637 #if ENABLE_HUSH_FUNCTIONS
638 struct function *child_func;
639 /* This field is used to prevent a bug here:
640 * while...do f1() {a;}; f1; f1() {b;}; f1; done
641 * When we execute "f1() {a;}" cmd, we create new function and clear
642 * cmd->group, cmd->group_as_string, cmd->argv[0].
643 * When we execute "f1() {b;}", we notice that f1 exists,
644 * and that its "parent cmd" struct is still "alive",
645 * we put those fields back into cmd->xxx
646 * (struct function has ->parent_cmd ptr to facilitate that).
647 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
648 * Without this trick, loop would execute a;b;b;b;...
649 * instead of correct sequence a;b;a;b;...
650 * When command is freed, it severs the link
651 * (sets ->child_func->parent_cmd to NULL).
654 char **argv; /* command name and arguments */
655 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
656 * and on execution these are substituted with their values.
657 * Substitution can make _several_ words out of one argv[n]!
658 * Example: argv[0]=='.^C*^C.' here: echo .$*.
659 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
661 struct redir_struct *redirects; /* I/O redirections */
663 /* Is there anything in this command at all? */
664 #define IS_NULL_CMD(cmd) \
665 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
669 int num_cmds; /* total number of commands in pipe */
670 int alive_cmds; /* number of commands running (not exited) */
671 int stopped_cmds; /* number of commands alive, but stopped */
673 unsigned jobid; /* job number */
674 pid_t pgrp; /* process group ID for the job */
675 char *cmdtext; /* name of job */
677 struct command *cmds; /* array of commands in pipe */
678 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
679 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
680 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
682 typedef enum pipe_style {
688 /* Is there anything in this pipe at all? */
689 #define IS_NULL_PIPE(pi) \
690 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
692 /* This holds pointers to the various results of parsing */
693 struct parse_context {
694 /* linked list of pipes */
695 struct pipe *list_head;
696 /* last pipe (being constructed right now) */
698 /* last command in pipe (being constructed right now) */
699 struct command *command;
700 /* last redirect in command->redirects list */
701 struct redir_struct *pending_redirect;
706 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
709 smallint ctx_inverted; /* "! cmd | cmd" */
711 smallint ctx_dsemicolon; /* ";;" seen */
713 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
715 /* group we are enclosed in:
716 * example: "if pipe1; pipe2; then pipe3; fi"
717 * when we see "if" or "then", we malloc and copy current context,
718 * and make ->stack point to it. then we parse pipeN.
719 * when closing "then" / fi" / whatever is found,
720 * we move list_head into ->stack->command->group,
721 * copy ->stack into current context, and delete ->stack.
722 * (parsing of { list } and ( list ) doesn't use this method)
724 struct parse_context *stack;
728 MAYBE_ASSIGNMENT = 0,
729 DEFINITELY_ASSIGNMENT = 1,
731 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
735 /* On program start, environ points to initial environment.
736 * putenv adds new pointers into it, unsetenv removes them.
737 * Neither of these (de)allocates the strings.
738 * setenv allocates new strings in malloc space and does putenv,
739 * and thus setenv is unusable (leaky) for shell's purposes */
740 #define setenv(...) setenv_is_leaky_dont_use()
742 struct variable *next;
743 char *varstr; /* points to "name=" portion */
744 int max_len; /* if > 0, name is part of initial env; else name is malloced */
745 uint16_t var_nest_level;
746 smallint flg_export; /* putenv should be done on this var */
747 smallint flg_read_only;
755 #if ENABLE_HUSH_FUNCTIONS
757 struct function *next;
759 struct command *parent_cmd;
762 char *body_as_string;
768 /* set -/+o OPT support. (TODO: make it optional)
769 * bash supports the following opts:
780 * interactive-comments on
798 static const char o_opt_strings[] ALIGN1 =
802 #if ENABLE_HUSH_MODE_X
810 #if ENABLE_HUSH_MODE_X
818 struct FILE_list *next;
824 /* "Globals" within this file */
825 /* Sorted roughly by size (smaller offsets == smaller code) */
827 /* interactive_fd != 0 means we are an interactive shell.
828 * If we are, then saved_tty_pgrp can also be != 0, meaning
829 * that controlling tty is available. With saved_tty_pgrp == 0,
830 * job control still works, but terminal signals
831 * (^C, ^Z, ^Y, ^\) won't work at all, and background
832 * process groups can only be created with "cmd &".
833 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
834 * to give tty to the foreground process group,
835 * and will take it back when the group is stopped (^Z)
838 #if ENABLE_HUSH_INTERACTIVE
839 /* 'interactive_fd' is a fd# open to ctty, if we have one
840 * _AND_ if we decided to act interactively */
843 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
844 # define G_interactive_fd (G.interactive_fd)
846 # define G_interactive_fd 0
848 #if ENABLE_FEATURE_EDITING
849 line_input_t *line_input_state;
854 #if ENABLE_HUSH_RANDOM_SUPPORT
860 pid_t saved_tty_pgrp;
861 struct pipe *job_list;
862 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
864 # define G_saved_tty_pgrp 0
866 /* How deeply are we in context where "set -e" is ignored */
868 /* "set -e" rules (do we follow them correctly?):
869 * Exit if pipe, list, or compound command exits with a non-zero status.
870 * Shell does not exit if failed command is part of condition in
871 * if/while, part of && or || list except the last command, any command
872 * in a pipe but the last, or if the command's return value is being
873 * inverted with !. If a compound command other than a subshell returns a
874 * non-zero status because a command failed while -e was being ignored, the
875 * shell does not exit. A trap on ERR, if set, is executed before the shell
876 * exits [ERR is a bashism].
878 * If a compound command or function executes in a context where -e is
879 * ignored, none of the commands executed within are affected by the -e
880 * setting. If a compound command or function sets -e while executing in a
881 * context where -e is ignored, that setting does not have any effect until
882 * the compound command or the command containing the function call completes.
885 char o_opt[NUM_OPT_O];
886 #if ENABLE_HUSH_MODE_X
887 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
891 #if ENABLE_HUSH_INTERACTIVE
892 smallint promptmode; /* 0: PS1, 1: PS2 */
894 smallint flag_SIGINT;
895 #if ENABLE_HUSH_LOOPS
896 smallint flag_break_continue;
898 #if ENABLE_HUSH_FUNCTIONS
899 /* 0: outside of a function (or sourced file)
900 * -1: inside of a function, ok to use return builtin
901 * 1: return is invoked, skip all till end of func
903 smallint flag_return_in_progress;
904 # define G_flag_return_in_progress (G.flag_return_in_progress)
906 # define G_flag_return_in_progress 0
908 smallint exiting; /* used to prevent EXIT trap recursion */
909 /* These support $?, $#, and $1 */
910 smalluint last_exitcode;
911 smalluint expand_exitcode;
912 smalluint last_bg_pid_exitcode;
914 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
915 smalluint global_args_malloced;
916 # define G_global_args_malloced (G.global_args_malloced)
918 # define G_global_args_malloced 0
920 /* how many non-NULL argv's we have. NB: $# + 1 */
924 char *argv0_for_re_execing;
926 #if ENABLE_HUSH_LOOPS
927 unsigned depth_break_continue;
928 unsigned depth_of_loop;
930 #if ENABLE_HUSH_GETOPTS
931 unsigned getopt_count;
934 char *ifs_whitespace; /* = G.ifs or malloced */
936 struct variable *top_var;
937 char **expanded_assignments;
938 struct variable **shadowed_vars_pp;
939 unsigned var_nest_level;
940 #if ENABLE_HUSH_FUNCTIONS
941 # if ENABLE_HUSH_LOCAL
942 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
944 struct function *top_func;
946 /* Signal and trap handling */
948 unsigned count_SIGCHLD;
949 unsigned handled_SIGCHLD;
950 smallint we_have_children;
952 #if ENABLE_HUSH_LINENO_VAR
956 struct FILE_list *FILE_list;
957 /* Which signals have non-DFL handler (even with no traps set)?
958 * Set at the start to:
959 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
960 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
961 * The rest is cleared right before execv syscalls.
962 * Other than these two times, never modified.
964 unsigned special_sig_mask;
966 unsigned fatal_sig_mask;
967 # define G_fatal_sig_mask (G.fatal_sig_mask)
969 # define G_fatal_sig_mask 0
972 char **traps; /* char *traps[NSIG] */
973 # define G_traps G.traps
975 # define G_traps ((char**)NULL)
977 sigset_t pending_set;
978 #if ENABLE_HUSH_MEMLEAK
979 unsigned long memleak_value;
985 #if ENABLE_FEATURE_EDITING
986 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
989 #define G (*ptr_to_globals)
990 /* Not #defining name to G.name - this quickly gets unwieldy
991 * (too many defines). Also, I actually prefer to see when a variable
992 * is global, thus "G." prefix is a useful hint */
993 #define INIT_G() do { \
994 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
995 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
996 sigfillset(&G.sa.sa_mask); \
997 G.sa.sa_flags = SA_RESTART; \
1001 /* Function prototypes for builtins */
1002 static int builtin_cd(char **argv) FAST_FUNC;
1003 #if ENABLE_HUSH_ECHO
1004 static int builtin_echo(char **argv) FAST_FUNC;
1006 static int builtin_eval(char **argv) FAST_FUNC;
1007 static int builtin_exec(char **argv) FAST_FUNC;
1008 static int builtin_exit(char **argv) FAST_FUNC;
1009 #if ENABLE_HUSH_EXPORT
1010 static int builtin_export(char **argv) FAST_FUNC;
1012 #if ENABLE_HUSH_READONLY
1013 static int builtin_readonly(char **argv) FAST_FUNC;
1016 static int builtin_fg_bg(char **argv) FAST_FUNC;
1017 static int builtin_jobs(char **argv) FAST_FUNC;
1019 #if ENABLE_HUSH_GETOPTS
1020 static int builtin_getopts(char **argv) FAST_FUNC;
1022 #if ENABLE_HUSH_HELP
1023 static int builtin_help(char **argv) FAST_FUNC;
1025 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1026 static int builtin_history(char **argv) FAST_FUNC;
1028 #if ENABLE_HUSH_LOCAL
1029 static int builtin_local(char **argv) FAST_FUNC;
1031 #if ENABLE_HUSH_MEMLEAK
1032 static int builtin_memleak(char **argv) FAST_FUNC;
1034 #if ENABLE_HUSH_PRINTF
1035 static int builtin_printf(char **argv) FAST_FUNC;
1037 static int builtin_pwd(char **argv) FAST_FUNC;
1038 #if ENABLE_HUSH_READ
1039 static int builtin_read(char **argv) FAST_FUNC;
1042 static int builtin_set(char **argv) FAST_FUNC;
1044 static int builtin_shift(char **argv) FAST_FUNC;
1045 static int builtin_source(char **argv) FAST_FUNC;
1046 #if ENABLE_HUSH_TEST || BASH_TEST2
1047 static int builtin_test(char **argv) FAST_FUNC;
1049 #if ENABLE_HUSH_TRAP
1050 static int builtin_trap(char **argv) FAST_FUNC;
1052 #if ENABLE_HUSH_TYPE
1053 static int builtin_type(char **argv) FAST_FUNC;
1055 #if ENABLE_HUSH_TIMES
1056 static int builtin_times(char **argv) FAST_FUNC;
1058 static int builtin_true(char **argv) FAST_FUNC;
1059 #if ENABLE_HUSH_UMASK
1060 static int builtin_umask(char **argv) FAST_FUNC;
1062 #if ENABLE_HUSH_UNSET
1063 static int builtin_unset(char **argv) FAST_FUNC;
1065 #if ENABLE_HUSH_KILL
1066 static int builtin_kill(char **argv) FAST_FUNC;
1068 #if ENABLE_HUSH_WAIT
1069 static int builtin_wait(char **argv) FAST_FUNC;
1071 #if ENABLE_HUSH_LOOPS
1072 static int builtin_break(char **argv) FAST_FUNC;
1073 static int builtin_continue(char **argv) FAST_FUNC;
1075 #if ENABLE_HUSH_FUNCTIONS
1076 static int builtin_return(char **argv) FAST_FUNC;
1079 /* Table of built-in functions. They can be forked or not, depending on
1080 * context: within pipes, they fork. As simple commands, they do not.
1081 * When used in non-forking context, they can change global variables
1082 * in the parent shell process. If forked, of course they cannot.
1083 * For example, 'unset foo | whatever' will parse and run, but foo will
1084 * still be set at the end. */
1085 struct built_in_command {
1087 int (*b_function)(char **argv) FAST_FUNC;
1088 #if ENABLE_HUSH_HELP
1089 const char *b_descr;
1090 # define BLTIN(cmd, func, help) { cmd, func, help }
1092 # define BLTIN(cmd, func, help) { cmd, func }
1096 static const struct built_in_command bltins1[] = {
1097 BLTIN("." , builtin_source , "Run commands in file"),
1098 BLTIN(":" , builtin_true , NULL),
1100 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1102 #if ENABLE_HUSH_LOOPS
1103 BLTIN("break" , builtin_break , "Exit loop"),
1105 BLTIN("cd" , builtin_cd , "Change directory"),
1106 #if ENABLE_HUSH_LOOPS
1107 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1109 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1110 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1111 BLTIN("exit" , builtin_exit , NULL),
1112 #if ENABLE_HUSH_EXPORT
1113 BLTIN("export" , builtin_export , "Set environment variables"),
1116 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1118 #if ENABLE_HUSH_GETOPTS
1119 BLTIN("getopts" , builtin_getopts , NULL),
1121 #if ENABLE_HUSH_HELP
1122 BLTIN("help" , builtin_help , NULL),
1124 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1125 BLTIN("history" , builtin_history , "Show history"),
1128 BLTIN("jobs" , builtin_jobs , "List jobs"),
1130 #if ENABLE_HUSH_KILL
1131 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1133 #if ENABLE_HUSH_LOCAL
1134 BLTIN("local" , builtin_local , "Set local variables"),
1136 #if ENABLE_HUSH_MEMLEAK
1137 BLTIN("memleak" , builtin_memleak , NULL),
1139 #if ENABLE_HUSH_READ
1140 BLTIN("read" , builtin_read , "Input into variable"),
1142 #if ENABLE_HUSH_READONLY
1143 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1145 #if ENABLE_HUSH_FUNCTIONS
1146 BLTIN("return" , builtin_return , "Return from function"),
1149 BLTIN("set" , builtin_set , "Set positional parameters"),
1151 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1153 BLTIN("source" , builtin_source , NULL),
1155 #if ENABLE_HUSH_TIMES
1156 BLTIN("times" , builtin_times , NULL),
1158 #if ENABLE_HUSH_TRAP
1159 BLTIN("trap" , builtin_trap , "Trap signals"),
1161 BLTIN("true" , builtin_true , NULL),
1162 #if ENABLE_HUSH_TYPE
1163 BLTIN("type" , builtin_type , "Show command type"),
1165 #if ENABLE_HUSH_ULIMIT
1166 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1168 #if ENABLE_HUSH_UMASK
1169 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1171 #if ENABLE_HUSH_UNSET
1172 BLTIN("unset" , builtin_unset , "Unset variables"),
1174 #if ENABLE_HUSH_WAIT
1175 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1178 /* These builtins won't be used if we are on NOMMU and need to re-exec
1179 * (it's cheaper to run an external program in this case):
1181 static const struct built_in_command bltins2[] = {
1182 #if ENABLE_HUSH_TEST
1183 BLTIN("[" , builtin_test , NULL),
1186 BLTIN("[[" , builtin_test , NULL),
1188 #if ENABLE_HUSH_ECHO
1189 BLTIN("echo" , builtin_echo , NULL),
1191 #if ENABLE_HUSH_PRINTF
1192 BLTIN("printf" , builtin_printf , NULL),
1194 BLTIN("pwd" , builtin_pwd , NULL),
1195 #if ENABLE_HUSH_TEST
1196 BLTIN("test" , builtin_test , NULL),
1204 /* prevent disasters with G.debug_indent < 0 */
1205 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1206 # define debug_enter() (G.debug_indent++)
1207 # define debug_leave() (G.debug_indent--)
1209 # define indent() ((void)0)
1210 # define debug_enter() ((void)0)
1211 # define debug_leave() ((void)0)
1214 #ifndef debug_printf
1215 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1218 #ifndef debug_printf_parse
1219 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1222 #ifndef debug_printf_exec
1223 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1226 #ifndef debug_printf_env
1227 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1230 #ifndef debug_printf_jobs
1231 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1232 # define DEBUG_JOBS 1
1234 # define DEBUG_JOBS 0
1237 #ifndef debug_printf_expand
1238 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1239 # define DEBUG_EXPAND 1
1241 # define DEBUG_EXPAND 0
1244 #ifndef debug_printf_varexp
1245 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1248 #ifndef debug_printf_glob
1249 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1250 # define DEBUG_GLOB 1
1252 # define DEBUG_GLOB 0
1255 #ifndef debug_printf_redir
1256 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1259 #ifndef debug_printf_list
1260 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1263 #ifndef debug_printf_subst
1264 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1267 #ifndef debug_printf_prompt
1268 # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1271 #ifndef debug_printf_clean
1272 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1273 # define DEBUG_CLEAN 1
1275 # define DEBUG_CLEAN 0
1279 static void debug_print_strings(const char *prefix, char **vv)
1282 fdprintf(2, "%s:\n", prefix);
1284 fdprintf(2, " '%s'\n", *vv++);
1287 # define debug_print_strings(prefix, vv) ((void)0)
1291 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1294 static void *xxmalloc(int lineno, size_t size)
1296 void *ptr = xmalloc((size + 0xff) & ~0xff);
1297 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1300 static void *xxrealloc(int lineno, void *ptr, size_t size)
1302 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1303 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1306 static char *xxstrdup(int lineno, const char *str)
1308 char *ptr = xstrdup(str);
1309 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1312 static void xxfree(void *ptr)
1314 fdprintf(2, "free %p\n", ptr);
1317 # define xmalloc(s) xxmalloc(__LINE__, s)
1318 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1319 # define xstrdup(s) xxstrdup(__LINE__, s)
1320 # define free(p) xxfree(p)
1324 /* Syntax and runtime errors. They always abort scripts.
1325 * In interactive use they usually discard unparsed and/or unexecuted commands
1326 * and return to the prompt.
1327 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1330 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1331 # define syntax_error(lineno, msg) syntax_error(msg)
1332 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1333 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1334 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1335 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1338 static void die_if_script(void)
1340 if (!G_interactive_fd) {
1341 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1342 xfunc_error_retval = G.last_exitcode;
1347 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1352 bb_error_msg("hush.c:%u", lineno);
1355 bb_verror_msg(fmt, p, NULL);
1360 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1363 bb_error_msg("syntax error: %s", msg);
1365 bb_error_msg("syntax error");
1369 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1371 bb_error_msg("syntax error at '%s'", msg);
1375 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1377 bb_error_msg("syntax error: unterminated %s", s);
1378 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1382 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1384 char msg[2] = { ch, '\0' };
1385 syntax_error_unterm_str(lineno, msg);
1388 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1394 bb_error_msg("hush.c:%u", lineno);
1396 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1401 # undef msg_and_die_if_script
1402 # undef syntax_error
1403 # undef syntax_error_at
1404 # undef syntax_error_unterm_ch
1405 # undef syntax_error_unterm_str
1406 # undef syntax_error_unexpected_ch
1408 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1409 # define syntax_error(msg) syntax_error(__LINE__, msg)
1410 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1411 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1412 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1413 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1417 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1418 static void cmdedit_update_prompt(void);
1420 # define cmdedit_update_prompt() ((void)0)
1424 /* Utility functions
1426 /* Replace each \x with x in place, return ptr past NUL. */
1427 static char *unbackslash(char *src)
1429 char *dst = src = strchrnul(src, '\\');
1438 /* else: "\<nul>". Do not delete this backslash.
1439 * Testcase: eval 'echo ok\'
1444 if ((*dst++ = *src++) == '\0')
1450 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1471 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1472 v[count1 + count2] = NULL;
1475 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1479 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1481 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1482 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1485 #define add_strings_to_strings(strings, add, need_to_dup) \
1486 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1489 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1490 static char **add_string_to_strings(char **strings, char *add)
1495 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1498 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1500 char **ptr = add_string_to_strings(strings, add);
1501 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1504 #define add_string_to_strings(strings, add) \
1505 xx_add_string_to_strings(__LINE__, strings, add)
1508 static void free_strings(char **strings)
1522 static int dup_CLOEXEC(int fd, int avoid_fd)
1526 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1528 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1529 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1530 } else { /* newfd < 0 */
1539 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1543 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1549 /* fd was not open? */
1554 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1555 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1561 /* Manipulating the list of open FILEs */
1562 static FILE *remember_FILE(FILE *fp)
1565 struct FILE_list *n = xmalloc(sizeof(*n));
1566 n->next = G.FILE_list;
1570 close_on_exec_on(n->fd);
1574 static void fclose_and_forget(FILE *fp)
1576 struct FILE_list **pp = &G.FILE_list;
1578 struct FILE_list *cur = *pp;
1579 if (cur->fp == fp) {
1588 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1590 struct FILE_list *fl = G.FILE_list;
1593 /* We use it only on script files, they are all CLOEXEC */
1594 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1595 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1602 static void restore_redirected_FILEs(void)
1604 struct FILE_list *fl = G.FILE_list;
1606 int should_be = fileno(fl->fp);
1607 if (fl->fd != should_be) {
1608 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1609 xmove_fd(fl->fd, should_be);
1615 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1616 static void close_all_FILE_list(void)
1618 struct FILE_list *fl = G.FILE_list;
1620 /* fclose would also free FILE object.
1621 * It is disastrous if we share memory with a vforked parent.
1622 * I'm not sure we never come here after vfork.
1623 * Therefore just close fd, nothing more.
1625 /*fclose(fl->fp); - unsafe */
1631 static int fd_in_FILEs(int fd)
1633 struct FILE_list *fl = G.FILE_list;
1643 /* Helpers for setting new $n and restoring them back
1645 typedef struct save_arg_t {
1649 IF_HUSH_SET(smallint sv_g_malloced;)
1652 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1654 sv->sv_argv0 = argv[0];
1655 sv->sv_g_argv = G.global_argv;
1656 sv->sv_g_argc = G.global_argc;
1657 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1659 argv[0] = G.global_argv[0]; /* retain $0 */
1660 G.global_argv = argv;
1661 IF_HUSH_SET(G.global_args_malloced = 0;)
1663 G.global_argc = 1 + string_array_len(argv + 1);
1666 static void restore_G_args(save_arg_t *sv, char **argv)
1669 if (G.global_args_malloced) {
1670 /* someone ran "set -- arg1 arg2 ...", undo */
1671 char **pp = G.global_argv;
1672 while (*++pp) /* note: does not free $0 */
1674 free(G.global_argv);
1677 argv[0] = sv->sv_argv0;
1678 G.global_argv = sv->sv_g_argv;
1679 G.global_argc = sv->sv_g_argc;
1680 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1684 /* Basic theory of signal handling in shell
1685 * ========================================
1686 * This does not describe what hush does, rather, it is current understanding
1687 * what it _should_ do. If it doesn't, it's a bug.
1688 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1690 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1691 * is finished or backgrounded. It is the same in interactive and
1692 * non-interactive shells, and is the same regardless of whether
1693 * a user trap handler is installed or a shell special one is in effect.
1694 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1695 * backgrounds (i.e. stops) or kills all members of currently running
1698 * Wait builtin is interruptible by signals for which user trap is set
1699 * or by SIGINT in interactive shell.
1701 * Trap handlers will execute even within trap handlers. (right?)
1703 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1704 * except for handlers set to '' (empty string).
1706 * If job control is off, backgrounded commands ("cmd &")
1707 * have SIGINT, SIGQUIT set to SIG_IGN.
1709 * Commands which are run in command substitution ("`cmd`")
1710 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1712 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1713 * by the shell from its parent.
1715 * Signals which differ from SIG_DFL action
1716 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1719 * SIGTERM (interactive): ignore
1720 * SIGHUP (interactive):
1721 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1722 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1723 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1724 * that all pipe members are stopped. Try this in bash:
1725 * while :; do :; done - ^Z does not background it
1726 * (while :; do :; done) - ^Z backgrounds it
1727 * SIGINT (interactive): wait for last pipe, ignore the rest
1728 * of the command line, show prompt. NB: ^C does not send SIGINT
1729 * to interactive shell while shell is waiting for a pipe,
1730 * since shell is bg'ed (is not in foreground process group).
1731 * Example 1: this waits 5 sec, but does not execute ls:
1732 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1733 * Example 2: this does not wait and does not execute ls:
1734 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1735 * Example 3: this does not wait 5 sec, but executes ls:
1736 * "sleep 5; ls -l" + press ^C
1737 * Example 4: this does not wait and does not execute ls:
1738 * "sleep 5 & wait; ls -l" + press ^C
1740 * (What happens to signals which are IGN on shell start?)
1741 * (What happens with signal mask on shell start?)
1743 * Old implementation
1744 * ==================
1745 * We use in-kernel pending signal mask to determine which signals were sent.
1746 * We block all signals which we don't want to take action immediately,
1747 * i.e. we block all signals which need to have special handling as described
1748 * above, and all signals which have traps set.
1749 * After each pipe execution, we extract any pending signals via sigtimedwait()
1752 * unsigned special_sig_mask: a mask of such "special" signals
1753 * sigset_t blocked_set: current blocked signal set
1756 * clear bit in blocked_set unless it is also in special_sig_mask
1757 * "trap 'cmd' SIGxxx":
1758 * set bit in blocked_set (even if 'cmd' is '')
1759 * after [v]fork, if we plan to be a shell:
1760 * unblock signals with special interactive handling
1761 * (child shell is not interactive),
1762 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1763 * after [v]fork, if we plan to exec:
1764 * POSIX says fork clears pending signal mask in child - no need to clear it.
1765 * Restore blocked signal set to one inherited by shell just prior to exec.
1767 * Note: as a result, we do not use signal handlers much. The only uses
1768 * are to count SIGCHLDs
1769 * and to restore tty pgrp on signal-induced exit.
1772 * Standard says "When a subshell is entered, traps that are not being ignored
1773 * are set to the default actions". bash interprets it so that traps which
1774 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1776 * Problem: the above approach makes it unwieldy to catch signals while
1777 * we are in read builtin, or while we read commands from stdin:
1778 * masked signals are not visible!
1780 * New implementation
1781 * ==================
1782 * We record each signal we are interested in by installing signal handler
1783 * for them - a bit like emulating kernel pending signal mask in userspace.
1784 * We are interested in: signals which need to have special handling
1785 * as described above, and all signals which have traps set.
1786 * Signals are recorded in pending_set.
1787 * After each pipe execution, we extract any pending signals
1790 * unsigned special_sig_mask: a mask of shell-special signals.
1791 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1792 * char *traps[sig] if trap for sig is set (even if it's '').
1793 * sigset_t pending_set: set of sigs we received.
1796 * if sig is in special_sig_mask, set handler back to:
1797 * record_pending_signo, or to IGN if it's a tty stop signal
1798 * if sig is in fatal_sig_mask, set handler back to sigexit.
1799 * else: set handler back to SIG_DFL
1800 * "trap 'cmd' SIGxxx":
1801 * set handler to record_pending_signo.
1803 * set handler to SIG_IGN.
1804 * after [v]fork, if we plan to be a shell:
1805 * set signals with special interactive handling to SIG_DFL
1806 * (because child shell is not interactive),
1807 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1808 * after [v]fork, if we plan to exec:
1809 * POSIX says fork clears pending signal mask in child - no need to clear it.
1811 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1812 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1815 * Standard says "When a subshell is entered, traps that are not being ignored
1816 * are set to the default actions". bash interprets it so that traps which
1817 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1820 SPECIAL_INTERACTIVE_SIGS = 0
1825 SPECIAL_JOBSTOP_SIGS = 0
1834 static void record_pending_signo(int sig)
1836 sigaddset(&G.pending_set, sig);
1837 #if ENABLE_HUSH_FAST
1838 if (sig == SIGCHLD) {
1840 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1845 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1847 struct sigaction old_sa;
1849 /* We could use signal() to install handlers... almost:
1850 * except that we need to mask ALL signals while handlers run.
1851 * I saw signal nesting in strace, race window isn't small.
1852 * SA_RESTART is also needed, but in Linux, signal()
1853 * sets SA_RESTART too.
1855 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1856 /* sigfillset(&G.sa.sa_mask); - already done */
1857 /* G.sa.sa_flags = SA_RESTART; - already done */
1858 G.sa.sa_handler = handler;
1859 sigaction(sig, &G.sa, &old_sa);
1860 return old_sa.sa_handler;
1863 static void hush_exit(int exitcode) NORETURN;
1865 static void restore_ttypgrp_and__exit(void) NORETURN;
1866 static void restore_ttypgrp_and__exit(void)
1868 /* xfunc has failed! die die die */
1869 /* no EXIT traps, this is an escape hatch! */
1871 hush_exit(xfunc_error_retval);
1876 /* Needed only on some libc:
1877 * It was observed that on exit(), fgetc'ed buffered data
1878 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1879 * With the net effect that even after fork(), not vfork(),
1880 * exit() in NOEXECed applet in "sh SCRIPT":
1881 * noexec_applet_here
1882 * echo END_OF_SCRIPT
1883 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1884 * This makes "echo END_OF_SCRIPT" executed twice.
1885 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1886 * and in `cmd` handling.
1887 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1889 static void fflush_and__exit(void) NORETURN;
1890 static void fflush_and__exit(void)
1893 _exit(xfunc_error_retval);
1896 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1897 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1898 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1899 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1901 /* Restores tty foreground process group, and exits.
1902 * May be called as signal handler for fatal signal
1903 * (will resend signal to itself, producing correct exit state)
1904 * or called directly with -EXITCODE.
1905 * We also call it if xfunc is exiting.
1907 static void sigexit(int sig) NORETURN;
1908 static void sigexit(int sig)
1910 /* Careful: we can end up here after [v]fork. Do not restore
1911 * tty pgrp then, only top-level shell process does that */
1912 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1913 /* Disable all signals: job control, SIGPIPE, etc.
1914 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1916 sigprocmask_allsigs(SIG_BLOCK);
1917 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1920 /* Not a signal, just exit */
1924 kill_myself_with_sig(sig); /* does not return */
1928 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1929 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1933 static sighandler_t pick_sighandler(unsigned sig)
1935 sighandler_t handler = SIG_DFL;
1936 if (sig < sizeof(unsigned)*8) {
1937 unsigned sigmask = (1 << sig);
1941 if (G_fatal_sig_mask & sigmask)
1945 /* sig has special handling? */
1946 if (G.special_sig_mask & sigmask) {
1947 handler = record_pending_signo;
1948 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1949 * in order to ignore them: they will be raised
1950 * in an endless loop when we try to do some
1951 * terminal ioctls! We do have to _ignore_ these.
1953 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1960 /* Restores tty foreground process group, and exits. */
1961 static void hush_exit(int exitcode)
1963 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1964 save_history(G.line_input_state);
1968 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1970 /* argv[0] is unused */
1971 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
1973 G.exiting = 1; /* prevent EXIT trap recursion */
1974 /* Note: G_traps[0] is not cleared!
1975 * "trap" will still show it, if executed
1980 #if ENABLE_FEATURE_CLEAN_UP
1982 struct variable *cur_var;
1983 if (G.cwd != bb_msg_unknown)
1985 cur_var = G.top_var;
1987 struct variable *tmp = cur_var;
1988 if (!cur_var->max_len)
1989 free(cur_var->varstr);
1990 cur_var = cur_var->next;
1998 sigexit(- (exitcode & 0xff));
2005 //TODO: return a mask of ALL handled sigs?
2006 static int check_and_run_traps(void)
2013 if (sigisemptyset(&G.pending_set))
2018 if (sigismember(&G.pending_set, sig)) {
2019 sigdelset(&G.pending_set, sig);
2022 } while (sig < NSIG);
2025 if (G_traps && G_traps[sig]) {
2026 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
2027 if (G_traps[sig][0]) {
2028 /* We have user-defined handler */
2029 smalluint save_rcode;
2031 /* argv[0] is unused */
2032 argv[1] = xstrdup(G_traps[sig]);
2033 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
2035 save_rcode = G.last_exitcode;
2038 //FIXME: shouldn't it be set to 128 + sig instead?
2039 G.last_exitcode = save_rcode;
2041 } /* else: "" trap, ignoring signal */
2044 /* not a trap: special action */
2047 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2053 //TODO: why are we doing this? ash and dash don't do this,
2054 //they have no handler for SIGHUP at all,
2055 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2057 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2058 /* bash is observed to signal whole process groups,
2059 * not individual processes */
2060 for (job = G.job_list; job; job = job->next) {
2063 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2064 if (kill(- job->pgrp, SIGHUP) == 0)
2065 kill(- job->pgrp, SIGCONT);
2070 #if ENABLE_HUSH_FAST
2072 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2074 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2076 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2077 * This simplifies wait builtin a bit.
2081 default: /* ignored: */
2082 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2083 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2085 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2086 * Example: wait is not interrupted by TERM
2087 * in interactive shell, because TERM is ignored.
2096 static const char *get_cwd(int force)
2098 if (force || G.cwd == NULL) {
2099 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2100 * we must not try to free(bb_msg_unknown) */
2101 if (G.cwd == bb_msg_unknown)
2103 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2105 G.cwd = bb_msg_unknown;
2112 * Shell and environment variable support
2114 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2116 struct variable **pp;
2117 struct variable *cur;
2120 while ((cur = *pp) != NULL) {
2121 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2128 static const char* FAST_FUNC get_local_var_value(const char *name)
2130 struct variable **vpp;
2131 unsigned len = strlen(name);
2133 if (G.expanded_assignments) {
2134 char **cpp = G.expanded_assignments;
2137 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2138 return cp + len + 1;
2143 vpp = get_ptr_to_local_var(name, len);
2145 return (*vpp)->varstr + len + 1;
2147 if (strcmp(name, "PPID") == 0)
2148 return utoa(G.root_ppid);
2149 // bash compat: UID? EUID?
2150 #if ENABLE_HUSH_RANDOM_SUPPORT
2151 if (strcmp(name, "RANDOM") == 0)
2152 return utoa(next_random(&G.random_gen));
2157 static void handle_changed_special_names(const char *name, unsigned name_len)
2159 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2160 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2162 cmdedit_update_prompt();
2166 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2169 #if ENABLE_HUSH_LINENO_VAR
2170 if (strncmp(name, "LINENO", 6) == 0) {
2171 G.lineno_var = NULL;
2175 #if ENABLE_HUSH_GETOPTS
2176 if (strncmp(name, "OPTIND", 6) == 0) {
2184 /* str holds "NAME=VAL" and is expected to be malloced.
2185 * We take ownership of it.
2187 #define SETFLAG_EXPORT (1 << 0)
2188 #define SETFLAG_UNEXPORT (1 << 1)
2189 #define SETFLAG_MAKE_RO (1 << 2)
2190 #define SETFLAG_VARLVL_SHIFT 3
2191 static int set_local_var(char *str, unsigned flags)
2193 struct variable **cur_pp;
2194 struct variable *cur;
2195 char *free_me = NULL;
2198 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
2200 eq_sign = strchr(str, '=');
2201 if (HUSH_DEBUG && !eq_sign)
2202 bb_error_msg_and_die("BUG in setvar");
2204 name_len = eq_sign - str + 1; /* including '=' */
2205 cur_pp = &G.top_var;
2206 while ((cur = *cur_pp) != NULL) {
2207 if (strncmp(cur->varstr, str, name_len) != 0) {
2208 cur_pp = &cur->next;
2212 /* We found an existing var with this name */
2213 if (cur->flg_read_only) {
2214 bb_error_msg("%s: readonly variable", str);
2216 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2217 //but export per se succeeds (does put the var in env). We don't mimic that.
2220 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2221 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2226 if (cur->var_nest_level < local_lvl) {
2227 /* bash 3.2.33(1) and exported vars:
2229 * # f() { local z=a; env | grep ^z; }
2235 if (cur->flg_export)
2236 flags |= SETFLAG_EXPORT;
2237 /* New variable is local ("local VAR=VAL" or
2239 * and existing one is global, or local
2240 * on a lower level that new one.
2241 * Remove it from global variable list:
2243 *cur_pp = cur->next;
2244 if (G.shadowed_vars_pp) {
2245 /* Save in "shadowed" list */
2246 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2247 cur->flg_export ? "exported " : "",
2248 cur->varstr, cur->var_nest_level, str, local_lvl
2250 cur->next = *G.shadowed_vars_pp;
2251 *G.shadowed_vars_pp = cur;
2253 /* Came from pseudo_exec_argv(), no need to save: delete it */
2254 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2255 cur->flg_export ? "exported " : "",
2256 cur->varstr, cur->var_nest_level, str, local_lvl
2258 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2259 free_me = cur->varstr; /* then free it later */
2265 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2266 debug_printf_env("assignement '%s' does not change anything\n", str);
2272 /* Replace the value in the found "struct variable" */
2273 if (cur->max_len != 0) {
2274 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
2275 /* This one is from startup env, reuse space */
2276 debug_printf_env("reusing startup env for '%s'\n", str);
2277 strcpy(cur->varstr, str);
2282 goto set_str_and_exp;
2284 /* max_len == 0 signifies "malloced" var, which we can
2285 * (and have to) free. But we can't free(cur->varstr) here:
2286 * if cur->flg_export is 1, it is in the environment.
2287 * We should either unsetenv+free, or wait until putenv,
2288 * then putenv(new)+free(old).
2290 free_me = cur->varstr;
2291 goto set_str_and_exp;
2294 /* Not found or shadowed - create new variable struct */
2295 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
2296 cur = xzalloc(sizeof(*cur));
2297 cur->var_nest_level = local_lvl;
2298 cur->next = *cur_pp;
2304 #if !BB_MMU || ENABLE_HUSH_READONLY
2305 if (flags & SETFLAG_MAKE_RO) {
2306 cur->flg_read_only = 1;
2309 if (flags & SETFLAG_EXPORT)
2310 cur->flg_export = 1;
2311 if (cur->flg_export) {
2312 if (flags & SETFLAG_UNEXPORT) {
2313 cur->flg_export = 0;
2314 /* unsetenv was already done */
2317 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
2318 i = putenv(cur->varstr);
2319 /* only now we can free old exported malloced string */
2326 handle_changed_special_names(cur->varstr, name_len - 1);
2331 /* Used at startup and after each cd */
2332 static void set_pwd_var(unsigned flag)
2334 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2337 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2338 static int unset_local_var_len(const char *name, int name_len)
2340 struct variable *cur;
2341 struct variable **cur_pp;
2343 cur_pp = &G.top_var;
2344 while ((cur = *cur_pp) != NULL) {
2345 if (strncmp(cur->varstr, name, name_len) == 0
2346 && cur->varstr[name_len] == '='
2348 if (cur->flg_read_only) {
2349 bb_error_msg("%s: readonly variable", name);
2350 return EXIT_FAILURE;
2353 *cur_pp = cur->next;
2354 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2355 bb_unsetenv(cur->varstr);
2362 cur_pp = &cur->next;
2365 /* Handle "unset PS1" et al even if did not find the variable to unset */
2366 handle_changed_special_names(name, name_len);
2368 return EXIT_SUCCESS;
2371 static int unset_local_var(const char *name)
2373 return unset_local_var_len(name, strlen(name));
2377 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2378 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
2379 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2381 char *var = xasprintf("%s=%s", name, val);
2382 set_local_var(var, /*flag:*/ 0);
2388 * Helpers for "var1=val1 var2=val2 cmd" feature
2390 static void add_vars(struct variable *var)
2392 struct variable *next;
2396 var->next = G.top_var;
2398 if (var->flg_export) {
2399 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2400 putenv(var->varstr);
2402 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2408 /* We put strings[i] into variable table and possibly putenv them.
2409 * If variable is read only, we can free the strings[i]
2410 * which attempts to overwrite it.
2411 * The strings[] vector itself is freed.
2413 static void set_vars_and_save_old(char **strings)
2422 struct variable *var_p;
2423 struct variable **var_pp;
2426 eq = strchr(*s, '=');
2427 if (HUSH_DEBUG && !eq)
2428 bb_error_msg_and_die("BUG in varexp4");
2429 var_pp = get_ptr_to_local_var(*s, eq - *s);
2432 if (var_p->flg_read_only) {
2434 bb_error_msg("%s: readonly variable", *s);
2436 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2437 * If VAR is readonly, leaving it in the list
2438 * after asssignment error (msg above)
2439 * causes doubled error message later, on unset.
2441 debug_printf_env("removing/freeing '%s' element\n", *s);
2444 do { *p = p[1]; p++; } while (*p);
2447 /* below, set_local_var() with nest level will
2448 * "shadow" (remove) this variable from
2449 * global linked list.
2452 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2453 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2464 static void reinit_unicode_for_hush(void)
2466 /* Unicode support should be activated even if LANG is set
2467 * _during_ shell execution, not only if it was set when
2468 * shell was started. Therefore, re-check LANG every time:
2470 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2471 || ENABLE_UNICODE_USING_LOCALE
2473 const char *s = get_local_var_value("LC_ALL");
2474 if (!s) s = get_local_var_value("LC_CTYPE");
2475 if (!s) s = get_local_var_value("LANG");
2481 * in_str support (strings, and "strings" read from files).
2484 #if ENABLE_HUSH_INTERACTIVE
2485 /* To test correct lineedit/interactive behavior, type from command line:
2491 * It exercises a lot of corner cases.
2493 # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2494 static void cmdedit_update_prompt(void)
2496 G.PS1 = get_local_var_value("PS1");
2499 G.PS2 = get_local_var_value("PS2");
2504 static const char *setup_prompt_string(void)
2506 const char *prompt_str;
2508 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
2510 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2511 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
2512 if (G.promptmode == 0) { /* PS1 */
2513 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2514 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2516 /* bash uses $PWD value, even if it is set by user.
2517 * It uses current dir only if PWD is unset.
2518 * We always use current dir. */
2519 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2523 debug_printf("prompt_str '%s'\n", prompt_str);
2526 static int get_user_input(struct in_str *i)
2529 const char *prompt_str;
2531 prompt_str = setup_prompt_string();
2532 # if ENABLE_FEATURE_EDITING
2534 reinit_unicode_for_hush();
2535 if (G.flag_SIGINT) {
2536 /* There was ^C'ed, make it look prettier: */
2540 /* buglet: SIGINT will not make new prompt to appear _at once_,
2541 * only after <Enter>. (^C works immediately) */
2542 r = read_line_input(G.line_input_state, prompt_str,
2543 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2545 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2548 check_and_run_traps();
2549 if (r != 0 && !G.flag_SIGINT)
2551 /* ^C or SIGINT: repeat */
2552 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2553 write(STDOUT_FILENO, "^C", 2);
2554 G.last_exitcode = 128 + SIGINT;
2557 /* EOF/error detected */
2559 i->peek_buf[0] = r = EOF;
2562 i->p = G.user_input_buf;
2563 return (unsigned char)*i->p++;
2567 if (i->last_char == '\0' || i->last_char == '\n') {
2568 /* Why check_and_run_traps here? Try this interactively:
2569 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2570 * $ <[enter], repeatedly...>
2571 * Without check_and_run_traps, handler never runs.
2573 check_and_run_traps();
2574 fputs(prompt_str, stdout);
2577 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2579 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2580 * no ^C masking happens during fgetc, no special code for ^C:
2581 * it generates SIGINT as usual.
2583 check_and_run_traps();
2585 G.last_exitcode = 128 + SIGINT;
2592 /* This is the magic location that prints prompts
2593 * and gets data back from the user */
2594 static int fgetc_interactive(struct in_str *i)
2597 /* If it's interactive stdin, get new line. */
2598 if (G_interactive_fd && i->file == stdin) {
2599 /* Returns first char (or EOF), the rest is in i->p[] */
2600 ch = get_user_input(i);
2601 G.promptmode = 1; /* PS2 */
2602 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
2604 /* Not stdin: script file, sourced file, etc */
2605 do ch = fgetc(i->file); while (ch == '\0');
2610 static inline int fgetc_interactive(struct in_str *i)
2613 do ch = fgetc(i->file); while (ch == '\0');
2616 #endif /* INTERACTIVE */
2618 static int i_getch(struct in_str *i)
2623 /* string-based in_str */
2624 ch = (unsigned char)*i->p;
2633 /* FILE-based in_str */
2635 #if ENABLE_FEATURE_EDITING
2636 /* This can be stdin, check line editing char[] buffer */
2637 if (i->p && *i->p != '\0') {
2638 ch = (unsigned char)*i->p++;
2642 /* peek_buf[] is an int array, not char. Can contain EOF. */
2643 ch = i->peek_buf[0];
2645 int ch2 = i->peek_buf[1];
2646 i->peek_buf[0] = ch2;
2647 if (ch2 == 0) /* very likely, avoid redundant write */
2653 ch = fgetc_interactive(i);
2655 debug_printf("file_get: got '%c' %d\n", ch, ch);
2657 #if ENABLE_HUSH_LINENO_VAR
2660 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2666 static int i_peek(struct in_str *i)
2671 /* string-based in_str */
2672 /* Doesn't report EOF on NUL. None of the callers care. */
2673 return (unsigned char)*i->p;
2676 /* FILE-based in_str */
2678 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2679 /* This can be stdin, check line editing char[] buffer */
2680 if (i->p && *i->p != '\0')
2681 return (unsigned char)*i->p;
2683 /* peek_buf[] is an int array, not char. Can contain EOF. */
2684 ch = i->peek_buf[0];
2688 /* Need to get a new char */
2689 ch = fgetc_interactive(i);
2690 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2692 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2693 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2699 i->peek_buf[0] = ch;
2700 /*i->peek_buf[1] = 0; - already is */
2704 /* Only ever called if i_peek() was called, and did not return EOF.
2705 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2706 * not end-of-line. Therefore we never need to read a new editing line here.
2708 static int i_peek2(struct in_str *i)
2712 /* There are two cases when i->p[] buffer exists.
2713 * (1) it's a string in_str.
2714 * (2) It's a file, and we have a saved line editing buffer.
2715 * In both cases, we know that i->p[0] exists and not NUL, and
2716 * the peek2 result is in i->p[1].
2719 return (unsigned char)i->p[1];
2721 /* Now we know it is a file-based in_str. */
2723 /* peek_buf[] is an int array, not char. Can contain EOF. */
2724 /* Is there 2nd char? */
2725 ch = i->peek_buf[1];
2727 /* We did not read it yet, get it now */
2728 do ch = fgetc(i->file); while (ch == '\0');
2729 i->peek_buf[1] = ch;
2732 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2736 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2741 ch = i_getch(input);
2744 ch2 = i_peek(input);
2747 /* backslash+newline, skip it */
2752 /* Note: this function _eats_ \<newline> pairs, safe to use plain
2753 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2755 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2763 ch2 = i_peek2(input);
2766 /* backslash+newline, skip it */
2772 static void setup_file_in_str(struct in_str *i, FILE *f)
2774 memset(i, 0, sizeof(*i));
2779 static void setup_string_in_str(struct in_str *i, const char *s)
2781 memset(i, 0, sizeof(*i));
2782 /*i->file = NULL */;
2790 #define B_CHUNK (32 * sizeof(char*))
2792 static void o_reset_to_empty_unquoted(o_string *o)
2795 o->has_quoted_part = 0;
2800 static void o_free_and_set_NULL(o_string *o)
2803 memset(o, 0, sizeof(*o));
2806 static ALWAYS_INLINE void o_free(o_string *o)
2811 static void o_grow_by(o_string *o, int len)
2813 if (o->length + len > o->maxlen) {
2814 o->maxlen += (2 * len) | (B_CHUNK-1);
2815 o->data = xrealloc(o->data, 1 + o->maxlen);
2819 static void o_addchr(o_string *o, int ch)
2821 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2822 if (o->length < o->maxlen) {
2823 /* likely. avoid o_grow_by() call */
2825 o->data[o->length] = ch;
2827 o->data[o->length] = '\0';
2835 /* Valid only if we know o_string is not empty */
2836 static void o_delchr(o_string *o)
2839 o->data[o->length] = '\0';
2843 static void o_addblock(o_string *o, const char *str, int len)
2846 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2850 static void o_addstr(o_string *o, const char *str)
2852 o_addblock(o, str, strlen(str));
2856 static void nommu_addchr(o_string *o, int ch)
2862 # define nommu_addchr(o, str) ((void)0)
2865 static void o_addstr_with_NUL(o_string *o, const char *str)
2867 o_addblock(o, str, strlen(str) + 1);
2871 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2872 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2873 * Apparently, on unquoted $v bash still does globbing
2874 * ("v='*.txt'; echo $v" prints all .txt files),
2875 * but NOT brace expansion! Thus, there should be TWO independent
2876 * quoting mechanisms on $v expansion side: one protects
2877 * $v from brace expansion, and other additionally protects "$v" against globbing.
2878 * We have only second one.
2881 #if ENABLE_HUSH_BRACE_EXPANSION
2882 # define MAYBE_BRACES "{}"
2884 # define MAYBE_BRACES ""
2887 /* My analysis of quoting semantics tells me that state information
2888 * is associated with a destination, not a source.
2890 static void o_addqchr(o_string *o, int ch)
2893 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2898 o->data[o->length] = '\\';
2901 o->data[o->length] = ch;
2903 o->data[o->length] = '\0';
2906 static void o_addQchr(o_string *o, int ch)
2909 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2910 && strchr("*?[\\" MAYBE_BRACES, ch)
2913 o->data[o->length] = '\\';
2917 o->data[o->length] = ch;
2919 o->data[o->length] = '\0';
2922 static void o_addqblock(o_string *o, const char *str, int len)
2927 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2928 if (ordinary_cnt > len) /* paranoia */
2930 o_addblock(o, str, ordinary_cnt);
2931 if (ordinary_cnt == len)
2932 return; /* NUL is already added by o_addblock */
2933 str += ordinary_cnt;
2934 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2938 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2940 o->data[o->length] = '\\';
2944 o->data[o->length] = ch;
2947 o->data[o->length] = '\0';
2950 static void o_addQblock(o_string *o, const char *str, int len)
2952 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2953 o_addblock(o, str, len);
2956 o_addqblock(o, str, len);
2959 static void o_addQstr(o_string *o, const char *str)
2961 o_addQblock(o, str, strlen(str));
2964 /* A special kind of o_string for $VAR and `cmd` expansion.
2965 * It contains char* list[] at the beginning, which is grown in 16 element
2966 * increments. Actual string data starts at the next multiple of 16 * (char*).
2967 * list[i] contains an INDEX (int!) into this string data.
2968 * It means that if list[] needs to grow, data needs to be moved higher up
2969 * but list[i]'s need not be modified.
2970 * NB: remembering how many list[i]'s you have there is crucial.
2971 * o_finalize_list() operation post-processes this structure - calculates
2972 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2974 #if DEBUG_EXPAND || DEBUG_GLOB
2975 static void debug_print_list(const char *prefix, o_string *o, int n)
2977 char **list = (char**)o->data;
2978 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2982 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2983 prefix, list, n, string_start, o->length, o->maxlen,
2984 !!(o->o_expflags & EXP_FLAG_GLOB),
2986 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2989 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2990 o->data + (int)(uintptr_t)list[i] + string_start,
2991 o->data + (int)(uintptr_t)list[i] + string_start);
2995 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2997 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
3001 # define debug_print_list(prefix, o, n) ((void)0)
3004 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3005 * in list[n] so that it points past last stored byte so far.
3006 * It returns n+1. */
3007 static int o_save_ptr_helper(o_string *o, int n)
3009 char **list = (char**)o->data;
3013 if (!o->has_empty_slot) {
3014 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3015 string_len = o->length - string_start;
3016 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
3017 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
3018 /* list[n] points to string_start, make space for 16 more pointers */
3019 o->maxlen += 0x10 * sizeof(list[0]);
3020 o->data = xrealloc(o->data, o->maxlen + 1);
3021 list = (char**)o->data;
3022 memmove(list + n + 0x10, list + n, string_len);
3023 o->length += 0x10 * sizeof(list[0]);
3025 debug_printf_list("list[%d]=%d string_start=%d\n",
3026 n, string_len, string_start);
3029 /* We have empty slot at list[n], reuse without growth */
3030 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3031 string_len = o->length - string_start;
3032 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3033 n, string_len, string_start);
3034 o->has_empty_slot = 0;
3036 o->has_quoted_part = 0;
3037 list[n] = (char*)(uintptr_t)string_len;
3041 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
3042 static int o_get_last_ptr(o_string *o, int n)
3044 char **list = (char**)o->data;
3045 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3047 return ((int)(uintptr_t)list[n-1]) + string_start;
3050 #if ENABLE_HUSH_BRACE_EXPANSION
3051 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
3052 * first, it processes even {a} (no commas), second,
3053 * I didn't manage to make it return strings when they don't match
3054 * existing files. Need to re-implement it.
3058 static int glob_needed(const char *s)
3067 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3073 /* Return pointer to next closing brace or to comma */
3074 static const char *next_brace_sub(const char *cp)
3078 while (*cp != '\0') {
3085 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3091 return *cp != '\0' ? cp : NULL;
3093 /* Recursive brace globber. Note: may garble pattern[]. */
3094 static int glob_brace(char *pattern, o_string *o, int n)
3096 char *new_pattern_buf;
3103 debug_printf_glob("glob_brace('%s')\n", pattern);
3109 if (*begin == '{') {
3110 /* Find the first sub-pattern and at the same time
3111 * find the rest after the closing brace */
3112 next = next_brace_sub(begin);
3114 /* An illegal expression */
3118 /* "{abc}" with no commas - illegal
3119 * brace expr, disregard and skip it */
3125 if (*begin == '\\' && begin[1] != '\0')
3129 debug_printf_glob("begin:%s\n", begin);
3130 debug_printf_glob("next:%s\n", next);
3132 /* Now find the end of the whole brace expression */
3134 while (*rest != '}') {
3135 rest = next_brace_sub(rest);
3137 /* An illegal expression */
3140 debug_printf_glob("rest:%s\n", rest);
3142 rest_len = strlen(++rest) + 1;
3144 /* We are sure the brace expression is well-formed */
3146 /* Allocate working buffer large enough for our work */
3147 new_pattern_buf = xmalloc(strlen(pattern));
3149 /* We have a brace expression. BEGIN points to the opening {,
3150 * NEXT points past the terminator of the first element, and REST
3151 * points past the final }. We will accumulate result names from
3152 * recursive runs for each brace alternative in the buffer using
3157 /* Construct the new glob expression */
3160 mempcpy(new_pattern_buf,
3161 /* We know the prefix for all sub-patterns */
3162 pattern, begin - pattern),
3166 /* Note: glob_brace() may garble new_pattern_buf[].
3167 * That's why we re-copy prefix every time (1st memcpy above).
3169 n = glob_brace(new_pattern_buf, o, n);
3171 /* We saw the last entry */
3175 next = next_brace_sub(next);
3177 free(new_pattern_buf);
3185 memset(&globdata, 0, sizeof(globdata));
3186 gr = glob(pattern, 0, NULL, &globdata);
3187 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3189 if (gr == GLOB_NOMATCH) {
3190 globfree(&globdata);
3191 /* NB: garbles parameter */
3192 unbackslash(pattern);
3193 o_addstr_with_NUL(o, pattern);
3194 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3195 return o_save_ptr_helper(o, n);
3197 if (gr == GLOB_NOSPACE)
3198 bb_die_memory_exhausted();
3199 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3200 * but we didn't specify it. Paranoia again. */
3201 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3203 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3204 char **argv = globdata.gl_pathv;
3206 o_addstr_with_NUL(o, *argv);
3207 n = o_save_ptr_helper(o, n);
3213 globfree(&globdata);
3217 /* Performs globbing on last list[],
3218 * saving each result as a new list[].
3220 static int perform_glob(o_string *o, int n)
3222 char *pattern, *copy;
3224 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3226 return o_save_ptr_helper(o, n);
3227 pattern = o->data + o_get_last_ptr(o, n);
3228 debug_printf_glob("glob pattern '%s'\n", pattern);
3229 if (!glob_needed(pattern)) {
3230 /* unbackslash last string in o in place, fix length */
3231 o->length = unbackslash(pattern) - o->data;
3232 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3233 return o_save_ptr_helper(o, n);
3236 copy = xstrdup(pattern);
3237 /* "forget" pattern in o */
3238 o->length = pattern - o->data;
3239 n = glob_brace(copy, o, n);
3242 debug_print_list("perform_glob returning", o, n);
3246 #else /* !HUSH_BRACE_EXPANSION */
3249 static int glob_needed(const char *s)
3258 if (*s == '*' || *s == '[' || *s == '?')
3264 /* Performs globbing on last list[],
3265 * saving each result as a new list[].
3267 static int perform_glob(o_string *o, int n)
3273 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3275 return o_save_ptr_helper(o, n);
3276 pattern = o->data + o_get_last_ptr(o, n);
3277 debug_printf_glob("glob pattern '%s'\n", pattern);
3278 if (!glob_needed(pattern)) {
3280 /* unbackslash last string in o in place, fix length */
3281 o->length = unbackslash(pattern) - o->data;
3282 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3283 return o_save_ptr_helper(o, n);
3286 memset(&globdata, 0, sizeof(globdata));
3287 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3288 * If we glob "*.\*" and don't find anything, we need
3289 * to fall back to using literal "*.*", but GLOB_NOCHECK
3290 * will return "*.\*"!
3292 gr = glob(pattern, 0, NULL, &globdata);
3293 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3295 if (gr == GLOB_NOMATCH) {
3296 globfree(&globdata);
3299 if (gr == GLOB_NOSPACE)
3300 bb_die_memory_exhausted();
3301 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3302 * but we didn't specify it. Paranoia again. */
3303 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3305 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3306 char **argv = globdata.gl_pathv;
3307 /* "forget" pattern in o */
3308 o->length = pattern - o->data;
3310 o_addstr_with_NUL(o, *argv);
3311 n = o_save_ptr_helper(o, n);
3317 globfree(&globdata);
3319 debug_print_list("perform_glob returning", o, n);
3323 #endif /* !HUSH_BRACE_EXPANSION */
3325 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3326 * Otherwise, just finish current list[] and start new */
3327 static int o_save_ptr(o_string *o, int n)
3329 if (o->o_expflags & EXP_FLAG_GLOB) {
3330 /* If o->has_empty_slot, list[n] was already globbed
3331 * (if it was requested back then when it was filled)
3332 * so don't do that again! */
3333 if (!o->has_empty_slot)
3334 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3336 return o_save_ptr_helper(o, n);
3339 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3340 static char **o_finalize_list(o_string *o, int n)
3346 debug_print_list("finalized", o, n);
3347 debug_printf_expand("finalized n:%d\n", n);
3348 list = (char**)o->data;
3349 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3353 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3358 static void free_pipe_list(struct pipe *pi);
3360 /* Returns pi->next - next pipe in the list */
3361 static struct pipe *free_pipe(struct pipe *pi)
3366 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3367 for (i = 0; i < pi->num_cmds; i++) {
3368 struct command *command;
3369 struct redir_struct *r, *rnext;
3371 command = &pi->cmds[i];
3372 debug_printf_clean(" command %d:\n", i);
3373 if (command->argv) {
3377 for (a = 0, p = command->argv; *p; a++, p++) {
3378 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3381 free_strings(command->argv);
3382 //command->argv = NULL;
3384 /* not "else if": on syntax error, we may have both! */
3385 if (command->group) {
3386 debug_printf_clean(" begin group (cmd_type:%d)\n",
3388 free_pipe_list(command->group);
3389 debug_printf_clean(" end group\n");
3390 //command->group = NULL;
3392 /* else is crucial here.
3393 * If group != NULL, child_func is meaningless */
3394 #if ENABLE_HUSH_FUNCTIONS
3395 else if (command->child_func) {
3396 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3397 command->child_func->parent_cmd = NULL;
3401 free(command->group_as_string);
3402 //command->group_as_string = NULL;
3404 for (r = command->redirects; r; r = rnext) {
3405 debug_printf_clean(" redirect %d%s",
3406 r->rd_fd, redir_table[r->rd_type].descrip);
3407 /* guard against the case >$FOO, where foo is unset or blank */
3408 if (r->rd_filename) {
3409 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3410 free(r->rd_filename);
3411 //r->rd_filename = NULL;
3413 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3417 //command->redirects = NULL;
3419 free(pi->cmds); /* children are an array, they get freed all at once */
3423 //pi->cmdtext = NULL;
3431 static void free_pipe_list(struct pipe *pi)
3435 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3437 debug_printf_clean("pipe followup code %d\n", pi->followup);
3443 /*** Parsing routines ***/
3445 #ifndef debug_print_tree
3446 static void debug_print_tree(struct pipe *pi, int lvl)
3448 static const char *const PIPE[] = {
3454 static const char *RES[] = {
3455 [RES_NONE ] = "NONE" ,
3458 [RES_THEN ] = "THEN" ,
3459 [RES_ELIF ] = "ELIF" ,
3460 [RES_ELSE ] = "ELSE" ,
3463 # if ENABLE_HUSH_LOOPS
3464 [RES_FOR ] = "FOR" ,
3465 [RES_WHILE] = "WHILE",
3466 [RES_UNTIL] = "UNTIL",
3468 [RES_DONE ] = "DONE" ,
3470 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3473 # if ENABLE_HUSH_CASE
3474 [RES_CASE ] = "CASE" ,
3475 [RES_CASE_IN ] = "CASE_IN" ,
3476 [RES_MATCH] = "MATCH",
3477 [RES_CASE_BODY] = "CASE_BODY",
3478 [RES_ESAC ] = "ESAC" ,
3480 [RES_XXXX ] = "XXXX" ,
3481 [RES_SNTX ] = "SNTX" ,
3483 static const char *const CMDTYPE[] = {
3487 # if ENABLE_HUSH_FUNCTIONS
3496 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3499 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3501 pi->followup, PIPE[pi->followup]
3504 while (prn < pi->num_cmds) {
3505 struct command *command = &pi->cmds[prn];
3506 char **argv = command->argv;
3508 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3510 command->assignment_cnt);
3511 #if ENABLE_HUSH_LINENO_VAR
3512 fdprintf(2, " LINENO:%u", command->lineno);
3514 if (command->group) {
3515 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3516 CMDTYPE[command->cmd_type],
3519 , " group_as_string:", command->group_as_string
3524 debug_print_tree(command->group, lvl+1);
3528 if (argv) while (*argv) {
3529 fdprintf(2, " '%s'", *argv);
3539 #endif /* debug_print_tree */
3541 static struct pipe *new_pipe(void)
3544 pi = xzalloc(sizeof(struct pipe));
3545 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3549 /* Command (member of a pipe) is complete, or we start a new pipe
3550 * if ctx->command is NULL.
3551 * No errors possible here.
3553 static int done_command(struct parse_context *ctx)
3555 /* The command is really already in the pipe structure, so
3556 * advance the pipe counter and make a new, null command. */
3557 struct pipe *pi = ctx->pipe;
3558 struct command *command = ctx->command;
3560 #if 0 /* Instead we emit error message at run time */
3561 if (ctx->pending_redirect) {
3562 /* For example, "cmd >" (no filename to redirect to) */
3563 syntax_error("invalid redirect");
3564 ctx->pending_redirect = NULL;
3569 if (IS_NULL_CMD(command)) {
3570 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3574 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3575 //debug_print_tree(ctx->list_head, 20);
3577 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3580 /* Only real trickiness here is that the uncommitted
3581 * command structure is not counted in pi->num_cmds. */
3582 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3583 ctx->command = command = &pi->cmds[pi->num_cmds];
3585 memset(command, 0, sizeof(*command));
3586 #if ENABLE_HUSH_LINENO_VAR
3587 command->lineno = G.lineno;
3588 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
3590 return pi->num_cmds; /* used only for 0/nonzero check */
3593 static void done_pipe(struct parse_context *ctx, pipe_style type)
3597 debug_printf_parse("done_pipe entered, followup %d\n", type);
3598 /* Close previous command */
3599 not_null = done_command(ctx);
3601 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3602 ctx->ctx_inverted = 0;
3603 ctx->pipe->res_word = ctx->ctx_res_w;
3605 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3606 /* Necessary since && and || have precedence over &:
3607 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3608 * in a backgrounded subshell.
3611 struct command *command;
3613 /* Is this actually this construct, all pipes end with && or ||? */
3614 pi = ctx->list_head;
3615 while (pi != ctx->pipe) {
3616 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3621 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3622 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3623 pi = xzalloc(sizeof(*pi));
3624 pi->followup = PIPE_BG;
3626 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3627 command = &pi->cmds[0];
3628 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3629 command->cmd_type = CMD_NORMAL;
3630 command->group = ctx->list_head;
3632 command->group_as_string = xstrndup(
3633 ctx->as_string.data,
3634 ctx->as_string.length - 1 /* do not copy last char, "&" */
3637 /* Replace all pipes in ctx with one newly created */
3638 ctx->list_head = ctx->pipe = pi;
3641 ctx->pipe->followup = type;
3644 /* Without this check, even just <enter> on command line generates
3645 * tree of three NOPs (!). Which is harmless but annoying.
3646 * IOW: it is safe to do it unconditionally. */
3649 || ctx->ctx_res_w == RES_FI
3651 #if ENABLE_HUSH_LOOPS
3652 || ctx->ctx_res_w == RES_DONE
3653 || ctx->ctx_res_w == RES_FOR
3654 || ctx->ctx_res_w == RES_IN
3656 #if ENABLE_HUSH_CASE
3657 || ctx->ctx_res_w == RES_ESAC
3661 debug_printf_parse("done_pipe: adding new pipe: "
3662 "not_null:%d ctx->ctx_res_w:%d\n",
3663 not_null, ctx->ctx_res_w);
3665 ctx->pipe->next = new_p;
3667 /* RES_THEN, RES_DO etc are "sticky" -
3668 * they remain set for pipes inside if/while.
3669 * This is used to control execution.
3670 * RES_FOR and RES_IN are NOT sticky (needed to support
3671 * cases where variable or value happens to match a keyword):
3673 #if ENABLE_HUSH_LOOPS
3674 if (ctx->ctx_res_w == RES_FOR
3675 || ctx->ctx_res_w == RES_IN)
3676 ctx->ctx_res_w = RES_NONE;
3678 #if ENABLE_HUSH_CASE
3679 if (ctx->ctx_res_w == RES_MATCH)
3680 ctx->ctx_res_w = RES_CASE_BODY;
3681 if (ctx->ctx_res_w == RES_CASE)
3682 ctx->ctx_res_w = RES_CASE_IN;
3684 ctx->command = NULL; /* trick done_command below */
3685 /* Create the memory for command, roughly:
3686 * ctx->pipe->cmds = new struct command;
3687 * ctx->command = &ctx->pipe->cmds[0];
3690 //debug_print_tree(ctx->list_head, 10);
3692 debug_printf_parse("done_pipe return\n");
3695 static void initialize_context(struct parse_context *ctx)
3697 memset(ctx, 0, sizeof(*ctx));
3698 if (MAYBE_ASSIGNMENT != 0)
3699 ctx->is_assignment = MAYBE_ASSIGNMENT;
3700 ctx->pipe = ctx->list_head = new_pipe();
3701 /* Create the memory for command, roughly:
3702 * ctx->pipe->cmds = new struct command;
3703 * ctx->command = &ctx->pipe->cmds[0];
3708 /* If a reserved word is found and processed, parse context is modified
3709 * and 1 is returned.
3712 struct reserved_combo {
3715 unsigned char assignment_flag;
3719 FLAG_END = (1 << RES_NONE ),
3721 FLAG_IF = (1 << RES_IF ),
3722 FLAG_THEN = (1 << RES_THEN ),
3723 FLAG_ELIF = (1 << RES_ELIF ),
3724 FLAG_ELSE = (1 << RES_ELSE ),
3725 FLAG_FI = (1 << RES_FI ),
3727 # if ENABLE_HUSH_LOOPS
3728 FLAG_FOR = (1 << RES_FOR ),
3729 FLAG_WHILE = (1 << RES_WHILE),
3730 FLAG_UNTIL = (1 << RES_UNTIL),
3731 FLAG_DO = (1 << RES_DO ),
3732 FLAG_DONE = (1 << RES_DONE ),
3733 FLAG_IN = (1 << RES_IN ),
3735 # if ENABLE_HUSH_CASE
3736 FLAG_MATCH = (1 << RES_MATCH),
3737 FLAG_ESAC = (1 << RES_ESAC ),
3739 FLAG_START = (1 << RES_XXXX ),
3742 static const struct reserved_combo* match_reserved_word(o_string *word)
3744 /* Mostly a list of accepted follow-up reserved words.
3745 * FLAG_END means we are done with the sequence, and are ready
3746 * to turn the compound list into a command.
3747 * FLAG_START means the word must start a new compound list.
3749 static const struct reserved_combo reserved_list[] = {
3751 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3752 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3753 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3754 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3755 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3756 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3758 # if ENABLE_HUSH_LOOPS
3759 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3760 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3761 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3762 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3763 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3764 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3766 # if ENABLE_HUSH_CASE
3767 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3768 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3771 const struct reserved_combo *r;
3773 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3774 if (strcmp(word->data, r->literal) == 0)
3779 /* Return NULL: not a keyword, else: keyword
3781 static const struct reserved_combo* reserved_word(struct parse_context *ctx)
3783 # if ENABLE_HUSH_CASE
3784 static const struct reserved_combo reserved_match = {
3785 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3788 const struct reserved_combo *r;
3790 if (ctx->word.has_quoted_part)
3792 r = match_reserved_word(&ctx->word);
3794 return r; /* NULL */
3796 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3797 # if ENABLE_HUSH_CASE
3798 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3799 /* "case word IN ..." - IN part starts first MATCH part */
3800 r = &reserved_match;
3803 if (r->flag == 0) { /* '!' */
3804 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3805 syntax_error("! ! command");
3806 ctx->ctx_res_w = RES_SNTX;
3808 ctx->ctx_inverted = 1;
3811 if (r->flag & FLAG_START) {
3812 struct parse_context *old;
3814 old = xmemdup(ctx, sizeof(*ctx));
3815 debug_printf_parse("push stack %p\n", old);
3816 initialize_context(ctx);
3818 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3819 syntax_error_at(ctx->word.data);
3820 ctx->ctx_res_w = RES_SNTX;
3823 /* "{...} fi" is ok. "{...} if" is not
3825 * if { echo foo; } then { echo bar; } fi */
3826 if (ctx->command->group)
3827 done_pipe(ctx, PIPE_SEQ);
3830 ctx->ctx_res_w = r->res;
3831 ctx->old_flag = r->flag;
3832 ctx->is_assignment = r->assignment_flag;
3833 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
3835 if (ctx->old_flag & FLAG_END) {
3836 struct parse_context *old;
3838 done_pipe(ctx, PIPE_SEQ);
3839 debug_printf_parse("pop stack %p\n", ctx->stack);
3841 old->command->group = ctx->list_head;
3842 old->command->cmd_type = CMD_NORMAL;
3844 /* At this point, the compound command's string is in
3845 * ctx->as_string... except for the leading keyword!
3846 * Consider this example: "echo a | if true; then echo a; fi"
3847 * ctx->as_string will contain "true; then echo a; fi",
3848 * with "if " remaining in old->as_string!
3852 int len = old->as_string.length;
3853 /* Concatenate halves */
3854 o_addstr(&old->as_string, ctx->as_string.data);
3855 o_free(&ctx->as_string);
3856 /* Find where leading keyword starts in first half */
3857 str = old->as_string.data + len;
3858 if (str > old->as_string.data)
3859 str--; /* skip whitespace after keyword */
3860 while (str > old->as_string.data && isalpha(str[-1]))
3862 /* Ugh, we're done with this horrid hack */
3863 old->command->group_as_string = xstrdup(str);
3864 debug_printf_parse("pop, remembering as:'%s'\n",
3865 old->command->group_as_string);
3868 *ctx = *old; /* physical copy */
3873 #endif /* HAS_KEYWORDS */
3875 /* Word is complete, look at it and update parsing context.
3876 * Normal return is 0. Syntax errors return 1.
3877 * Note: on return, word is reset, but not o_free'd!
3879 static int done_word(struct parse_context *ctx)
3881 struct command *command = ctx->command;
3883 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3884 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
3885 debug_printf_parse("done_word return 0: true null, ignored\n");
3889 if (ctx->pending_redirect) {
3890 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3891 * only if run as "bash", not "sh" */
3892 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
3894 * If the redirection operator is "<<" or "<<-", the word
3895 * that follows the redirection operator shall be
3896 * subjected to quote removal; it is unspecified whether
3897 * any of the other expansions occur. For the other
3898 * redirection operators, the word that follows the
3899 * redirection operator shall be subjected to tilde
3900 * expansion, parameter expansion, command substitution,
3901 * arithmetic expansion, and quote removal.
3902 * Pathname expansion shall not be performed
3903 * on the word by a non-interactive shell; an interactive
3904 * shell may perform it, but shall do so only when
3905 * the expansion would result in one word."
3907 //bash does not do parameter/command substitution or arithmetic expansion
3908 //for _heredoc_ redirection word: these constructs look for exact eof marker
3912 // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3914 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
3915 /* Cater for >\file case:
3916 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3917 * Same with heredocs:
3918 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3920 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3921 unbackslash(ctx->pending_redirect->rd_filename);
3922 /* Is it <<"HEREDOC"? */
3923 if (ctx->word.has_quoted_part) {
3924 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3927 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
3928 ctx->pending_redirect = NULL;
3931 # if ENABLE_HUSH_CASE
3932 if (ctx->ctx_dsemicolon
3933 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3935 /* already done when ctx_dsemicolon was set to 1: */
3936 /* ctx->ctx_res_w = RES_MATCH; */
3937 ctx->ctx_dsemicolon = 0;
3940 if (!command->argv /* if it's the first word... */
3941 # if ENABLE_HUSH_LOOPS
3942 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3943 && ctx->ctx_res_w != RES_IN
3945 # if ENABLE_HUSH_CASE
3946 && ctx->ctx_res_w != RES_CASE
3949 const struct reserved_combo *reserved;
3950 reserved = reserved_word(ctx);
3951 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
3953 # if ENABLE_HUSH_LINENO_VAR
3957 * If we don't close the pipe _now_, immediately after "do", lineno logic
3958 * sees "cmd" as starting at "do" - i.e., at the previous line.
3961 IF_HUSH_IF(|| reserved->res == RES_THEN)
3962 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3963 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3964 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3966 done_pipe(ctx, PIPE_SEQ);
3969 o_reset_to_empty_unquoted(&ctx->word);
3970 debug_printf_parse("done_word return %d\n",
3971 (ctx->ctx_res_w == RES_SNTX));
3972 return (ctx->ctx_res_w == RES_SNTX);
3974 # if defined(CMD_SINGLEWORD_NOGLOB)
3977 || strcmp(ctx->word.data, "[[") == 0
3979 /* In bash, local/export/readonly are special, args
3980 * are assignments and therefore expansion of them
3981 * should be "one-word" expansion:
3982 * $ export i=`echo 'a b'` # one arg: "i=a b"
3984 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3985 * ls: cannot access i=a: No such file or directory
3986 * ls: cannot access b: No such file or directory
3987 * Note: bash 3.2.33(1) does this only if export word
3988 * itself is not quoted:
3989 * $ export i=`echo 'aaa bbb'`; echo "$i"
3991 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3994 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3995 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3996 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
3998 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4003 #endif /* HAS_KEYWORDS */
4005 if (command->group) {
4006 /* "{ echo foo; } echo bar" - bad */
4007 syntax_error_at(ctx->word.data);
4008 debug_printf_parse("done_word return 1: syntax error, "
4009 "groups and arglists don't mix\n");
4013 /* If this word wasn't an assignment, next ones definitely
4014 * can't be assignments. Even if they look like ones. */
4015 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4016 && ctx->is_assignment != WORD_IS_KEYWORD
4018 ctx->is_assignment = NOT_ASSIGNMENT;
4020 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
4021 command->assignment_cnt++;
4022 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4024 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4025 ctx->is_assignment = MAYBE_ASSIGNMENT;
4027 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4028 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
4029 debug_print_strings("word appended to argv", command->argv);
4032 #if ENABLE_HUSH_LOOPS
4033 if (ctx->ctx_res_w == RES_FOR) {
4034 if (ctx->word.has_quoted_part
4035 || !is_well_formed_var_name(command->argv[0], '\0')
4037 /* bash says just "not a valid identifier" */
4038 syntax_error("not a valid identifier in for");
4041 /* Force FOR to have just one word (variable name) */
4042 /* NB: basically, this makes hush see "for v in ..."
4043 * syntax as if it is "for v; in ...". FOR and IN become
4044 * two pipe structs in parse tree. */
4045 done_pipe(ctx, PIPE_SEQ);
4048 #if ENABLE_HUSH_CASE
4049 /* Force CASE to have just one word */
4050 if (ctx->ctx_res_w == RES_CASE) {
4051 done_pipe(ctx, PIPE_SEQ);
4055 o_reset_to_empty_unquoted(&ctx->word);
4057 debug_printf_parse("done_word return 0\n");
4062 /* Peek ahead in the input to find out if we have a "&n" construct,
4063 * as in "2>&1", that represents duplicating a file descriptor.
4065 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4066 * REDIRFD_SYNTAX_ERR if syntax error,
4067 * REDIRFD_TO_FILE if no & was seen,
4068 * or the number found.
4071 #define parse_redir_right_fd(as_string, input) \
4072 parse_redir_right_fd(input)
4074 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4080 return REDIRFD_TO_FILE;
4082 ch = i_getch(input); /* get the & */
4083 nommu_addchr(as_string, ch);
4086 ch = i_getch(input);
4087 nommu_addchr(as_string, ch);
4088 return REDIRFD_CLOSE;
4092 while (ch != EOF && isdigit(ch)) {
4093 d = d*10 + (ch-'0');
4095 ch = i_getch(input);
4096 nommu_addchr(as_string, ch);
4101 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4103 bb_error_msg("ambiguous redirect");
4104 return REDIRFD_SYNTAX_ERR;
4107 /* Return code is 0 normal, 1 if a syntax error is detected
4109 static int parse_redirect(struct parse_context *ctx,
4112 struct in_str *input)
4114 struct command *command = ctx->command;
4115 struct redir_struct *redir;
4116 struct redir_struct **redirp;
4119 dup_num = REDIRFD_TO_FILE;
4120 if (style != REDIRECT_HEREDOC) {
4121 /* Check for a '>&1' type redirect */
4122 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4123 if (dup_num == REDIRFD_SYNTAX_ERR)
4126 int ch = i_peek_and_eat_bkslash_nl(input);
4127 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4128 if (dup_num) { /* <<-... */
4129 ch = i_getch(input);
4130 nommu_addchr(&ctx->as_string, ch);
4135 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4136 int ch = i_peek_and_eat_bkslash_nl(input);
4138 /* >|FILE redirect ("clobbering" >).
4139 * Since we do not support "set -o noclobber" yet,
4140 * >| and > are the same for now. Just eat |.
4142 ch = i_getch(input);
4143 nommu_addchr(&ctx->as_string, ch);
4147 /* Create a new redir_struct and append it to the linked list */
4148 redirp = &command->redirects;
4149 while ((redir = *redirp) != NULL) {
4150 redirp = &(redir->next);
4152 *redirp = redir = xzalloc(sizeof(*redir));
4153 /* redir->next = NULL; */
4154 /* redir->rd_filename = NULL; */
4155 redir->rd_type = style;
4156 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4158 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4159 redir_table[style].descrip);
4161 redir->rd_dup = dup_num;
4162 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4163 /* Erik had a check here that the file descriptor in question
4164 * is legit; I postpone that to "run time"
4165 * A "-" representation of "close me" shows up as a -3 here */
4166 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4167 redir->rd_fd, redir->rd_dup);
4169 #if 0 /* Instead we emit error message at run time */
4170 if (ctx->pending_redirect) {
4171 /* For example, "cmd > <file" */
4172 syntax_error("invalid redirect");
4175 /* Set ctx->pending_redirect, so we know what to do at the
4176 * end of the next parsed word. */
4177 ctx->pending_redirect = redir;
4182 /* If a redirect is immediately preceded by a number, that number is
4183 * supposed to tell which file descriptor to redirect. This routine
4184 * looks for such preceding numbers. In an ideal world this routine
4185 * needs to handle all the following classes of redirects...
4186 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4187 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4188 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4189 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4191 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4193 * ... If n is quoted, the number shall not be recognized as part of
4194 * the redirection expression. For example:
4196 * writes the character 2 into file a"
4197 * We are getting it right by setting ->has_quoted_part on any \<char>
4199 * A -1 return means no valid number was found,
4200 * the caller should use the appropriate default for this redirection.
4202 static int redirect_opt_num(o_string *o)
4206 if (o->data == NULL)
4208 num = bb_strtou(o->data, NULL, 10);
4209 if (errno || num < 0)
4211 o_reset_to_empty_unquoted(o);
4216 #define fetch_till_str(as_string, input, word, skip_tabs) \
4217 fetch_till_str(input, word, skip_tabs)
4219 static char *fetch_till_str(o_string *as_string,
4220 struct in_str *input,
4224 o_string heredoc = NULL_O_STRING;
4226 int prev = 0; /* not \ */
4229 /* Starting with "" is necessary for this case:
4235 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4240 ch = i_getch(input);
4242 nommu_addchr(as_string, ch);
4243 if (ch == '\n' || ch == EOF) {
4245 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4246 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4247 heredoc.data[past_EOL] = '\0';
4248 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4249 return heredoc.data;
4252 /* This is a new line.
4253 * Remember position and backslash-escaping status.
4255 o_addchr(&heredoc, ch);
4258 past_EOL = heredoc.length;
4259 /* Get 1st char of next line, possibly skipping leading tabs */
4261 ch = i_getch(input);
4263 nommu_addchr(as_string, ch);
4264 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4265 /* If this immediately ended the line,
4266 * go back to end-of-line checks.
4269 goto check_heredoc_end;
4277 o_addchr(&heredoc, ch);
4278 nommu_addchr(as_string, ch);
4279 if (prev == '\\' && ch == '\\')
4280 /* Correctly handle foo\\<eol> (not a line cont.) */
4281 prev = 0; /* not \ */
4287 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4288 * and load them all. There should be exactly heredoc_cnt of them.
4290 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4292 struct pipe *pi = ctx->list_head;
4294 while (pi && heredoc_cnt) {
4296 struct command *cmd = pi->cmds;
4298 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4300 cmd->argv ? cmd->argv[0] : "NONE");
4301 for (i = 0; i < pi->num_cmds; i++) {
4302 struct redir_struct *redir = cmd->redirects;
4304 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4305 i, cmd->argv ? cmd->argv[0] : "NONE");
4307 if (redir->rd_type == REDIRECT_HEREDOC) {
4310 redir->rd_type = REDIRECT_HEREDOC2;
4311 /* redir->rd_dup is (ab)used to indicate <<- */
4312 p = fetch_till_str(&ctx->as_string, input,
4313 redir->rd_filename, redir->rd_dup);
4315 syntax_error("unexpected EOF in here document");
4318 free(redir->rd_filename);
4319 redir->rd_filename = p;
4322 redir = redir->next;
4329 /* Should be 0. If it isn't, it's a parse error */
4331 bb_error_msg_and_die("heredoc BUG 2");
4337 static int run_list(struct pipe *pi);
4339 #define parse_stream(pstring, input, end_trigger) \
4340 parse_stream(input, end_trigger)
4342 static struct pipe *parse_stream(char **pstring,
4343 struct in_str *input,
4347 static int parse_group(struct parse_context *ctx,
4348 struct in_str *input, int ch)
4350 /* ctx->word contains characters seen prior to ( or {.
4351 * Typically it's empty, but for function defs,
4352 * it contains function name (without '()'). */
4354 # define as_string NULL
4356 char *as_string = NULL;
4358 struct pipe *pipe_list;
4360 struct command *command = ctx->command;
4362 debug_printf_parse("parse_group entered\n");
4363 #if ENABLE_HUSH_FUNCTIONS
4364 if (ch == '(' && !ctx->word.has_quoted_part) {
4365 if (ctx->word.length)
4369 goto skip; /* (... */
4370 if (command->argv[1]) { /* word word ... (... */
4371 syntax_error_unexpected_ch('(');
4374 /* it is "word(..." or "word (..." */
4376 ch = i_getch(input);
4377 while (ch == ' ' || ch == '\t');
4379 syntax_error_unexpected_ch(ch);
4382 nommu_addchr(&ctx->as_string, ch);
4384 ch = i_getch(input);
4385 while (ch == ' ' || ch == '\t' || ch == '\n');
4386 if (ch != '{' && ch != '(') {
4387 syntax_error_unexpected_ch(ch);
4390 nommu_addchr(&ctx->as_string, ch);
4391 command->cmd_type = CMD_FUNCDEF;
4396 #if 0 /* Prevented by caller */
4397 if (command->argv /* word [word]{... */
4398 || ctx->word.length /* word{... */
4399 || ctx->word.has_quoted_part /* ""{... */
4402 debug_printf_parse("parse_group return 1: "
4403 "syntax error, groups and arglists don't mix\n");
4408 IF_HUSH_FUNCTIONS(skip:)
4413 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4414 command->cmd_type = CMD_SUBSHELL;
4416 /* bash does not allow "{echo...", requires whitespace */
4418 if (ch != ' ' && ch != '\t' && ch != '\n'
4419 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4421 syntax_error_unexpected_ch(ch);
4425 ch = i_getch(input);
4426 nommu_addchr(&ctx->as_string, ch);
4430 pipe_list = parse_stream(&as_string, input, endch);
4433 o_addstr(&ctx->as_string, as_string);
4436 /* empty ()/{} or parse error? */
4437 if (!pipe_list || pipe_list == ERR_PTR) {
4438 /* parse_stream already emitted error msg */
4441 debug_printf_parse("parse_group return 1: "
4442 "parse_stream returned %p\n", pipe_list);
4446 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4447 command->group_as_string = as_string;
4448 debug_printf_parse("end of group, remembering as:'%s'\n",
4449 command->group_as_string);
4452 #if ENABLE_HUSH_FUNCTIONS
4453 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4454 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4455 struct command *cmd2;
4457 cmd2 = xzalloc(sizeof(*cmd2));
4458 cmd2->cmd_type = CMD_SUBSHELL;
4459 cmd2->group = pipe_list;
4462 cmd2->group_as_string = command->group_as_string;
4463 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4466 pipe_list = new_pipe();
4467 pipe_list->cmds = cmd2;
4468 pipe_list->num_cmds = 1;
4472 command->group = pipe_list;
4474 debug_printf_parse("parse_group return 0\n");
4476 /* command remains "open", available for possible redirects */
4480 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4481 /* Subroutines for copying $(...) and `...` things */
4483 static int add_till_single_quote(o_string *dest, struct in_str *input)
4486 int ch = i_getch(input);
4488 syntax_error_unterm_ch('\'');
4496 static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4499 int ch = i_getch(input);
4501 syntax_error_unterm_ch('\'');
4506 o_addqchr(dest, ch);
4509 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4510 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4511 static int add_till_double_quote(o_string *dest, struct in_str *input)
4514 int ch = i_getch(input);
4516 syntax_error_unterm_ch('"');
4521 if (ch == '\\') { /* \x. Copy both chars. */
4523 ch = i_getch(input);
4527 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4532 //if (ch == '$') ...
4535 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4537 * "Within the backquoted style of command substitution, backslash
4538 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4539 * The search for the matching backquote shall be satisfied by the first
4540 * backquote found without a preceding backslash; during this search,
4541 * if a non-escaped backquote is encountered within a shell comment,
4542 * a here-document, an embedded command substitution of the $(command)
4543 * form, or a quoted string, undefined results occur. A single-quoted
4544 * or double-quoted string that begins, but does not end, within the
4545 * "`...`" sequence produces undefined results."
4547 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4549 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4552 int ch = i_getch(input);
4556 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4557 ch = i_getch(input);
4561 && (!in_dquote || ch != '"')
4563 o_addchr(dest, '\\');
4567 syntax_error_unterm_ch('`');
4573 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4574 * quoting and nested ()s.
4575 * "With the $(command) style of command substitution, all characters
4576 * following the open parenthesis to the matching closing parenthesis
4577 * constitute the command. Any valid shell script can be used for command,
4578 * except a script consisting solely of redirections which produces
4579 * unspecified results."
4581 * echo $(echo '(TEST)' BEST) (TEST) BEST
4582 * echo $(echo 'TEST)' BEST) TEST) BEST
4583 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4585 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4586 * can contain arbitrary constructs, just like $(cmd).
4587 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4588 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4590 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4591 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4594 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4595 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4596 char end_char2 = end_ch >> 8;
4598 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4600 #if ENABLE_HUSH_INTERACTIVE
4601 G.promptmode = 1; /* PS2 */
4603 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4606 ch = i_getch(input);
4608 syntax_error_unterm_ch(end_ch);
4612 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4618 /* we look for closing )) of $((EXPR)) */
4619 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4620 i_getch(input); /* eat second ')' */
4625 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
4626 if (ch == '(' || ch == '{') {
4627 ch = (ch == '(' ? ')' : '}');
4628 if (!add_till_closing_bracket(dest, input, ch))
4634 if (!add_till_single_quote(dest, input))
4640 if (!add_till_double_quote(dest, input))
4646 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4652 /* \x. Copy verbatim. Important for \(, \) */
4653 ch = i_getch(input);
4655 syntax_error_unterm_ch(end_ch);
4660 /* "backslash+newline", ignore both */
4661 o_delchr(dest); /* undo insertion of '\' */
4666 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
4670 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
4673 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4675 /* Return code: 0 for OK, 1 for syntax error */
4677 #define parse_dollar(as_string, dest, input, quote_mask) \
4678 parse_dollar(dest, input, quote_mask)
4679 #define as_string NULL
4681 static int parse_dollar(o_string *as_string,
4683 struct in_str *input, unsigned char quote_mask)
4685 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4687 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4690 ch = i_getch(input);
4691 nommu_addchr(as_string, ch);
4693 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4695 debug_printf_parse(": '%c'\n", ch);
4696 o_addchr(dest, ch | quote_mask);
4698 ch = i_peek_and_eat_bkslash_nl(input);
4699 if (!isalnum(ch) && ch != '_') {
4700 /* End of variable name reached */
4703 ch = i_getch(input);
4704 nommu_addchr(as_string, ch);
4706 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4707 } else if (isdigit(ch)) {
4709 ch = i_getch(input);
4710 nommu_addchr(as_string, ch);
4711 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4712 debug_printf_parse(": '%c'\n", ch);
4713 o_addchr(dest, ch | quote_mask);
4714 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4715 } else switch (ch) {
4717 case '!': /* last bg pid */
4718 case '?': /* last exit code */
4719 case '#': /* number of args */
4720 case '*': /* args */
4721 case '@': /* args */
4722 goto make_one_char_var;
4726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4728 ch = i_getch(input); /* eat '{' */
4729 nommu_addchr(as_string, ch);
4731 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4732 /* It should be ${?}, or ${#var},
4733 * or even ${?+subst} - operator acting on a special variable,
4734 * or the beginning of variable name.
4737 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4740 syntax_error_unterm_str("${name}");
4741 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4744 nommu_addchr(as_string, ch);
4748 /* It's possible to just call add_till_closing_bracket() at this point.
4749 * However, this regresses some of our testsuite cases
4750 * which check invalid constructs like ${%}.
4751 * Oh well... let's check that the var name part is fine... */
4757 debug_printf_parse(": '%c'\n", ch);
4759 ch = i_getch(input);
4760 nommu_addchr(as_string, ch);
4764 if (!isalnum(ch) && ch != '_') {
4766 unsigned char last_ch;
4767 /* handle parameter expansions
4768 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4770 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4771 if (len_single_ch != '#'
4772 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4773 || i_peek(input) != '}'
4775 goto bad_dollar_syntax;
4777 /* else: it's "length of C" ${#C} op,
4778 * where C is a single char
4779 * special var name, e.g. ${#!}.
4782 /* Eat everything until closing '}' (or ':') */
4786 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4788 /* It's ${var:N[:M]} thing */
4789 end_ch = '}' * 0x100 + ':';
4791 if (BASH_PATTERN_SUBST
4794 /* It's ${var/[/]pattern[/repl]} thing */
4795 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4797 nommu_addchr(as_string, '/');
4800 end_ch = '}' * 0x100 + '/';
4806 #if ENABLE_HUSH_DOLLAR_OPS
4807 last_ch = add_till_closing_bracket(dest, input, end_ch);
4808 if (last_ch == 0) /* error? */
4811 #error Simple code to only allow ${var} is not implemented
4814 o_addstr(as_string, dest->data + pos);
4815 o_addchr(as_string, last_ch);
4818 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4819 && (end_ch & 0xff00)
4821 /* close the first block: */
4822 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4823 /* while parsing N from ${var:N[:M]}
4824 * or pattern from ${var/[/]pattern[/repl]} */
4825 if ((end_ch & 0xff) == last_ch) {
4826 /* got ':' or '/'- parse the rest */
4831 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4832 /* it's ${var:N} - emulate :999999999 */
4833 o_addstr(dest, "999999999");
4834 } /* else: it's ${var/[/]pattern} */
4838 len_single_ch = 0; /* it can't be ${#C} op */
4840 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4843 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4847 ch = i_getch(input);
4848 nommu_addchr(as_string, ch);
4849 # if ENABLE_FEATURE_SH_MATH
4850 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4851 ch = i_getch(input);
4852 nommu_addchr(as_string, ch);
4853 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4854 o_addchr(dest, /*quote_mask |*/ '+');
4857 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4858 return 0; /* error */
4860 o_addstr(as_string, dest->data + pos);
4861 o_addchr(as_string, ')');
4862 o_addchr(as_string, ')');
4864 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4868 # if ENABLE_HUSH_TICK
4869 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4870 o_addchr(dest, quote_mask | '`');
4873 if (!add_till_closing_bracket(dest, input, ')'))
4874 return 0; /* error */
4876 o_addstr(as_string, dest->data + pos);
4877 o_addchr(as_string, ')');
4879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4887 /* TODO: $_ and $-: */
4888 /* $_ Shell or shell script name; or last argument of last command
4889 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4890 * but in command's env, set to full pathname used to invoke it */
4891 /* $- Option flags set by set builtin or shell options (-i etc) */
4892 ch = i_getch(input);
4893 nommu_addchr(as_string, ch);
4894 ch = i_peek_and_eat_bkslash_nl(input);
4895 if (isalnum(ch)) { /* it's $_name or $_123 */
4902 o_addQchr(dest, '$');
4904 debug_printf_parse("parse_dollar return 1 (ok)\n");
4910 #define encode_string(as_string, dest, input, dquote_end) \
4911 encode_string(dest, input, dquote_end)
4912 #define as_string NULL
4914 static int encode_string(o_string *as_string,
4916 struct in_str *input,
4923 ch = i_getch(input);
4925 nommu_addchr(as_string, ch);
4926 if (ch == dquote_end) { /* may be only '"' or EOF */
4927 debug_printf_parse("encode_string return 1 (ok)\n");
4930 /* note: can't move it above ch == dquote_end check! */
4932 syntax_error_unterm_ch('"');
4933 return 0; /* error */
4937 next = i_peek(input);
4939 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4940 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4943 /* Testcase: in interactive shell a file with
4944 * echo "unterminated string\<eof>
4947 syntax_error_unterm_ch('"');
4948 return 0; /* error */
4951 * "The backslash retains its special meaning [in "..."]
4952 * only when followed by one of the following characters:
4953 * $, `, ", \, or <newline>. A double quote may be quoted
4954 * within double quotes by preceding it with a backslash."
4955 * NB: in (unquoted) heredoc, above does not apply to ",
4956 * therefore we check for it by "next == dquote_end" cond.
4958 if (next == dquote_end || strchr("$`\\\n", next)) {
4959 ch = i_getch(input); /* eat next */
4961 goto again; /* skip \<newline> */
4962 } /* else: ch remains == '\\', and we double it below: */
4963 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4964 nommu_addchr(as_string, ch);
4968 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4969 debug_printf_parse("encode_string return 0: "
4970 "parse_dollar returned 0 (error)\n");
4975 #if ENABLE_HUSH_TICK
4977 //unsigned pos = dest->length;
4978 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4979 o_addchr(dest, 0x80 | '`');
4980 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4981 return 0; /* error */
4982 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4983 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4987 o_addQchr(dest, ch);
4993 * Scan input until EOF or end_trigger char.
4994 * Return a list of pipes to execute, or NULL on EOF
4995 * or if end_trigger character is met.
4996 * On syntax error, exit if shell is not interactive,
4997 * reset parsing machinery and start parsing anew,
4998 * or return ERR_PTR.
5000 static struct pipe *parse_stream(char **pstring,
5001 struct in_str *input,
5004 struct parse_context ctx;
5007 /* Single-quote triggers a bypass of the main loop until its mate is
5008 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
5010 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5011 end_trigger ? end_trigger : 'X');
5014 initialize_context(&ctx);
5016 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5019 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
5021 /* We used to separate words on $IFS here. This was wrong.
5022 * $IFS is used only for word splitting when $var is expanded,
5023 * here we should use blank chars as separators, not $IFS
5028 const char *is_blank;
5029 const char *is_special;
5033 redir_type redir_style;
5035 ch = i_getch(input);
5036 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5037 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5042 syntax_error_unterm_str("here document");
5045 if (end_trigger == ')') {
5046 syntax_error_unterm_ch('(');
5049 if (end_trigger == '}') {
5050 syntax_error_unterm_ch('{');
5054 if (done_word(&ctx)) {
5057 o_free_and_set_NULL(&ctx.word);
5058 done_pipe(&ctx, PIPE_SEQ);
5060 /* If we got nothing... */
5061 /* (this makes bare "&" cmd a no-op.
5062 * bash says: "syntax error near unexpected token '&'") */
5063 if (pi->num_cmds == 0
5064 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
5070 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
5072 *pstring = ctx.as_string.data;
5074 o_free(&ctx.as_string);
5077 debug_printf_parse("parse_stream return %p\n", pi);
5081 /* Handle "'" and "\" first, as they won't play nice with
5082 * i_peek_and_eat_bkslash_nl() anyway:
5090 ch = i_getch(input);
5092 continue; /* drop \<newline>, get next char */
5093 nommu_addchr(&ctx.as_string, '\\');
5094 o_addchr(&ctx.word, '\\');
5096 /* Testcase: eval 'echo Ok\' */
5097 /* bash-4.3.43 was removing backslash,
5098 * but 4.4.19 retains it, most other shells too
5100 continue; /* get next char */
5102 /* Example: echo Hello \2>file
5103 * we need to know that word 2 is quoted
5105 ctx.word.has_quoted_part = 1;
5106 nommu_addchr(&ctx.as_string, ch);
5107 o_addchr(&ctx.word, ch);
5108 continue; /* get next char */
5110 nommu_addchr(&ctx.as_string, ch);
5112 ctx.word.has_quoted_part = 1;
5113 next = i_getch(input);
5114 if (next == '\'' && !ctx.pending_redirect)
5115 goto insert_empty_quoted_str_marker;
5120 syntax_error_unterm_ch('\'');
5123 nommu_addchr(&ctx.as_string, ch);
5126 if (ch == SPECIAL_VAR_SYMBOL) {
5127 /* Convert raw ^C to corresponding special variable reference */
5128 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5129 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5131 o_addqchr(&ctx.word, ch);
5132 ch = i_getch(input);
5134 continue; /* get next char */
5139 next = i_peek_and_eat_bkslash_nl(input);
5141 is_special = "{}<>;&|()#" /* special outside of "str" */
5142 "$\"" IF_HUSH_TICK("`") /* always special */
5143 SPECIAL_VAR_SYMBOL_STR;
5144 /* Are { and } special here? */
5145 if (ctx.command->argv /* word [word]{... - non-special */
5146 || ctx.word.length /* word{... - non-special */
5147 || ctx.word.has_quoted_part /* ""{... - non-special */
5148 || (next != ';' /* }; - special */
5149 && next != ')' /* }) - special */
5150 && next != '(' /* {( - special */
5151 && next != '&' /* }& and }&& ... - special */
5152 && next != '|' /* }|| ... - special */
5153 && !strchr(defifs, next) /* {word - non-special */
5156 /* They are not special, skip "{}" */
5159 is_special = strchr(is_special, ch);
5160 is_blank = strchr(defifs, ch);
5162 if (!is_special && !is_blank) { /* ordinary char */
5164 o_addQchr(&ctx.word, ch);
5165 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5166 || ctx.is_assignment == WORD_IS_KEYWORD)
5168 && is_well_formed_var_name(ctx.word.data, '=')
5170 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5171 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5177 #if ENABLE_HUSH_LINENO_VAR
5179 * "while ...; do<whitespace><newline>
5181 * would think that "cmd" starts in <whitespace> -
5182 * i.e., at the previous line.
5183 * We need to skip all whitespace before newlines.
5185 while (ch != '\n') {
5186 next = i_peek(input);
5187 if (next != ' ' && next != '\t' && next != '\n')
5188 break; /* next char is not ws */
5189 ch = i_getch(input);
5191 /* ch == last eaten whitespace char */
5193 if (done_word(&ctx)) {
5197 /* Is this a case when newline is simply ignored?
5199 * "cmd | <newline> cmd ..."
5200 * "case ... in <newline> word) ..."
5202 if (IS_NULL_CMD(ctx.command)
5203 && ctx.word.length == 0 && !ctx.word.has_quoted_part
5205 /* This newline can be ignored. But...
5206 * Without check #1, interactive shell
5207 * ignores even bare <newline>,
5208 * and shows the continuation prompt:
5209 * ps1_prompt$ <enter>
5210 * ps2> _ <=== wrong, should be ps1
5211 * Without check #2, "cmd & <newline>"
5212 * is similarly mistreated.
5213 * (BTW, this makes "cmd & cmd"
5214 * and "cmd && cmd" non-orthogonal.
5215 * Really, ask yourself, why
5216 * "cmd && <newline>" doesn't start
5217 * cmd but waits for more input?
5218 * The only reason is that it might be
5219 * a "cmd1 && <nl> cmd2 &" construct,
5220 * cmd1 may need to run in BG).
5222 struct pipe *pi = ctx.list_head;
5223 if (pi->num_cmds != 0 /* check #1 */
5224 && pi->followup != PIPE_BG /* check #2 */
5229 /* Treat newline as a command separator. */
5230 done_pipe(&ctx, PIPE_SEQ);
5231 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5233 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5238 ctx.is_assignment = MAYBE_ASSIGNMENT;
5239 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5241 /* note: if (is_blank) continue;
5242 * will still trigger for us */
5246 /* "cmd}" or "cmd }..." without semicolon or &:
5247 * } is an ordinary char in this case, even inside { cmd; }
5248 * Pathological example: { ""}; } should exec "}" cmd
5251 if (ctx.word.length != 0 /* word} */
5252 || ctx.word.has_quoted_part /* ""} */
5256 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5257 /* Generally, there should be semicolon: "cmd; }"
5258 * However, bash allows to omit it if "cmd" is
5259 * a group. Examples:
5262 * { echo 0 >&2 | { echo 1; } }
5263 * { while false; do :; done }
5264 * { case a in b) ;; esac }
5266 if (ctx.command->group)
5270 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5271 /* Can't be an end of {cmd}, skip the check */
5272 goto skip_end_trigger;
5273 /* else: } does terminate a group */
5276 if (end_trigger && end_trigger == ch
5277 && (ch != ';' || heredoc_cnt == 0)
5278 #if ENABLE_HUSH_CASE
5280 || ctx.ctx_res_w != RES_MATCH
5281 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
5286 /* This is technically valid:
5287 * { cat <<HERE; }; echo Ok
5291 * but we don't support this.
5292 * We require heredoc to be in enclosing {}/(),
5295 syntax_error_unterm_str("here document");
5298 if (done_word(&ctx)) {
5301 done_pipe(&ctx, PIPE_SEQ);
5302 ctx.is_assignment = MAYBE_ASSIGNMENT;
5303 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5304 /* Do we sit outside of any if's, loops or case's? */
5306 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5308 o_free_and_set_NULL(&ctx.word);
5310 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5312 *pstring = ctx.as_string.data;
5314 o_free(&ctx.as_string);
5316 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5317 /* Example: bare "{ }", "()" */
5318 G.last_exitcode = 2; /* bash compat */
5319 syntax_error_unexpected_ch(ch);
5322 debug_printf_parse("parse_stream return %p: "
5323 "end_trigger char found\n",
5326 return ctx.list_head;
5333 /* Catch <, > before deciding whether this word is
5334 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5337 redir_fd = redirect_opt_num(&ctx.word);
5338 if (done_word(&ctx)) {
5341 redir_style = REDIRECT_OVERWRITE;
5343 redir_style = REDIRECT_APPEND;
5344 ch = i_getch(input);
5345 nommu_addchr(&ctx.as_string, ch);
5348 else if (next == '(') {
5349 syntax_error(">(process) not supported");
5353 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5355 continue; /* get next char */
5357 redir_fd = redirect_opt_num(&ctx.word);
5358 if (done_word(&ctx)) {
5361 redir_style = REDIRECT_INPUT;
5363 redir_style = REDIRECT_HEREDOC;
5365 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5366 ch = i_getch(input);
5367 nommu_addchr(&ctx.as_string, ch);
5368 } else if (next == '>') {
5369 redir_style = REDIRECT_IO;
5370 ch = i_getch(input);
5371 nommu_addchr(&ctx.as_string, ch);
5374 else if (next == '(') {
5375 syntax_error("<(process) not supported");
5379 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5381 continue; /* get next char */
5383 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
5384 /* skip "#comment" */
5385 /* note: we do not add it to &ctx.as_string */
5387 * comment inside $() goes to the next \n, even inside quoted string (!):
5388 * cmd "$(cmd2 #comment)" - syntax error
5389 * cmd "`cmd2 #comment`" - ok
5390 * We accept both (comment ends where command subst ends, in both cases).
5395 nommu_addchr(&ctx.as_string, '\n');
5398 ch = i_getch(input);
5402 continue; /* get next char */
5408 if (ctx.is_assignment == MAYBE_ASSIGNMENT
5409 /* check that we are not in word in "a=1 2>word b=1": */
5410 && !ctx.pending_redirect
5412 /* ch is a special char and thus this word
5413 * cannot be an assignment */
5414 ctx.is_assignment = NOT_ASSIGNMENT;
5415 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5418 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5421 case SPECIAL_VAR_SYMBOL:
5422 /* Convert raw ^C to corresponding special variable reference */
5423 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5424 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5427 /* non-comment #: "echo a#b" etc */
5428 o_addchr(&ctx.word, ch);
5429 continue; /* get next char */
5431 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
5432 debug_printf_parse("parse_stream parse error: "
5433 "parse_dollar returned 0 (error)\n");
5436 continue; /* get next char */
5438 ctx.word.has_quoted_part = 1;
5439 if (next == '"' && !ctx.pending_redirect) {
5440 i_getch(input); /* eat second " */
5441 insert_empty_quoted_str_marker:
5442 nommu_addchr(&ctx.as_string, next);
5443 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5444 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5445 continue; /* get next char */
5447 if (ctx.is_assignment == NOT_ASSIGNMENT)
5448 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5449 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
5451 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5452 continue; /* get next char */
5453 #if ENABLE_HUSH_TICK
5455 USE_FOR_NOMMU(unsigned pos;)
5457 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5458 o_addchr(&ctx.word, '`');
5459 USE_FOR_NOMMU(pos = ctx.word.length;)
5460 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
5463 o_addstr(&ctx.as_string, ctx.word.data + pos);
5464 o_addchr(&ctx.as_string, '`');
5466 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5467 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
5468 continue; /* get next char */
5472 #if ENABLE_HUSH_CASE
5475 if (done_word(&ctx)) {
5478 done_pipe(&ctx, PIPE_SEQ);
5479 #if ENABLE_HUSH_CASE
5480 /* Eat multiple semicolons, detect
5481 * whether it means something special */
5483 ch = i_peek_and_eat_bkslash_nl(input);
5486 ch = i_getch(input);
5487 nommu_addchr(&ctx.as_string, ch);
5488 if (ctx.ctx_res_w == RES_CASE_BODY) {
5489 ctx.ctx_dsemicolon = 1;
5490 ctx.ctx_res_w = RES_MATCH;
5496 /* We just finished a cmd. New one may start
5497 * with an assignment */
5498 ctx.is_assignment = MAYBE_ASSIGNMENT;
5499 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5500 continue; /* get next char */
5502 if (done_word(&ctx)) {
5506 ch = i_getch(input);
5507 nommu_addchr(&ctx.as_string, ch);
5508 done_pipe(&ctx, PIPE_AND);
5510 done_pipe(&ctx, PIPE_BG);
5514 if (done_word(&ctx)) {
5517 #if ENABLE_HUSH_CASE
5518 if (ctx.ctx_res_w == RES_MATCH)
5519 break; /* we are in case's "word | word)" */
5521 if (next == '|') { /* || */
5522 ch = i_getch(input);
5523 nommu_addchr(&ctx.as_string, ch);
5524 done_pipe(&ctx, PIPE_OR);
5526 /* we could pick up a file descriptor choice here
5527 * with redirect_opt_num(), but bash doesn't do it.
5528 * "echo foo 2| cat" yields "foo 2". */
5533 #if ENABLE_HUSH_CASE
5534 /* "case... in [(]word)..." - skip '(' */
5535 if (ctx.ctx_res_w == RES_MATCH
5536 && ctx.command->argv == NULL /* not (word|(... */
5537 && ctx.word.length == 0 /* not word(... */
5538 && ctx.word.has_quoted_part == 0 /* not ""(... */
5540 continue; /* get next char */
5544 if (parse_group(&ctx, input, ch) != 0) {
5549 #if ENABLE_HUSH_CASE
5550 if (ctx.ctx_res_w == RES_MATCH)
5554 /* proper use of this character is caught by end_trigger:
5555 * if we see {, we call parse_group(..., end_trigger='}')
5556 * and it will match } earlier (not here). */
5557 G.last_exitcode = 2;
5558 syntax_error_unexpected_ch(ch);
5562 bb_error_msg_and_die("BUG: unexpected %c", ch);
5567 G.last_exitcode = 1;
5570 struct parse_context *pctx;
5571 IF_HAS_KEYWORDS(struct parse_context *p2;)
5573 /* Clean up allocated tree.
5574 * Sample for finding leaks on syntax error recovery path.
5575 * Run it from interactive shell, watch pmap `pidof hush`.
5576 * while if false; then false; fi; do break; fi
5577 * Samples to catch leaks at execution:
5578 * while if (true | { true;}); then echo ok; fi; do break; done
5579 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5583 /* Update pipe/command counts,
5584 * otherwise freeing may miss some */
5585 done_pipe(pctx, PIPE_SEQ);
5586 debug_printf_clean("freeing list %p from ctx %p\n",
5587 pctx->list_head, pctx);
5588 debug_print_tree(pctx->list_head, 0);
5589 free_pipe_list(pctx->list_head);
5590 debug_printf_clean("freed list %p\n", pctx->list_head);
5592 o_free(&pctx->as_string);
5594 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5598 IF_HAS_KEYWORDS(pctx = p2;)
5599 } while (HAS_KEYWORDS && pctx);
5601 o_free_and_set_NULL(&ctx.word);
5612 /*** Execution routines ***/
5614 /* Expansion can recurse, need forward decls: */
5615 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5616 #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
5617 expand_string_to_string(str)
5619 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
5620 #if ENABLE_HUSH_TICK
5621 static int process_command_subs(o_string *dest, const char *s);
5623 static int expand_vars_to_list(o_string *output, int n, char *arg);
5625 /* expand_strvec_to_strvec() takes a list of strings, expands
5626 * all variable references within and returns a pointer to
5627 * a list of expanded strings, possibly with larger number
5628 * of strings. (Think VAR="a b"; echo $VAR).
5629 * This new list is allocated as a single malloc block.
5630 * NULL-terminated list of char* pointers is at the beginning of it,
5631 * followed by strings themselves.
5632 * Caller can deallocate entire list by single free(list). */
5634 /* A horde of its helpers come first: */
5636 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5638 while (--len >= 0) {
5641 #if ENABLE_HUSH_BRACE_EXPANSION
5642 if (c == '{' || c == '}') {
5643 /* { -> \{, } -> \} */
5645 /* And now we want to add { or } and continue:
5648 * luckily, just falling through achieves this.
5654 /* \z -> \\\z; \<eol> -> \\<eol> */
5659 o_addchr(o, *str++);
5665 /* Store given string, finalizing the word and starting new one whenever
5666 * we encounter IFS char(s). This is used for expanding variable values.
5667 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5668 * Return in output->ended_in_ifs:
5669 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5671 static int expand_on_ifs(o_string *output, int n, const char *str)
5673 int last_is_ifs = 0;
5678 if (!*str) /* EOL - do not finalize word */
5680 word_len = strcspn(str, G.ifs);
5682 /* We have WORD_LEN leading non-IFS chars */
5683 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5684 o_addblock(output, str, word_len);
5686 /* Protect backslashes against globbing up :)
5687 * Example: "v='\*'; echo b$v" prints "b\*"
5688 * (and does not try to glob on "*")
5690 o_addblock_duplicate_backslash(output, str, word_len);
5691 /*/ Why can't we do it easier? */
5692 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5693 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5697 if (!*str) /* EOL - do not finalize word */
5701 /* We know str here points to at least one IFS char */
5703 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
5704 if (!*str) /* EOL - do not finalize word */
5707 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5708 && strchr(G.ifs, *str) /* the second check would fail */
5710 /* This is a non-whitespace $IFS char */
5711 /* Skip it and IFS whitespace chars, start new word */
5713 str += strspn(str, G.ifs_whitespace);
5717 /* Start new word... but not always! */
5718 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5719 if (output->has_quoted_part
5720 /* Case "v=' a'; echo $v":
5721 * here nothing precedes the space in $v expansion,
5722 * therefore we should not finish the word
5723 * (IOW: if there *is* word to finalize, only then do it):
5725 || (n > 0 && output->data[output->length - 1])
5728 o_addchr(output, '\0');
5729 debug_print_list("expand_on_ifs", output, n);
5730 n = o_save_ptr(output, n);
5734 output->ended_in_ifs = last_is_ifs;
5735 debug_print_list("expand_on_ifs[1]", output, n);
5739 /* Helper to expand $((...)) and heredoc body. These act as if
5740 * they are in double quotes, with the exception that they are not :).
5741 * Just the rules are similar: "expand only $var and `cmd`"
5743 * Returns malloced string.
5744 * As an optimization, we return NULL if expansion is not needed.
5746 static char *encode_then_expand_string(const char *str)
5749 struct in_str input;
5750 o_string dest = NULL_O_STRING;
5755 if (!*cp) return NULL; /* string has no special chars */
5756 if (*cp == '$') break;
5757 if (*cp == '\\') break;
5758 #if ENABLE_HUSH_TICK
5759 if (*cp == '`') break;
5764 /* We need to expand. Example:
5765 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5767 setup_string_in_str(&input, str);
5768 encode_string(NULL, &dest, &input, EOF);
5769 //TODO: error check (encode_string returns 0 on error)?
5770 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5771 exp_str = expand_string_to_string(dest.data,
5772 EXP_FLAG_ESC_GLOB_CHARS,
5775 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5780 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5781 * These can contain single- and double-quoted strings,
5782 * and treated as if the ARG string is initially unquoted. IOW:
5783 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5784 * a dquoted string: "${var#"zz"}"), the difference only comes later
5785 * (word splitting and globbing of the ${var...} result).
5787 #if !BASH_PATTERN_SUBST
5788 #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5789 encode_then_expand_vararg(str, handle_squotes)
5791 static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5793 #if !BASH_PATTERN_SUBST
5794 const int do_unbackslash = 0;
5797 struct in_str input;
5798 o_string dest = NULL_O_STRING;
5803 if (!*cp) return NULL; /* string has no special chars */
5804 if (*cp == '$') break;
5805 if (*cp == '\\') break;
5806 if (*cp == '\'') break;
5807 if (*cp == '"') break;
5808 #if ENABLE_HUSH_TICK
5809 if (*cp == '`') break;
5814 setup_string_in_str(&input, str);
5815 dest.data = xzalloc(1); /* start as "", not as NULL */
5821 ch = i_getch(&input);
5822 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5823 __func__, ch, ch, !!dest.o_expflags);
5825 if (!dest.o_expflags) {
5828 if (handle_squotes && ch == '\'') {
5829 if (!add_till_single_quote_dquoted(&dest, &input))
5830 goto ret; /* error */
5835 syntax_error_unterm_ch('"');
5836 goto ret; /* error */
5839 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5843 ch = i_getch(&input);
5845 //example? error message? syntax_error_unterm_ch('"');
5846 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5849 o_addqchr(&dest, ch);
5853 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5854 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5859 #if ENABLE_HUSH_TICK
5861 //unsigned pos = dest->length;
5862 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5863 o_addchr(&dest, 0x80 | '`');
5864 if (!add_till_backquote(&dest, &input,
5865 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5868 goto ret; /* error */
5870 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5871 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5875 o_addQchr(&dest, ch);
5878 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5879 exp_str = expand_string_to_string(dest.data,
5880 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5884 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
5889 /* Expanding ARG in ${var+ARG}, ${var-ARG}
5891 static int encode_then_append_var_plusminus(o_string *output, int n,
5892 const char *str, int dquoted)
5894 struct in_str input;
5895 o_string dest = NULL_O_STRING;
5901 if (!*cp) return NULL; /* string has no special chars */
5902 if (*cp == '$') break;
5903 if (*cp == '\\') break;
5904 if (*cp == '\'') break;
5905 if (*cp == '"') break;
5906 #if ENABLE_HUSH_TICK
5907 if (*cp == '`') break;
5913 setup_string_in_str(&input, str);
5918 ch = i_getch(&input);
5919 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
5920 __func__, ch, ch, dest.o_expflags);
5922 if (!dest.o_expflags) {
5925 if (!dquoted && strchr(G.ifs, ch)) {
5926 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
5927 * do not assume we are at the start of the word (PREFIX above).
5930 n = expand_vars_to_list(output, n, dest.data);
5931 o_free_and_set_NULL(&dest);
5932 o_addchr(output, '\0');
5933 n = o_save_ptr(output, n); /* create next word */
5935 if (output->length != o_get_last_ptr(output, n)
5936 || output->has_quoted_part
5939 * f() { for i; do echo "|$i|"; done; }; x=x
5940 * f a${x:+ }b # 1st condition
5943 * f ""${x:+ }b # 2nd condition
5947 o_addchr(output, '\0');
5948 n = o_save_ptr(output, n); /* create next word */
5952 if (!dquoted && ch == '\'') {
5953 if (!add_till_single_quote_dquoted(&dest, &input))
5954 goto ret; /* error */
5955 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5956 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5961 syntax_error_unterm_ch('"');
5962 goto ret; /* error */
5965 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5966 if (dest.o_expflags) {
5967 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5968 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5973 ch = i_getch(&input);
5975 //example? error message? syntax_error_unterm_ch('"');
5976 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5979 o_addqchr(&dest, ch);
5983 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
5984 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5989 #if ENABLE_HUSH_TICK
5991 //unsigned pos = dest->length;
5992 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5993 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
5994 if (!add_till_backquote(&dest, &input,
5995 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5998 goto ret; /* error */
6000 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6001 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6006 /* Always glob-protect if in dquotes:
6007 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6008 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6010 o_addqchr(&dest, ch);
6012 /* Glob-protect only if char is quoted:
6013 * x=x; echo ${x:+/bin/c*} - prints many filenames
6014 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6016 o_addQchr(&dest, ch);
6021 n = expand_vars_to_list(output, n, dest.data);
6028 #if ENABLE_FEATURE_SH_MATH
6029 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
6031 arith_state_t math_state;
6035 math_state.lookupvar = get_local_var_value;
6036 math_state.setvar = set_local_var_from_halves;
6037 //math_state.endofname = endofname;
6038 exp_str = encode_then_expand_string(arg);
6039 res = arith(&math_state, exp_str ? exp_str : arg);
6042 *errmsg_p = math_state.errmsg;
6043 if (math_state.errmsg)
6044 msg_and_die_if_script(math_state.errmsg);
6049 #if BASH_PATTERN_SUBST
6050 /* ${var/[/]pattern[/repl]} helpers */
6051 static char *strstr_pattern(char *val, const char *pattern, int *size)
6054 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6055 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6062 /* Optimization: if "*pat" did not match the start of "string",
6063 * we know that "tring", "ring" etc will not match too:
6065 if (pattern[0] == '*')
6070 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6072 char *result = NULL;
6073 unsigned res_len = 0;
6074 unsigned repl_len = strlen(repl);
6076 /* Null pattern never matches, including if "var" is empty */
6078 return result; /* NULL, no replaces happened */
6082 char *s = strstr_pattern(val, pattern, &size);
6086 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
6087 strcpy(mempcpy(result + res_len, val, s - val), repl);
6088 res_len += (s - val) + repl_len;
6089 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6095 if (*val && result) {
6096 result = xrealloc(result, res_len + strlen(val) + 1);
6097 strcpy(result + res_len, val);
6098 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6100 debug_printf_varexp("result:'%s'\n", result);
6103 #endif /* BASH_PATTERN_SUBST */
6105 static int append_str_maybe_ifs_split(o_string *output, int n,
6106 int first_ch, const char *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));
6112 n = expand_on_ifs(output, n, val);
6113 } else { /* quoted "$VAR" */
6114 output->has_quoted_part = 1;
6115 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6116 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6118 o_addQstr(output, val);
6123 /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6125 static NOINLINE int expand_one_var(o_string *output, int n,
6126 int first_ch, char *arg, char **pp)
6133 char exp_save = exp_save; /* for compiler */
6134 char *exp_saveptr; /* points to expansion operator */
6135 char *exp_word = exp_word; /* for compiler */
6141 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
6143 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
6145 arg[0] = (arg0 & 0x7f);
6148 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
6149 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6150 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6151 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
6153 /* It must be length operator: ${#var} */
6157 /* Maybe handle parameter expansion */
6158 if (exp_saveptr /* if 2nd char is one of expansion operators */
6159 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
6161 /* ${?:0}, ${#[:]%0} etc */
6162 exp_saveptr = var + 1;
6164 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6165 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6167 exp_op = exp_save = *exp_saveptr;
6169 exp_word = exp_saveptr + 1;
6170 if (exp_op == ':') {
6171 exp_op = *exp_word++;
6172 //TODO: try ${var:} and ${var:bogus} in non-bash config
6174 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
6176 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6181 *exp_saveptr = '\0';
6182 } /* else: it's not an expansion op, but bare ${var} */
6185 /* Look up the variable in question */
6186 if (isdigit(var[0])) {
6187 /* parse_dollar should have vetted var for us */
6188 int nn = xatoi_positive(var);
6189 if (nn < G.global_argc)
6190 val = G.global_argv[nn];
6191 /* else val remains NULL: $N with too big N */
6195 val = utoa(G.root_pid);
6197 case '!': /* bg pid */
6198 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6200 case '?': /* exitcode */
6201 val = utoa(G.last_exitcode);
6203 case '#': /* argc */
6204 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6207 val = get_local_var_value(var);
6211 /* Handle any expansions */
6212 if (exp_op == 'L') {
6213 reinit_unicode_for_hush();
6214 debug_printf_expand("expand: length(%s)=", val);
6215 val = utoa(val ? unicode_strlen(val) : 0);
6216 debug_printf_expand("%s\n", val);
6217 } else if (exp_op) {
6218 if (exp_op == '%' || exp_op == '#') {
6219 /* Standard-mandated substring removal ops:
6220 * ${parameter%word} - remove smallest suffix pattern
6221 * ${parameter%%word} - remove largest suffix pattern
6222 * ${parameter#word} - remove smallest prefix pattern
6223 * ${parameter##word} - remove largest prefix pattern
6225 * Word is expanded to produce a glob pattern.
6226 * Then var's value is matched to it and matching part removed.
6228 //FIXME: ${x#...${...}...}
6229 //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6230 //inner ${...} may have side effects!
6231 if (val && val[0]) {
6235 unsigned scan_flags = pick_scan(exp_op, *exp_word);
6236 if (exp_op == *exp_word) /* ## or %% */
6238 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6239 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6241 exp_word = exp_exp_word;
6242 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6244 * HACK ALERT. We depend here on the fact that
6245 * G.global_argv and results of utoa and get_local_var_value
6246 * are actually in writable memory:
6247 * scan_and_match momentarily stores NULs there.
6250 loc = scan_and_match(t, exp_word, scan_flags);
6251 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
6253 if (loc) { /* match was found */
6254 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
6255 val = loc; /* take right part */
6257 val = to_be_freed = xstrndup(val, loc - val); /* left */
6261 #if BASH_PATTERN_SUBST
6262 else if (exp_op == '/' || exp_op == '\\') {
6263 /* It's ${var/[/]pattern[/repl]} thing.
6264 * Note that in encoded form it has TWO parts:
6265 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6266 * and if // is used, it is encoded as \:
6267 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6269 if (val && val[0]) {
6270 /* pattern uses non-standard expansion.
6271 * repl should be unbackslashed and globbed
6272 * by the usual expansion rules:
6274 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6275 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6276 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6277 * v='a bz'; echo ${v/a*z/\z} #prints "z"
6278 * (note that a*z _pattern_ is never globbed!)
6280 char *pattern, *repl, *t;
6281 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6283 pattern = xstrdup(exp_word);
6284 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6285 *p++ = SPECIAL_VAR_SYMBOL;
6287 p = strchr(p, SPECIAL_VAR_SYMBOL);
6289 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
6290 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6291 /* HACK ALERT. We depend here on the fact that
6292 * G.global_argv and results of utoa and get_local_var_value
6293 * are actually in writable memory:
6294 * replace_pattern momentarily stores NULs there. */
6296 to_be_freed = replace_pattern(t,
6298 (repl ? repl : exp_word),
6300 if (to_be_freed) /* at least one replace happened */
6305 /* Empty variable always gives nothing */
6306 // "v=''; echo ${v/*/w}" prints "", not "w"
6307 /* Just skip "replace" part */
6308 *p++ = SPECIAL_VAR_SYMBOL;
6309 p = strchr(p, SPECIAL_VAR_SYMBOL);
6313 #endif /* BASH_PATTERN_SUBST */
6314 else if (exp_op == ':') {
6315 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
6316 /* It's ${var:N[:M]} bashism.
6317 * Note that in encoded form it has TWO parts:
6318 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6323 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6326 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6327 *p++ = SPECIAL_VAR_SYMBOL;
6329 p = strchr(p, SPECIAL_VAR_SYMBOL);
6331 len = expand_and_evaluate_arith(exp_word, &errmsg);
6334 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
6336 /* negative beg counts from the end */
6337 beg = (arith_t)strlen(val) + beg;
6338 if (beg < 0) /* ${v: -999999} is "" */
6341 debug_printf_varexp("from val:'%s'\n", val);
6343 /* in bash, len=-n means strlen()-n */
6344 len = (arith_t)strlen(val) - beg + len;
6345 if (len < 0) /* bash compat */
6346 msg_and_die_if_script("%s: substring expression < 0", var);
6348 if (len <= 0 || !val || beg >= strlen(val)) {
6352 /* Paranoia. What if user entered 9999999999999
6353 * which fits in arith_t but not int? */
6356 val = to_be_freed = xstrndup(val + beg, len);
6358 debug_printf_varexp("val:'%s'\n", val);
6359 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
6360 msg_and_die_if_script("malformed ${%s:...}", var);
6363 } else { /* one of "-=+?" */
6364 /* Standard-mandated substitution ops:
6365 * ${var?word} - indicate error if unset
6366 * If var is unset, word (or a message indicating it is unset
6367 * if word is null) is written to standard error
6368 * and the shell exits with a non-zero exit status.
6369 * Otherwise, the value of var is substituted.
6370 * ${var-word} - use default value
6371 * If var is unset, word is substituted.
6372 * ${var=word} - assign and use default value
6373 * If var is unset, word is assigned to var.
6374 * In all cases, final value of var is substituted.
6375 * ${var+word} - use alternative value
6376 * If var is unset, null is substituted.
6377 * Otherwise, word is substituted.
6379 * Word is subjected to tilde expansion, parameter expansion,
6380 * command substitution, and arithmetic expansion.
6381 * If word is not needed, it is not expanded.
6383 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6384 * but also treat null var as if it is unset.
6386 * Word-splitting and single quote behavior:
6388 * $ f() { for i; do echo "|$i|"; done; };
6390 * $ x=; f ${x:?'x y' z}
6391 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6392 * $ x=; f "${x:?'x y' z}"
6393 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6395 * $ x=; f ${x:='x y' z}
6399 * $ x=; f "${x:='x y' z}"
6402 * $ x=x; f ${x:+'x y' z}
6405 * $ x=x; f "${x:+'x y' z}"
6408 * $ x=; f ${x:-'x y' z}
6411 * $ x=; f "${x:-'x y' z}"
6414 int use_word = (!val || ((exp_save == ':') && !val[0]));
6416 use_word = !use_word;
6417 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6418 (exp_save == ':') ? "true" : "false", use_word);
6420 if (exp_op == '+' || exp_op == '-') {
6421 /* ${var+word} - use alternative value */
6422 /* ${var-word} - use default value */
6423 n = encode_then_append_var_plusminus(output, n, exp_word,
6424 /*dquoted:*/ (arg0 & 0x80)
6428 /* ${var?word} - indicate error if unset */
6429 /* ${var=word} - assign and use default value */
6430 to_be_freed = encode_then_expand_vararg(exp_word,
6431 /*handle_squotes:*/ !(arg0 & 0x80),
6435 exp_word = to_be_freed;
6436 if (exp_op == '?') {
6437 /* mimic bash message */
6438 msg_and_die_if_script("%s: %s",
6442 : "parameter null or not set"
6443 /* ash has more specific messages, a-la: */
6444 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6446 //TODO: how interactive bash aborts expansion mid-command?
6447 //It aborts the entire line, returns to prompt:
6448 // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6451 // ("echo YO" is not executed, neither the f function call)
6455 if (exp_op == '=') {
6456 /* ${var=[word]} or ${var:=[word]} */
6457 if (isdigit(var[0]) || var[0] == '#') {
6458 /* mimic bash message */
6459 msg_and_die_if_script("$%s: cannot assign in this way", var);
6462 char *new_var = xasprintf("%s=%s", var, val);
6463 set_local_var(new_var, /*flag:*/ 0);
6468 } /* one of "-=+?" */
6470 *exp_saveptr = exp_save;
6476 n = append_str_maybe_ifs_split(output, n, first_ch, val);
6482 /* Expand all variable references in given string, adding words to list[]
6483 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6484 * to be filled). This routine is extremely tricky: has to deal with
6485 * variables/parameters with whitespace, $* and $@, and constructs like
6486 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
6487 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
6489 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
6490 * expansion of right-hand side of assignment == 1-element expand.
6492 char cant_be_null = 0; /* only bit 0x80 matters */
6495 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6496 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
6497 debug_print_list("expand_vars_to_list[0]", output, n);
6499 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6501 #if ENABLE_FEATURE_SH_MATH
6502 char arith_buf[sizeof(arith_t)*3 + 2];
6505 if (output->ended_in_ifs) {
6506 o_addchr(output, '\0');
6507 n = o_save_ptr(output, n);
6508 output->ended_in_ifs = 0;
6511 o_addblock(output, arg, p - arg);
6512 debug_print_list("expand_vars_to_list[1]", output, n);
6514 p = strchr(p, SPECIAL_VAR_SYMBOL);
6516 /* Fetch special var name (if it is indeed one of them)
6517 * and quote bit, force the bit on if singleword expansion -
6518 * important for not getting v=$@ expand to many words. */
6519 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6521 /* Is this variable quoted and thus expansion can't be null?
6522 * "$@" is special. Even if quoted, it can still
6523 * expand to nothing (not even an empty string),
6524 * thus it is excluded. */
6525 if ((first_ch & 0x7f) != '@')
6526 cant_be_null |= first_ch;
6528 switch (first_ch & 0x7f) {
6529 /* Highest bit in first_ch indicates that var is double-quoted */
6533 if (!G.global_argv[1])
6536 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6537 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6538 while (G.global_argv[i]) {
6539 n = expand_on_ifs(output, n, G.global_argv[i]);
6540 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6541 if (G.global_argv[i++][0] && G.global_argv[i]) {
6542 /* this argv[] is not empty and not last:
6543 * put terminating NUL, start new word */
6544 o_addchr(output, '\0');
6545 debug_print_list("expand_vars_to_list[2]", output, n);
6546 n = o_save_ptr(output, n);
6547 debug_print_list("expand_vars_to_list[3]", output, n);
6551 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6552 * and in this case should treat it like '$*' - see 'else...' below */
6553 if (first_ch == (char)('@'|0x80) /* quoted $@ */
6554 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6557 o_addQstr(output, G.global_argv[i]);
6558 if (++i >= G.global_argc)
6560 o_addchr(output, '\0');
6561 debug_print_list("expand_vars_to_list[4]", output, n);
6562 n = o_save_ptr(output, n);
6564 } else { /* quoted $* (or v="$@" case): add as one word */
6566 o_addQstr(output, G.global_argv[i]);
6567 if (!G.global_argv[++i])
6570 o_addchr(output, G.ifs[0]);
6572 output->has_quoted_part = 1;
6576 case SPECIAL_VAR_SYMBOL: {
6577 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6578 /* "Empty variable", used to make "" etc to not disappear */
6579 output->has_quoted_part = 1;
6580 cant_be_null = 0x80;
6584 case SPECIAL_VAR_QUOTED_SVS:
6585 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6586 /* "^C variable", represents literal ^C char (possible in scripts) */
6587 o_addchr(output, SPECIAL_VAR_SYMBOL);
6590 #if ENABLE_HUSH_TICK
6592 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6593 o_string subst_result = NULL_O_STRING;
6595 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6597 /* Can't just stuff it into output o_string,
6598 * expanded result may need to be globbed
6600 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6601 G.last_exitcode = process_command_subs(&subst_result, arg);
6602 G.expand_exitcode = G.last_exitcode;
6603 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6604 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
6605 o_free(&subst_result);
6609 #if ENABLE_FEATURE_SH_MATH
6611 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
6614 arg++; /* skip '+' */
6615 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6616 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6617 res = expand_and_evaluate_arith(arg, NULL);
6618 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6619 sprintf(arith_buf, ARITH_FMT, res);
6620 o_addstr(output, arith_buf);
6625 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
6626 n = expand_one_var(output, n, first_ch, arg, &p);
6628 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6630 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6631 * Do the check to avoid writing to a const string. */
6632 if (*p != SPECIAL_VAR_SYMBOL)
6633 *p = SPECIAL_VAR_SYMBOL;
6635 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6638 /* handle trailing string */
6639 if (output->ended_in_ifs) {
6640 o_addchr(output, '\0');
6641 n = o_save_ptr(output, n);
6643 debug_print_list("expand_vars_to_list[a]", output, n);
6644 /* this part is literal, and it was already pre-quoted
6645 * if needed (much earlier), do not use o_addQstr here!
6647 o_addstr(output, arg);
6648 debug_print_list("expand_vars_to_list[b]", output, n);
6650 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6651 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6652 && !output->has_quoted_part
6655 /* allow to reuse list[n] later without re-growth */
6656 output->has_empty_slot = 1;
6662 static char **expand_variables(char **argv, unsigned expflags)
6666 o_string output = NULL_O_STRING;
6668 output.o_expflags = expflags;
6672 /* go to next list[n] */
6673 output.ended_in_ifs = 0;
6674 n = o_save_ptr(&output, n);
6679 /* expand argv[i] */
6680 n = expand_vars_to_list(&output, n, *argv++);
6681 /* if (!output->has_empty_slot) -- need this?? */
6682 o_addchr(&output, '\0');
6684 debug_print_list("expand_variables", &output, n);
6686 /* output.data (malloced in one block) gets returned in "list" */
6687 list = o_finalize_list(&output, n);
6688 debug_print_strings("expand_variables[1]", list);
6692 static char **expand_strvec_to_strvec(char **argv)
6694 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6697 #if defined(CMD_SINGLEWORD_NOGLOB)
6698 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6700 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6704 /* Used for expansion of right hand of assignments,
6705 * $((...)), heredocs, variable expansion parts.
6707 * NB: should NOT do globbing!
6708 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6710 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
6712 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6713 const int do_unbackslash = 1;
6714 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
6716 char *argv[2], **list;
6718 debug_printf_expand("string_to_string<='%s'\n", str);
6719 /* This is generally an optimization, but it also
6720 * handles "", which otherwise trips over !list[0] check below.
6721 * (is this ever happens that we actually get str="" here?)
6723 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6724 //TODO: Can use on strings with \ too, just unbackslash() them?
6725 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6726 return xstrdup(str);
6729 argv[0] = (char*)str;
6731 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
6733 /* Example where it happens:
6734 * x=; echo ${x:-"$@"}
6736 ((char*)list)[0] = '\0';
6740 bb_error_msg_and_die("BUG in varexp2");
6741 /* actually, just move string 2*sizeof(char*) bytes back */
6742 overlapping_strcpy((char*)list, list[0]);
6744 unbackslash((char*)list);
6746 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6751 static char* expand_strvec_to_string(char **argv)
6755 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6756 /* Convert all NULs to spaces */
6761 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6762 bb_error_msg_and_die("BUG in varexp3");
6763 /* bash uses ' ' regardless of $IFS contents */
6768 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6769 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6774 static char **expand_assignments(char **argv, int count)
6779 G.expanded_assignments = p = NULL;
6780 /* Expand assignments into one string each */
6781 for (i = 0; i < count; i++) {
6782 p = add_string_to_strings(p,
6783 expand_string_to_string(argv[i],
6784 EXP_FLAG_ESC_GLOB_CHARS,
6788 G.expanded_assignments = p;
6790 G.expanded_assignments = NULL;
6795 static void switch_off_special_sigs(unsigned mask)
6798 while ((mask >>= 1) != 0) {
6802 #if ENABLE_HUSH_TRAP
6804 if (G_traps[sig] && !G_traps[sig][0])
6805 /* trap is '', has to remain SIG_IGN */
6808 G_traps[sig] = NULL;
6811 /* We are here only if no trap or trap was not '' */
6812 install_sighandler(sig, SIG_DFL);
6818 void re_execute_shell(char ***to_free, const char *s,
6819 char *g_argv0, char **g_argv,
6820 char **builtin_argv) NORETURN;
6822 static void reset_traps_to_defaults(void)
6824 /* This function is always called in a child shell
6825 * after fork (not vfork, NOMMU doesn't use this function).
6827 IF_HUSH_TRAP(unsigned sig;)
6830 /* Child shells are not interactive.
6831 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6832 * Testcase: (while :; do :; done) + ^Z should background.
6833 * Same goes for SIGTERM, SIGHUP, SIGINT.
6835 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6836 if (!G_traps && !mask)
6837 return; /* already no traps and no special sigs */
6839 /* Switch off special sigs */
6840 switch_off_special_sigs(mask);
6841 # if ENABLE_HUSH_JOB
6842 G_fatal_sig_mask = 0;
6844 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6845 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6846 * remain set in G.special_sig_mask */
6848 # if ENABLE_HUSH_TRAP
6852 /* Reset all sigs to default except ones with empty traps */
6853 for (sig = 0; sig < NSIG; sig++) {
6855 continue; /* no trap: nothing to do */
6856 if (!G_traps[sig][0])
6857 continue; /* empty trap: has to remain SIG_IGN */
6858 /* sig has non-empty trap, reset it: */
6860 G_traps[sig] = NULL;
6861 /* There is no signal for trap 0 (EXIT) */
6864 install_sighandler(sig, pick_sighandler(sig));
6871 static void re_execute_shell(char ***to_free, const char *s,
6872 char *g_argv0, char **g_argv,
6873 char **builtin_argv) NORETURN;
6874 static void re_execute_shell(char ***to_free, const char *s,
6875 char *g_argv0, char **g_argv,
6876 char **builtin_argv)
6878 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6879 /* delims + 2 * (number of bytes in printed hex numbers) */
6880 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6881 char *heredoc_argv[4];
6882 struct variable *cur;
6883 # if ENABLE_HUSH_FUNCTIONS
6884 struct function *funcp;
6888 unsigned long long empty_trap_mask;
6890 if (!g_argv0) { /* heredoc */
6891 argv = heredoc_argv;
6892 argv[0] = (char *) G.argv0_for_re_execing;
6893 argv[1] = (char *) "-<";
6894 argv[2] = (char *) s;
6896 pp = &argv[3]; /* used as pointer to empty environment */
6902 if (pp) while (*pp++)
6905 empty_trap_mask = 0;
6908 for (sig = 1; sig < NSIG; sig++) {
6909 if (G_traps[sig] && !G_traps[sig][0])
6910 empty_trap_mask |= 1LL << sig;
6914 sprintf(param_buf, NOMMU_HACK_FMT
6915 , (unsigned) G.root_pid
6916 , (unsigned) G.root_ppid
6917 , (unsigned) G.last_bg_pid
6918 , (unsigned) G.last_exitcode
6921 IF_HUSH_LOOPS(, G.depth_of_loop)
6923 # undef NOMMU_HACK_FMT
6924 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6925 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6928 for (cur = G.top_var; cur; cur = cur->next) {
6929 if (!cur->flg_export || cur->flg_read_only)
6932 # if ENABLE_HUSH_FUNCTIONS
6933 for (funcp = G.top_func; funcp; funcp = funcp->next)
6939 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6940 *pp++ = (char *) G.argv0_for_re_execing;
6942 for (cur = G.top_var; cur; cur = cur->next) {
6943 if (strcmp(cur->varstr, hush_version_str) == 0)
6945 if (cur->flg_read_only) {
6946 *pp++ = (char *) "-R";
6947 *pp++ = cur->varstr;
6948 } else if (!cur->flg_export) {
6949 *pp++ = (char *) "-V";
6950 *pp++ = cur->varstr;
6953 # if ENABLE_HUSH_FUNCTIONS
6954 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6955 *pp++ = (char *) "-F";
6956 *pp++ = funcp->name;
6957 *pp++ = funcp->body_as_string;
6960 /* We can pass activated traps here. Say, -Tnn:trap_string
6962 * However, POSIX says that subshells reset signals with traps
6964 * I tested bash-3.2 and it not only does that with true subshells
6965 * of the form ( list ), but with any forked children shells.
6966 * I set trap "echo W" WINCH; and then tried:
6968 * { echo 1; sleep 20; echo 2; } &
6969 * while true; do echo 1; sleep 20; echo 2; break; done &
6970 * true | { echo 1; sleep 20; echo 2; } | cat
6972 * In all these cases sending SIGWINCH to the child shell
6973 * did not run the trap. If I add trap "echo V" WINCH;
6974 * _inside_ group (just before echo 1), it works.
6976 * I conclude it means we don't need to pass active traps here.
6978 *pp++ = (char *) "-c";
6981 while (*++builtin_argv)
6982 *pp++ = *builtin_argv;
6983 *pp++ = (char *) "";
6988 /* *pp = NULL; - is already there */
6992 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6993 /* Don't propagate SIG_IGN to the child */
6994 if (SPECIAL_JOBSTOP_SIGS != 0)
6995 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6996 execve(bb_busybox_exec_path, argv, pp);
6997 /* Fallback. Useful for init=/bin/hush usage etc */
6998 if (argv[0][0] == '/')
6999 execve(argv[0], argv, pp);
7000 xfunc_error_retval = 127;
7001 bb_error_msg_and_die("can't re-execute the shell");
7003 #endif /* !BB_MMU */
7006 static int run_and_free_list(struct pipe *pi);
7008 /* Executing from string: eval, sh -c '...'
7009 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7010 * end_trigger controls how often we stop parsing
7011 * NUL: parse all, execute, return
7012 * ';': parse till ';' or newline, execute, repeat till EOF
7014 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7016 /* Why we need empty flag?
7017 * An obscure corner case "false; ``; echo $?":
7018 * empty command in `` should still set $? to 0.
7019 * But we can't just set $? to 0 at the start,
7020 * this breaks "false; echo `echo $?`" case.
7024 struct pipe *pipe_list;
7026 #if ENABLE_HUSH_INTERACTIVE
7027 if (end_trigger == ';') {
7028 G.promptmode = 0; /* PS1 */
7029 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7032 pipe_list = parse_stream(NULL, inp, end_trigger);
7033 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7034 /* If we are in "big" script
7035 * (not in `cmd` or something similar)...
7037 if (pipe_list == ERR_PTR && end_trigger == ';') {
7038 /* Discard cached input (rest of line) */
7039 int ch = inp->last_char;
7040 while (ch != EOF && ch != '\n') {
7041 //bb_error_msg("Discarded:'%c'", ch);
7046 /* This stream isn't empty */
7050 if (!pipe_list && empty)
7051 G.last_exitcode = 0;
7054 debug_print_tree(pipe_list, 0);
7055 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7056 run_and_free_list(pipe_list);
7058 if (G_flag_return_in_progress == 1)
7063 static void parse_and_run_string(const char *s)
7065 struct in_str input;
7066 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7068 setup_string_in_str(&input, s);
7069 parse_and_run_stream(&input, '\0');
7070 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
7073 static void parse_and_run_file(FILE *f)
7075 struct in_str input;
7076 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7078 IF_HUSH_LINENO_VAR(G.lineno = 1;)
7079 setup_file_in_str(&input, f);
7080 parse_and_run_stream(&input, ';');
7081 IF_HUSH_LINENO_VAR(G.lineno = sv;)
7084 #if ENABLE_HUSH_TICK
7085 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
7090 char **to_free = NULL;
7094 pid = BB_MMU ? xfork() : xvfork();
7095 if (pid == 0) { /* child */
7096 disable_restore_tty_pgrp_on_exit();
7097 /* Process substitution is not considered to be usual
7098 * 'command execution'.
7099 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7106 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7107 close(channel[0]); /* NB: close _first_, then move fd! */
7108 xmove_fd(channel[1], 1);
7109 /* Prevent it from trying to handle ctrl-z etc */
7110 IF_HUSH_JOB(G.run_list_level = 1;)
7111 # if ENABLE_HUSH_TRAP
7112 /* Awful hack for `trap` or $(trap).
7114 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7115 * contains an example where "trap" is executed in a subshell:
7117 * save_traps=$(trap)
7119 * eval "$save_traps"
7121 * Standard does not say that "trap" in subshell shall print
7122 * parent shell's traps. It only says that its output
7123 * must have suitable form, but then, in the above example
7124 * (which is not supposed to be normative), it implies that.
7126 * bash (and probably other shell) does implement it
7127 * (traps are reset to defaults, but "trap" still shows them),
7128 * but as a result, "trap" logic is hopelessly messed up:
7131 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7132 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7133 * # true | trap <--- trap is in subshell - no output (ditto)
7134 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7135 * trap -- 'echo Ho' SIGWINCH
7136 * # echo `(trap)` <--- in subshell in subshell - output
7137 * trap -- 'echo Ho' SIGWINCH
7138 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7139 * trap -- 'echo Ho' SIGWINCH
7141 * The rules when to forget and when to not forget traps
7142 * get really complex and nonsensical.
7144 * Our solution: ONLY bare $(trap) or `trap` is special.
7146 s = skip_whitespace(s);
7147 if (is_prefixed_with(s, "trap")
7148 && skip_whitespace(s + 4)[0] == '\0'
7150 static const char *const argv[] = { NULL, NULL };
7151 builtin_trap((char**)argv);
7152 fflush_all(); /* important */
7157 reset_traps_to_defaults();
7158 parse_and_run_string(s);
7159 _exit(G.last_exitcode);
7161 /* We re-execute after vfork on NOMMU. This makes this script safe:
7162 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7163 * huge=`cat BIG` # was blocking here forever
7166 re_execute_shell(&to_free,
7176 # if ENABLE_HUSH_FAST
7178 //bb_error_msg("[%d] fork in generate_stream_from_string:"
7179 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7180 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7182 enable_restore_tty_pgrp_on_exit();
7187 return remember_FILE(xfdopen_for_read(channel[0]));
7190 /* Return code is exit status of the process that is run. */
7191 static int process_command_subs(o_string *dest, const char *s)
7195 int status, ch, eol_cnt;
7197 fp = generate_stream_from_string(s, &pid);
7199 /* Now send results of command back into original context */
7201 while ((ch = getc(fp)) != EOF) {
7209 o_addchr(dest, '\n');
7212 o_addQchr(dest, ch);
7215 debug_printf("done reading from `cmd` pipe, closing it\n");
7216 fclose_and_forget(fp);
7217 /* We need to extract exitcode. Test case
7218 * "true; echo `sleep 1; false` $?"
7220 safe_waitpid(pid, &status, 0);
7221 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7222 return WEXITSTATUS(status);
7224 #endif /* ENABLE_HUSH_TICK */
7227 static void setup_heredoc(struct redir_struct *redir)
7229 struct fd_pair pair;
7232 /* the _body_ of heredoc (misleading field name) */
7233 const char *heredoc = redir->rd_filename;
7240 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
7241 expanded = encode_then_expand_string(heredoc);
7245 len = strlen(heredoc);
7247 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7249 xmove_fd(pair.rd, redir->rd_fd);
7251 /* Try writing without forking. Newer kernels have
7252 * dynamically growing pipes. Must use non-blocking write! */
7255 written = write(pair.wr, heredoc, len);
7266 ndelay_off(pair.wr);
7268 /* Okay, pipe buffer was not big enough */
7269 /* Note: we must not create a stray child (bastard? :)
7270 * for the unsuspecting parent process. Child creates a grandchild
7271 * and exits before parent execs the process which consumes heredoc
7272 * (that exec happens after we return from this function) */
7279 disable_restore_tty_pgrp_on_exit();
7280 pid = BB_MMU ? xfork() : xvfork();
7284 close(redir->rd_fd); /* read side of the pipe */
7286 full_write(pair.wr, heredoc, len); /* may loop or block */
7289 /* Delegate blocking writes to another process */
7290 xmove_fd(pair.wr, STDOUT_FILENO);
7291 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7295 #if ENABLE_HUSH_FAST
7297 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7299 enable_restore_tty_pgrp_on_exit();
7305 wait(NULL); /* wait till child has died */
7311 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7312 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7315 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7317 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7318 sq[i].orig_fd = orig;
7319 sq[i].moved_to = moved;
7320 sq[i+1].orig_fd = -1; /* end marker */
7324 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7330 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7331 /* If we collide with an already moved fd... */
7332 if (fd == sq[i].moved_to) {
7333 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
7334 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7335 if (sq[i].moved_to < 0) /* what? */
7339 if (fd == sq[i].orig_fd) {
7340 /* Example: echo Hello >/dev/null 1>&2 */
7341 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7346 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
7347 moved_to = dup_CLOEXEC(fd, avoid_fd);
7348 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7349 if (moved_to < 0 && errno != EBADF)
7351 return append_squirrel(sq, i, fd, moved_to);
7354 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7359 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7360 /* If we collide with an already moved fd... */
7361 if (fd == sq[i].orig_fd) {
7363 * "echo 3>FILE 3>&- 3>FILE"
7364 * "echo 3>&- 3>FILE"
7365 * No need for last redirect to insert
7366 * another "need to close 3" indicator.
7368 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7373 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7374 return append_squirrel(sq, i, fd, -1);
7377 /* fd: redirect wants this fd to be used (e.g. 3>file).
7378 * Move all conflicting internally used fds,
7379 * and remember them so that we can restore them later.
7381 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
7383 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7386 #if ENABLE_HUSH_INTERACTIVE
7387 if (fd == G.interactive_fd) {
7388 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
7389 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
7390 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7391 return 1; /* "we closed fd" */
7394 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7395 * (1) Redirect in a forked child. No need to save FILEs' fds,
7396 * we aren't going to use them anymore, ok to trash.
7397 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7398 * but how are we doing to restore them?
7399 * "fileno(fd) = new_fd" can't be done.
7404 /* If this one of script's fds? */
7405 if (save_FILEs_on_redirect(fd, avoid_fd))
7406 return 1; /* yes. "we closed fd" */
7408 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7409 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7410 return 0; /* "we did not close fd" */
7413 static void restore_redirects(struct squirrel *sq)
7417 for (i = 0; sq[i].orig_fd >= 0; i++) {
7418 if (sq[i].moved_to >= 0) {
7419 /* We simply die on error */
7420 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7421 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7423 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7424 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7425 close(sq[i].orig_fd);
7431 /* If moved, G.interactive_fd stays on new fd, not restoring it */
7433 restore_redirected_FILEs();
7436 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
7437 static void close_saved_fds_and_FILE_fds(void)
7439 if (G_interactive_fd)
7440 close(G_interactive_fd);
7441 close_all_FILE_list();
7445 static int internally_opened_fd(int fd, struct squirrel *sq)
7449 #if ENABLE_HUSH_INTERACTIVE
7450 if (fd == G.interactive_fd)
7453 /* If this one of script's fds? */
7454 if (fd_in_FILEs(fd))
7457 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7458 if (fd == sq[i].moved_to)
7464 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
7465 * and stderr if they are redirected. */
7466 static int setup_redirects(struct command *prog, struct squirrel **sqp)
7468 struct redir_struct *redir;
7470 for (redir = prog->redirects; redir; redir = redir->next) {
7474 if (redir->rd_type == REDIRECT_HEREDOC2) {
7475 /* "rd_fd<<HERE" case */
7476 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
7477 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7479 debug_printf_parse("set heredoc '%s'\n",
7480 redir->rd_filename);
7481 setup_heredoc(redir);
7485 if (redir->rd_dup == REDIRFD_TO_FILE) {
7486 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
7490 if (redir->rd_filename == NULL) {
7493 * "cmd >" (no filename)
7494 * "cmd > <file" (2nd redirect starts too early)
7496 syntax_error("invalid redirect");
7499 mode = redir_table[redir->rd_type].mode;
7500 p = expand_string_to_string(redir->rd_filename,
7501 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
7502 newfd = open_or_warn(p, mode);
7505 /* Error message from open_or_warn can be lost
7506 * if stderr has been redirected, but bash
7507 * and ash both lose it as well
7508 * (though zsh doesn't!)
7512 if (newfd == redir->rd_fd && sqp) {
7513 /* open() gave us precisely the fd we wanted.
7514 * This means that this fd was not busy
7515 * (not opened to anywhere).
7516 * Remember to close it on restore:
7518 *sqp = add_squirrel_closed(*sqp, newfd);
7519 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7522 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7523 newfd = redir->rd_dup;
7526 if (newfd == redir->rd_fd)
7529 /* if "N>FILE": move newfd to redir->rd_fd */
7530 /* if "N>&M": dup newfd to redir->rd_fd */
7531 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7533 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7534 if (newfd == REDIRFD_CLOSE) {
7535 /* "N>&-" means "close me" */
7537 /* ^^^ optimization: saving may already
7538 * have closed it. If not... */
7539 close(redir->rd_fd);
7541 /* Sometimes we do another close on restore, getting EBADF.
7542 * Consider "echo 3>FILE 3>&-"
7543 * first redirect remembers "need to close 3",
7544 * and second redirect closes 3! Restore code then closes 3 again.
7547 /* if newfd is a script fd or saved fd, simulate EBADF */
7548 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7550 //bb_perror_msg_and_die("can't duplicate file descriptor");
7551 newfd = -1; /* same effect as code above */
7553 xdup2(newfd, redir->rd_fd);
7554 if (redir->rd_dup == REDIRFD_TO_FILE)
7555 /* "rd_fd > FILE" */
7557 /* else: "rd_fd > rd_dup" */
7563 static char *find_in_path(const char *arg)
7566 const char *PATH = get_local_var_value("PATH");
7572 const char *end = strchrnul(PATH, ':');
7573 int sz = end - PATH; /* must be int! */
7577 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7579 /* We have xxx::yyyy in $PATH,
7580 * it means "use current dir" */
7583 if (access(ret, F_OK) == 0)
7596 static const struct built_in_command *find_builtin_helper(const char *name,
7597 const struct built_in_command *x,
7598 const struct built_in_command *end)
7601 if (strcmp(name, x->b_cmd) != 0) {
7605 debug_printf_exec("found builtin '%s'\n", name);
7610 static const struct built_in_command *find_builtin1(const char *name)
7612 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7614 static const struct built_in_command *find_builtin(const char *name)
7616 const struct built_in_command *x = find_builtin1(name);
7619 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7622 static void remove_nested_vars(void)
7624 struct variable *cur;
7625 struct variable **cur_pp;
7627 cur_pp = &G.top_var;
7628 while ((cur = *cur_pp) != NULL) {
7629 if (cur->var_nest_level <= G.var_nest_level) {
7630 cur_pp = &cur->next;
7634 if (cur->flg_export) {
7635 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7636 bb_unsetenv(cur->varstr);
7638 /* Remove from global list */
7639 *cur_pp = cur->next;
7641 if (!cur->max_len) {
7642 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7649 static void enter_var_nest_level(void)
7652 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7654 /* Try: f() { echo -n .; f; }; f
7655 * struct variable::var_nest_level is uint16_t,
7656 * thus limiting recursion to < 2^16.
7657 * In any case, with 8 Mbyte stack SEGV happens
7658 * not too long after 2^16 recursions anyway.
7660 if (G.var_nest_level > 0xff00)
7661 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7664 static void leave_var_nest_level(void)
7667 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7668 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7669 bb_error_msg_and_die("BUG: nesting underflow");
7671 remove_nested_vars();
7674 #if ENABLE_HUSH_FUNCTIONS
7675 static struct function **find_function_slot(const char *name)
7677 struct function *funcp;
7678 struct function **funcpp = &G.top_func;
7680 while ((funcp = *funcpp) != NULL) {
7681 if (strcmp(name, funcp->name) == 0) {
7682 debug_printf_exec("found function '%s'\n", name);
7685 funcpp = &funcp->next;
7690 static ALWAYS_INLINE const struct function *find_function(const char *name)
7692 const struct function *funcp = *find_function_slot(name);
7696 /* Note: takes ownership on name ptr */
7697 static struct function *new_function(char *name)
7699 struct function **funcpp = find_function_slot(name);
7700 struct function *funcp = *funcpp;
7702 if (funcp != NULL) {
7703 struct command *cmd = funcp->parent_cmd;
7704 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7706 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7708 /* Note: if !funcp->body, do not free body_as_string!
7709 * This is a special case of "-F name body" function:
7710 * body_as_string was not malloced! */
7712 free_pipe_list(funcp->body);
7714 free(funcp->body_as_string);
7718 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7719 cmd->argv[0] = funcp->name;
7720 cmd->group = funcp->body;
7722 cmd->group_as_string = funcp->body_as_string;
7726 debug_printf_exec("remembering new function '%s'\n", name);
7727 funcp = *funcpp = xzalloc(sizeof(*funcp));
7728 /*funcp->next = NULL;*/
7735 # if ENABLE_HUSH_UNSET
7736 static void unset_func(const char *name)
7738 struct function **funcpp = find_function_slot(name);
7739 struct function *funcp = *funcpp;
7741 if (funcp != NULL) {
7742 debug_printf_exec("freeing function '%s'\n", funcp->name);
7743 *funcpp = funcp->next;
7744 /* funcp is unlinked now, deleting it.
7745 * Note: if !funcp->body, the function was created by
7746 * "-F name body", do not free ->body_as_string
7747 * and ->name as they were not malloced. */
7749 free_pipe_list(funcp->body);
7752 free(funcp->body_as_string);
7761 #define exec_function(to_free, funcp, argv) \
7762 exec_function(funcp, argv)
7764 static void exec_function(char ***to_free,
7765 const struct function *funcp,
7766 char **argv) NORETURN;
7767 static void exec_function(char ***to_free,
7768 const struct function *funcp,
7774 argv[0] = G.global_argv[0];
7775 G.global_argv = argv;
7776 G.global_argc = n = 1 + string_array_len(argv + 1);
7778 // Example when we are here: "cmd | func"
7779 // func will run with saved-redirect fds open.
7780 // $ f() { echo /proc/self/fd/*; }
7782 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7783 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7786 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7787 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7788 // They are CLOEXEC so external programs won't see them, but
7789 // for "more correctness" we might want to close those extra fds here:
7790 //? close_saved_fds_and_FILE_fds();
7792 /* "we are in a function, ok to use return" */
7793 G_flag_return_in_progress = -1;
7794 enter_var_nest_level();
7795 IF_HUSH_LOCAL(G.func_nest_level++;)
7797 /* On MMU, funcp->body is always non-NULL */
7798 n = run_list(funcp->body);
7802 //? close_saved_fds_and_FILE_fds();
7804 //TODO: check whether "true | func_with_return" works
7806 re_execute_shell(to_free,
7807 funcp->body_as_string,
7814 static int run_function(const struct function *funcp, char **argv)
7820 save_and_replace_G_args(&sv, argv);
7822 /* "We are in function, ok to use return" */
7823 sv_flg = G_flag_return_in_progress;
7824 G_flag_return_in_progress = -1;
7826 /* Make "local" variables properly shadow previous ones */
7827 IF_HUSH_LOCAL(enter_var_nest_level();)
7828 IF_HUSH_LOCAL(G.func_nest_level++;)
7830 /* On MMU, funcp->body is always non-NULL */
7833 /* Function defined by -F */
7834 parse_and_run_string(funcp->body_as_string);
7835 rc = G.last_exitcode;
7839 rc = run_list(funcp->body);
7842 IF_HUSH_LOCAL(G.func_nest_level--;)
7843 IF_HUSH_LOCAL(leave_var_nest_level();)
7845 G_flag_return_in_progress = sv_flg;
7847 restore_G_args(&sv, argv);
7851 #endif /* ENABLE_HUSH_FUNCTIONS */
7855 #define exec_builtin(to_free, x, argv) \
7856 exec_builtin(x, argv)
7858 #define exec_builtin(to_free, x, argv) \
7859 exec_builtin(to_free, argv)
7861 static void exec_builtin(char ***to_free,
7862 const struct built_in_command *x,
7863 char **argv) NORETURN;
7864 static void exec_builtin(char ***to_free,
7865 const struct built_in_command *x,
7871 //? close_saved_fds_and_FILE_fds();
7872 rcode = x->b_function(argv);
7877 /* On NOMMU, we must never block!
7878 * Example: { sleep 99 | read line; } & echo Ok
7880 re_execute_shell(to_free,
7889 static void execvp_or_die(char **argv) NORETURN;
7890 static void execvp_or_die(char **argv)
7893 debug_printf_exec("execing '%s'\n", argv[0]);
7894 /* Don't propagate SIG_IGN to the child */
7895 if (SPECIAL_JOBSTOP_SIGS != 0)
7896 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7897 execvp(argv[0], argv);
7899 if (errno == EACCES) e = 126;
7900 if (errno == ENOENT) e = 127;
7901 bb_perror_msg("can't execute '%s'", argv[0]);
7905 #if ENABLE_HUSH_MODE_X
7906 static void dump_cmd_in_x_mode(char **argv)
7908 if (G_x_mode && argv) {
7909 /* We want to output the line in one write op */
7917 len += strlen(argv[n++]) + 1;
7923 p += sprintf(p, " %s", argv[n++]);
7931 # define dump_cmd_in_x_mode(argv) ((void)0)
7934 #if ENABLE_HUSH_COMMAND
7935 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7944 char *path = getenv("PATH");
7945 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
7947 _exit(1); /* PROG was not found */
7949 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7951 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
7957 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
7961 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7962 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7963 #define pseudo_exec(nommu_save, command, argv_expanded) \
7964 pseudo_exec(command, argv_expanded)
7967 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7969 * Don't exit() here. If you don't exec, use _exit instead.
7970 * The at_exit handlers apparently confuse the calling process,
7971 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7973 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7974 char **argv, int assignment_cnt,
7975 char **argv_expanded) NORETURN;
7976 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7977 char **argv, int assignment_cnt,
7978 char **argv_expanded)
7980 const struct built_in_command *x;
7981 struct variable **sv_shadowed;
7983 IF_HUSH_COMMAND(char opt_vV = 0;)
7984 IF_HUSH_FUNCTIONS(const struct function *funcp;)
7986 new_env = expand_assignments(argv, assignment_cnt);
7987 dump_cmd_in_x_mode(new_env);
7989 if (!argv[assignment_cnt]) {
7990 /* Case when we are here: ... | var=val | ...
7991 * (note that we do not exit early, i.e., do not optimize out
7992 * expand_assignments(): think about ... | var=`sleep 1` | ...
7994 free_strings(new_env);
7995 _exit(EXIT_SUCCESS);
7998 sv_shadowed = G.shadowed_vars_pp;
8000 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
8002 G.shadowed_vars_pp = &nommu_save->old_vars;
8005 set_vars_and_save_old(new_env);
8006 G.shadowed_vars_pp = sv_shadowed;
8008 if (argv_expanded) {
8009 argv = argv_expanded;
8011 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8013 nommu_save->argv = argv;
8016 dump_cmd_in_x_mode(argv);
8018 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8019 if (strchr(argv[0], '/') != NULL)
8023 #if ENABLE_HUSH_FUNCTIONS
8024 /* Check if the command matches any functions (this goes before bltins) */
8025 funcp = find_function(argv[0]);
8027 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
8030 #if ENABLE_HUSH_COMMAND
8031 /* "command BAR": run BAR without looking it up among functions
8032 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8033 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8035 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8040 if (p[0] != '-' || !p[1])
8041 continue; /* bash allows "command command command [-OPT] BAR" */
8049 if (p[0] != '-' || !p[1])
8051 continue; /* next arg is also -opts, process it too */
8057 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8062 # if ENABLE_HUSH_FUNCTIONS
8063 if (opt_vV && find_function(argv[0]))
8064 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8068 /* Check if the command matches any of the builtins.
8069 * Depending on context, this might be redundant. But it's
8070 * easier to waste a few CPU cycles than it is to figure out
8071 * if this is one of those cases.
8073 /* Why "BB_MMU ? :" difference in logic? -
8074 * On NOMMU, it is more expensive to re-execute shell
8075 * just in order to run echo or test builtin.
8076 * It's better to skip it here and run corresponding
8077 * non-builtin later. */
8078 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8080 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8081 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
8084 #if ENABLE_FEATURE_SH_STANDALONE
8085 /* Check if the command matches any busybox applets */
8087 int a = find_applet_by_name(argv[0]);
8089 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
8090 # if BB_MMU /* see above why on NOMMU it is not allowed */
8091 if (APPLET_IS_NOEXEC(a)) {
8092 /* Do not leak open fds from opened script files etc.
8093 * Testcase: interactive "ls -l /proc/self/fd"
8094 * should not show tty fd open.
8096 close_saved_fds_and_FILE_fds();
8097 //FIXME: should also close saved redir fds
8098 //This casuses test failures in
8099 //redir_children_should_not_see_saved_fd_2.tests
8100 //redir_children_should_not_see_saved_fd_3.tests
8101 //if you replace "busybox find" with just "find" in them
8102 /* Without this, "rm -i FILE" can't be ^C'ed: */
8103 switch_off_special_sigs(G.special_sig_mask);
8104 debug_printf_exec("running applet '%s'\n", argv[0]);
8105 run_noexec_applet_and_exit(a, argv[0], argv);
8108 /* Re-exec ourselves */
8109 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
8110 /* Don't propagate SIG_IGN to the child */
8111 if (SPECIAL_JOBSTOP_SIGS != 0)
8112 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8113 execv(bb_busybox_exec_path, argv);
8114 /* If they called chroot or otherwise made the binary no longer
8115 * executable, fall through */
8120 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8123 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
8124 execvp_or_die(argv);
8127 /* Called after [v]fork() in run_pipe
8129 static void pseudo_exec(nommu_save_t *nommu_save,
8130 struct command *command,
8131 char **argv_expanded) NORETURN;
8132 static void pseudo_exec(nommu_save_t *nommu_save,
8133 struct command *command,
8134 char **argv_expanded)
8136 #if ENABLE_HUSH_FUNCTIONS
8137 if (command->cmd_type == CMD_FUNCDEF) {
8138 /* Ignore funcdefs in pipes:
8139 * true | f() { cmd }
8145 if (command->argv) {
8146 pseudo_exec_argv(nommu_save, command->argv,
8147 command->assignment_cnt, argv_expanded);
8150 if (command->group) {
8151 /* Cases when we are here:
8154 * ... | ( list ) | ...
8155 * ... | { list } | ...
8159 debug_printf_exec("pseudo_exec: run_list\n");
8160 reset_traps_to_defaults();
8161 rcode = run_list(command->group);
8162 /* OK to leak memory by not calling free_pipe_list,
8163 * since this process is about to exit */
8166 re_execute_shell(&nommu_save->argv_from_re_execing,
8167 command->group_as_string,
8174 /* Case when we are here: ... | >file */
8175 debug_printf_exec("pseudo_exec'ed null command\n");
8176 _exit(EXIT_SUCCESS);
8180 static const char *get_cmdtext(struct pipe *pi)
8186 /* This is subtle. ->cmdtext is created only on first backgrounding.
8187 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8188 * On subsequent bg argv is trashed, but we won't use it */
8192 argv = pi->cmds[0].argv;
8194 pi->cmdtext = xzalloc(1);
8199 len += strlen(*argv) + 1;
8203 argv = pi->cmds[0].argv;
8205 p = stpcpy(p, *argv);
8212 static void remove_job_from_table(struct pipe *pi)
8214 struct pipe *prev_pipe;
8216 if (pi == G.job_list) {
8217 G.job_list = pi->next;
8219 prev_pipe = G.job_list;
8220 while (prev_pipe->next != pi)
8221 prev_pipe = prev_pipe->next;
8222 prev_pipe->next = pi->next;
8226 G.last_jobid = G.job_list->jobid;
8229 static void delete_finished_job(struct pipe *pi)
8231 remove_job_from_table(pi);
8235 static void clean_up_last_dead_job(void)
8237 if (G.job_list && !G.job_list->alive_cmds)
8238 delete_finished_job(G.job_list);
8241 static void insert_job_into_table(struct pipe *pi)
8243 struct pipe *job, **jobp;
8246 clean_up_last_dead_job();
8248 /* Find the end of the list, and find next job ID to use */
8251 while ((job = *jobp) != NULL) {
8258 /* Create a new job struct at the end */
8259 job = *jobp = xmemdup(pi, sizeof(*pi));
8261 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8262 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8263 for (i = 0; i < pi->num_cmds; i++) {
8264 job->cmds[i].pid = pi->cmds[i].pid;
8265 /* all other fields are not used and stay zero */
8267 job->cmdtext = xstrdup(get_cmdtext(pi));
8269 if (G_interactive_fd)
8270 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
8271 G.last_jobid = job->jobid;
8275 static int job_exited_or_stopped(struct pipe *pi)
8279 if (pi->alive_cmds != pi->stopped_cmds)
8282 /* All processes in fg pipe have exited or stopped */
8286 rcode = pi->cmds[i].cmd_exitcode;
8287 /* usually last process gives overall exitstatus,
8288 * but with "set -o pipefail", last *failed* process does */
8289 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8292 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8296 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
8303 dead = WIFEXITED(status) || WIFSIGNALED(status);
8306 if (WIFSTOPPED(status))
8307 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8308 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8309 if (WIFSIGNALED(status))
8310 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8311 childpid, WTERMSIG(status), WEXITSTATUS(status));
8312 if (WIFEXITED(status))
8313 debug_printf_jobs("pid %d exited, exitcode %d\n",
8314 childpid, WEXITSTATUS(status));
8316 /* Were we asked to wait for a fg pipe? */
8318 i = fg_pipe->num_cmds;
8323 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8324 if (fg_pipe->cmds[i].pid != childpid)
8328 fg_pipe->cmds[i].pid = 0;
8329 fg_pipe->alive_cmds--;
8330 ex = WEXITSTATUS(status);
8331 /* bash prints killer signal's name for *last*
8332 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8333 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8335 if (WIFSIGNALED(status)) {
8336 int sig = WTERMSIG(status);
8337 if (i == fg_pipe->num_cmds-1)
8338 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8339 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8340 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8341 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8342 * Maybe we need to use sig | 128? */
8345 fg_pipe->cmds[i].cmd_exitcode = ex;
8347 fg_pipe->stopped_cmds++;
8349 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8350 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
8351 rcode = job_exited_or_stopped(fg_pipe);
8353 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
8354 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8355 * and "killall -STOP cat" */
8356 if (G_interactive_fd) {
8358 if (fg_pipe->alive_cmds != 0)
8359 insert_job_into_table(fg_pipe);
8363 if (fg_pipe->alive_cmds == 0)
8366 /* There are still running processes in the fg_pipe */
8369 /* It wasn't in fg_pipe, look for process in bg pipes */
8373 /* We were asked to wait for bg or orphaned children */
8374 /* No need to remember exitcode in this case */
8375 for (pi = G.job_list; pi; pi = pi->next) {
8376 for (i = 0; i < pi->num_cmds; i++) {
8377 if (pi->cmds[i].pid == childpid)
8378 goto found_pi_and_prognum;
8381 /* Happens when shell is used as init process (init=/bin/sh) */
8382 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8383 return -1; /* this wasn't a process from fg_pipe */
8385 found_pi_and_prognum:
8388 int rcode = WEXITSTATUS(status);
8389 if (WIFSIGNALED(status))
8390 rcode = 128 + WTERMSIG(status);
8391 pi->cmds[i].cmd_exitcode = rcode;
8392 if (G.last_bg_pid == pi->cmds[i].pid)
8393 G.last_bg_pid_exitcode = rcode;
8394 pi->cmds[i].pid = 0;
8396 if (!pi->alive_cmds) {
8397 if (G_interactive_fd) {
8398 printf(JOB_STATUS_FORMAT, pi->jobid,
8399 "Done", pi->cmdtext);
8400 delete_finished_job(pi);
8403 * bash deletes finished jobs from job table only in interactive mode,
8404 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8405 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8406 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8407 * We only retain one "dead" job, if it's the single job on the list.
8408 * This covers most of real-world scenarios where this is useful.
8410 if (pi != G.job_list)
8411 delete_finished_job(pi);
8419 return -1; /* this wasn't a process from fg_pipe */
8422 /* Check to see if any processes have exited -- if they have,
8423 * figure out why and see if a job has completed.
8425 * If non-NULL fg_pipe: wait for its completion or stop.
8426 * Return its exitcode or zero if stopped.
8428 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8429 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8430 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8431 * or 0 if no children changed status.
8433 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8434 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8435 * or 0 if no children changed status.
8437 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8443 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8445 attributes = WUNTRACED;
8446 if (fg_pipe == NULL)
8447 attributes |= WNOHANG;
8450 #if ENABLE_HUSH_FAST
8451 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8452 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8453 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8454 /* There was neither fork nor SIGCHLD since last waitpid */
8455 /* Avoid doing waitpid syscall if possible */
8456 if (!G.we_have_children) {
8460 if (fg_pipe == NULL) { /* is WNOHANG set? */
8461 /* We have children, but they did not exit
8462 * or stop yet (we saw no SIGCHLD) */
8465 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8469 /* Do we do this right?
8470 * bash-3.00# sleep 20 | false
8472 * [3]+ Stopped sleep 20 | false
8473 * bash-3.00# echo $?
8474 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8475 * [hush 1.14.0: yes we do it right]
8479 #if ENABLE_HUSH_FAST
8481 i = G.count_SIGCHLD;
8483 childpid = waitpid(-1, &status, attributes);
8484 if (childpid <= 0) {
8485 if (childpid && errno != ECHILD)
8486 bb_perror_msg("waitpid");
8487 #if ENABLE_HUSH_FAST
8488 else { /* Until next SIGCHLD, waitpid's are useless */
8489 G.we_have_children = (childpid == 0);
8490 G.handled_SIGCHLD = i;
8491 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8494 /* ECHILD (no children), or 0 (no change in children status) */
8498 rcode = process_wait_result(fg_pipe, childpid, status);
8500 /* fg_pipe exited or stopped */
8503 if (childpid == waitfor_pid) {
8504 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
8505 rcode = WEXITSTATUS(status);
8506 if (WIFSIGNALED(status))
8507 rcode = 128 + WTERMSIG(status);
8508 if (WIFSTOPPED(status))
8509 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8510 rcode = 128 + WSTOPSIG(status);
8512 break; /* "wait PID" called us, give it exitcode+1 */
8514 /* This wasn't one of our processes, or */
8515 /* fg_pipe still has running processes, do waitpid again */
8516 } /* while (waitpid succeeds)... */
8522 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
8525 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
8526 if (G_saved_tty_pgrp) {
8527 /* Job finished, move the shell to the foreground */
8528 p = getpgrp(); /* our process group id */
8529 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8530 tcsetpgrp(G_interactive_fd, p);
8536 /* Start all the jobs, but don't wait for anything to finish.
8539 * Return code is normally -1, when the caller has to wait for children
8540 * to finish to determine the exit status of the pipe. If the pipe
8541 * is a simple builtin command, however, the action is done by the
8542 * time run_pipe returns, and the exit code is provided as the
8545 * Returns -1 only if started some children. IOW: we have to
8546 * mask out retvals of builtins etc with 0xff!
8548 * The only case when we do not need to [v]fork is when the pipe
8549 * is single, non-backgrounded, non-subshell command. Examples:
8550 * cmd ; ... { list } ; ...
8551 * cmd && ... { list } && ...
8552 * cmd || ... { list } || ...
8553 * If it is, then we can run cmd as a builtin, NOFORK,
8554 * or (if SH_STANDALONE) an applet, and we can run the { list }
8555 * with run_list. If it isn't one of these, we fork and exec cmd.
8557 * Cases when we must fork:
8558 * non-single: cmd | cmd
8559 * backgrounded: cmd & { list } &
8560 * subshell: ( list ) [&]
8562 #if !ENABLE_HUSH_MODE_X
8563 #define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8564 redirect_and_varexp_helper(command, squirrel)
8566 static int redirect_and_varexp_helper(
8567 struct command *command,
8568 struct squirrel **sqp,
8569 char **argv_expanded)
8571 /* Assignments occur before redirects. Try:
8572 * a=`sleep 1` sleep 2 3>/qwe/rty
8575 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8576 dump_cmd_in_x_mode(new_env);
8577 dump_cmd_in_x_mode(argv_expanded);
8578 /* this takes ownership of new_env[i] elements, and frees new_env: */
8579 set_vars_and_save_old(new_env);
8581 /* setup_redirects acts on file descriptors, not FILEs.
8582 * This is perfect for work that comes after exec().
8583 * Is it really safe for inline use? Experimentally,
8584 * things seem to work. */
8585 return setup_redirects(command, sqp);
8587 static NOINLINE int run_pipe(struct pipe *pi)
8589 static const char *const null_ptr = NULL;
8593 struct command *command;
8594 char **argv_expanded;
8596 struct squirrel *squirrel = NULL;
8599 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8602 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8603 * Result should be 3 lines: q w e, qwe, q w e
8605 if (G.ifs_whitespace != G.ifs)
8606 free(G.ifs_whitespace);
8607 G.ifs = get_local_var_value("IFS");
8610 G.ifs_whitespace = (char*)G.ifs;
8611 p = skip_whitespace(G.ifs);
8613 /* Not all $IFS is whitespace */
8615 int len = p - G.ifs;
8616 p = skip_non_whitespace(p);
8617 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8618 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8628 G.ifs_whitespace = (char*)G.ifs;
8631 IF_HUSH_JOB(pi->pgrp = -1;)
8632 pi->stopped_cmds = 0;
8633 command = &pi->cmds[0];
8634 argv_expanded = NULL;
8636 if (pi->num_cmds != 1
8637 || pi->followup == PIPE_BG
8638 || command->cmd_type == CMD_SUBSHELL
8645 debug_printf_exec(": group:%p argv:'%s'\n",
8646 command->group, command->argv ? command->argv[0] : "NONE");
8648 if (command->group) {
8649 #if ENABLE_HUSH_FUNCTIONS
8650 if (command->cmd_type == CMD_FUNCDEF) {
8651 /* "executing" func () { list } */
8652 struct function *funcp;
8654 funcp = new_function(command->argv[0]);
8655 /* funcp->name is already set to argv[0] */
8656 funcp->body = command->group;
8658 funcp->body_as_string = command->group_as_string;
8659 command->group_as_string = NULL;
8661 command->group = NULL;
8662 command->argv[0] = NULL;
8663 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8664 funcp->parent_cmd = command;
8665 command->child_func = funcp;
8667 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8669 return EXIT_SUCCESS;
8673 debug_printf("non-subshell group\n");
8674 rcode = 1; /* exitcode if redir failed */
8675 if (setup_redirects(command, &squirrel) == 0) {
8676 debug_printf_exec(": run_list\n");
8677 //FIXME: we need to pass squirrel down into run_list()
8678 //for SH_STANDALONE case, or else this construct:
8679 // { find /proc/self/fd; true; } >FILE; cmd2
8680 //has no way of closing saved fd#1 for "find",
8681 //and in SH_STANDALONE mode, "find" is not execed,
8682 //therefore CLOEXEC on saved fd does not help.
8683 rcode = run_list(command->group) & 0xff;
8685 restore_redirects(squirrel);
8686 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8688 debug_printf_exec("run_pipe: return %d\n", rcode);
8692 argv = command->argv ? command->argv : (char **) &null_ptr;
8694 const struct built_in_command *x;
8695 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8696 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
8697 struct variable **sv_shadowed;
8698 struct variable *old_vars;
8700 #if ENABLE_HUSH_LINENO_VAR
8702 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8705 if (argv[command->assignment_cnt] == NULL) {
8706 /* Assignments, but no command.
8707 * Ensure redirects take effect (that is, create files).
8711 G.expand_exitcode = 0;
8713 rcode = setup_redirects(command, &squirrel);
8714 restore_redirects(squirrel);
8716 /* Set shell variables */
8718 bb_putchar_stderr('+');
8720 while (i < command->assignment_cnt) {
8721 char *p = expand_string_to_string(argv[i],
8722 EXP_FLAG_ESC_GLOB_CHARS,
8726 fprintf(stderr, " %s", p);
8727 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
8728 if (set_local_var(p, /*flag:*/ 0)) {
8729 /* assignment to readonly var / putenv error? */
8735 bb_putchar_stderr('\n');
8736 /* Redirect error sets $? to 1. Otherwise,
8737 * if evaluating assignment value set $?, retain it.
8739 * false; q=`exit 2`; echo $? - should print 2
8740 * false; x=1; echo $? - should print 0
8741 * Because of the 2nd case, we can't just use G.last_exitcode.
8744 rcode = G.expand_exitcode;
8745 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8747 debug_printf_exec("run_pipe: return %d\n", rcode);
8751 /* Expand the rest into (possibly) many strings each */
8752 #if defined(CMD_SINGLEWORD_NOGLOB)
8753 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
8754 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8757 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8759 /* If someone gives us an empty string: `cmd with empty output` */
8760 if (!argv_expanded[0]) {
8761 free(argv_expanded);
8762 /* `false` still has to set exitcode 1 */
8763 G.expand_exitcode = G.last_exitcode;
8764 goto only_assignments;
8768 sv_shadowed = G.shadowed_vars_pp;
8770 /* Check if argv[0] matches any functions (this goes before bltins) */
8771 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8772 IF_HUSH_FUNCTIONS(x = NULL;)
8773 IF_HUSH_FUNCTIONS(if (!funcp))
8774 x = find_builtin(argv_expanded[0]);
8776 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8777 debug_printf("exec with redirects only\n");
8779 * Variable assignments are executed, but then "forgotten":
8780 * a=`sleep 1;echo A` exec 3>&-; echo $a
8781 * sleeps, but prints nothing.
8783 enter_var_nest_level();
8784 G.shadowed_vars_pp = &old_vars;
8785 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8786 G.shadowed_vars_pp = sv_shadowed;
8787 /* rcode=1 can be if redir file can't be opened */
8789 goto clean_up_and_ret1;
8792 /* Bump var nesting, or this will leak exported $a:
8793 * a=b true; env | grep ^a=
8795 enter_var_nest_level();
8796 /* Collect all variables "shadowed" by helper
8797 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8798 * into old_vars list:
8800 G.shadowed_vars_pp = &old_vars;
8801 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8804 /* Do not collect *to old_vars list* vars shadowed
8805 * by e.g. "local VAR" builtin (collect them
8806 * in the previously nested list instead):
8807 * don't want them to be restored immediately
8808 * after "local" completes.
8810 G.shadowed_vars_pp = sv_shadowed;
8812 debug_printf_exec(": builtin '%s' '%s'...\n",
8813 x->b_cmd, argv_expanded[1]);
8815 rcode = x->b_function(argv_expanded) & 0xff;
8818 #if ENABLE_HUSH_FUNCTIONS
8820 debug_printf_exec(": function '%s' '%s'...\n",
8821 funcp->name, argv_expanded[1]);
8822 rcode = run_function(funcp, argv_expanded) & 0xff;
8824 * But do collect *to old_vars list* vars shadowed
8825 * within function execution. To that end, restore
8826 * this pointer _after_ function run:
8828 G.shadowed_vars_pp = sv_shadowed;
8833 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
8834 int n = find_applet_by_name(argv_expanded[0]);
8835 if (n < 0 || !APPLET_IS_NOFORK(n))
8838 enter_var_nest_level();
8839 /* Collect all variables "shadowed" by helper into old_vars list */
8840 G.shadowed_vars_pp = &old_vars;
8841 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8842 G.shadowed_vars_pp = sv_shadowed;
8845 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8846 argv_expanded[0], argv_expanded[1]);
8848 * Note: signals (^C) can't interrupt here.
8849 * We remember them and they will be acted upon
8850 * after applet returns.
8851 * This makes applets which can run for a long time
8852 * and/or wait for user input ineligible for NOFORK:
8853 * for example, "yes" or "rm" (rm -i waits for input).
8855 rcode = run_nofork_applet(n, argv_expanded);
8860 restore_redirects(squirrel);
8862 leave_var_nest_level();
8866 * Try "usleep 99999999" + ^C + "echo $?"
8867 * with FEATURE_SH_NOFORK=y.
8870 /* It was builtin or nofork.
8871 * if this would be a real fork/execed program,
8872 * it should have died if a fatal sig was received.
8873 * But OTOH, there was no separate process,
8874 * the sig was sent to _shell_, not to non-existing
8876 * Let's just handle ^C only, this one is obvious:
8877 * we aren't ok with exitcode 0 when ^C was pressed
8878 * during builtin/nofork.
8880 if (sigismember(&G.pending_set, SIGINT))
8881 rcode = 128 + SIGINT;
8883 free(argv_expanded);
8884 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8886 debug_printf_exec("run_pipe return %d\n", rcode);
8891 /* NB: argv_expanded may already be created, and that
8892 * might include `cmd` runs! Do not rerun it! We *must*
8893 * use argv_expanded if it's non-NULL */
8895 /* Going to fork a child per each pipe member */
8900 while (cmd_no < pi->num_cmds) {
8901 struct fd_pair pipefds;
8903 int sv_var_nest_level = G.var_nest_level;
8904 volatile nommu_save_t nommu_save;
8905 nommu_save.old_vars = NULL;
8906 nommu_save.argv = NULL;
8907 nommu_save.argv_from_re_execing = NULL;
8909 command = &pi->cmds[cmd_no];
8911 if (command->argv) {
8912 debug_printf_exec(": pipe member '%s' '%s'...\n",
8913 command->argv[0], command->argv[1]);
8915 debug_printf_exec(": pipe member with no argv\n");
8918 /* pipes are inserted between pairs of commands */
8921 if (cmd_no < pi->num_cmds)
8922 xpiped_pair(pipefds);
8924 #if ENABLE_HUSH_LINENO_VAR
8926 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8929 command->pid = BB_MMU ? fork() : vfork();
8930 if (!command->pid) { /* child */
8932 disable_restore_tty_pgrp_on_exit();
8933 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8935 /* Every child adds itself to new process group
8936 * with pgid == pid_of_first_child_in_pipe */
8937 if (G.run_list_level == 1 && G_interactive_fd) {
8940 if (pgrp < 0) /* true for 1st process only */
8942 if (setpgid(0, pgrp) == 0
8943 && pi->followup != PIPE_BG
8944 && G_saved_tty_pgrp /* we have ctty */
8946 /* We do it in *every* child, not just first,
8948 tcsetpgrp(G_interactive_fd, pgrp);
8952 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8953 /* 1st cmd in backgrounded pipe
8954 * should have its stdin /dev/null'ed */
8956 if (open(bb_dev_null, O_RDONLY))
8957 xopen("/", O_RDONLY);
8959 xmove_fd(next_infd, 0);
8961 xmove_fd(pipefds.wr, 1);
8964 /* Like bash, explicit redirects override pipes,
8965 * and the pipe fd (fd#1) is available for dup'ing:
8966 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8967 * of cmd1 goes into pipe.
8969 if (setup_redirects(command, NULL)) {
8970 /* Happens when redir file can't be opened:
8971 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8973 * hush: can't open '/qwe/rty': No such file or directory
8975 * (echo BAR is not executed, it hits _exit(1) below)
8980 /* Stores to nommu_save list of env vars putenv'ed
8981 * (NOMMU, on MMU we don't need that) */
8982 /* cast away volatility... */
8983 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8984 /* pseudo_exec() does not return */
8987 /* parent or error */
8988 #if ENABLE_HUSH_FAST
8990 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8992 enable_restore_tty_pgrp_on_exit();
8994 /* Clean up after vforked child */
8995 free(nommu_save.argv);
8996 free(nommu_save.argv_from_re_execing);
8997 G.var_nest_level = sv_var_nest_level;
8998 remove_nested_vars();
8999 add_vars(nommu_save.old_vars);
9001 free(argv_expanded);
9002 argv_expanded = NULL;
9003 if (command->pid < 0) { /* [v]fork failed */
9004 /* Clearly indicate, was it fork or vfork */
9005 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9009 /* Second and next children need to know pid of first one */
9011 pi->pgrp = command->pid;
9017 if (cmd_no < pi->num_cmds)
9019 /* Pass read (output) pipe end to next iteration */
9020 next_infd = pipefds.rd;
9023 if (!pi->alive_cmds) {
9025 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9030 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9034 /* NB: called by pseudo_exec, and therefore must not modify any
9035 * global data until exec/_exit (we can be a child after vfork!) */
9036 static int run_list(struct pipe *pi)
9038 #if ENABLE_HUSH_CASE
9039 char *case_word = NULL;
9041 #if ENABLE_HUSH_LOOPS
9042 struct pipe *loop_top = NULL;
9043 char **for_lcur = NULL;
9044 char **for_list = NULL;
9046 smallint last_followup;
9048 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9049 smalluint cond_code = 0;
9051 enum { cond_code = 0 };
9054 smallint rword; /* RES_foo */
9055 smallint last_rword; /* ditto */
9058 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9061 #if ENABLE_HUSH_LOOPS
9062 /* Check syntax for "for" */
9065 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9066 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9068 /* current word is FOR or IN (BOLD in comments below) */
9069 if (cpipe->next == NULL) {
9070 syntax_error("malformed for");
9072 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9075 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9076 if (cpipe->next->res_word == RES_DO)
9078 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9079 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9080 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9082 syntax_error("malformed for");
9084 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9091 /* Past this point, all code paths should jump to ret: label
9092 * in order to return, no direct "return" statements please.
9093 * This helps to ensure that no memory is leaked. */
9101 last_rword = RES_XXXX;
9103 last_followup = PIPE_SEQ;
9104 rcode = G.last_exitcode;
9106 /* Go through list of pipes, (maybe) executing them. */
9107 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
9109 int sv_errexit_depth;
9113 if (G_flag_return_in_progress == 1)
9116 IF_HAS_KEYWORDS(rword = pi->res_word;)
9117 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9118 rword, cond_code, last_rword);
9120 sv_errexit_depth = G.errexit_depth;
9123 rword == RES_IF || rword == RES_ELIF ||
9125 pi->followup != PIPE_SEQ
9129 #if ENABLE_HUSH_LOOPS
9130 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9131 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9133 /* start of a loop: remember where loop starts */
9138 /* Still in the same "if...", "then..." or "do..." branch? */
9139 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9140 if ((rcode == 0 && last_followup == PIPE_OR)
9141 || (rcode != 0 && last_followup == PIPE_AND)
9143 /* It is "<true> || CMD" or "<false> && CMD"
9144 * and we should not execute CMD */
9145 debug_printf_exec("skipped cmd because of || or &&\n");
9146 last_followup = pi->followup;
9147 goto dont_check_jobs_but_continue;
9150 last_followup = pi->followup;
9151 IF_HAS_KEYWORDS(last_rword = rword;)
9154 if (rword == RES_THEN) {
9155 /* if false; then ... fi has exitcode 0! */
9156 G.last_exitcode = rcode = EXIT_SUCCESS;
9157 /* "if <false> THEN cmd": skip cmd */
9161 if (rword == RES_ELSE || rword == RES_ELIF) {
9162 /* "if <true> then ... ELSE/ELIF cmd":
9163 * skip cmd and all following ones */
9168 #if ENABLE_HUSH_LOOPS
9169 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9171 /* first loop through for */
9173 static const char encoded_dollar_at[] ALIGN1 = {
9174 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9175 }; /* encoded representation of "$@" */
9176 static const char *const encoded_dollar_at_argv[] = {
9177 encoded_dollar_at, NULL
9178 }; /* argv list with one element: "$@" */
9181 vals = (char**)encoded_dollar_at_argv;
9182 if (pi->next->res_word == RES_IN) {
9183 /* if no variable values after "in" we skip "for" */
9184 if (!pi->next->cmds[0].argv) {
9185 G.last_exitcode = rcode = EXIT_SUCCESS;
9186 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9189 vals = pi->next->cmds[0].argv;
9190 } /* else: "for var; do..." -> assume "$@" list */
9191 /* create list of variable values */
9192 debug_print_strings("for_list made from", vals);
9193 for_list = expand_strvec_to_strvec(vals);
9194 for_lcur = for_list;
9195 debug_print_strings("for_list", for_list);
9198 /* "for" loop is over, clean up */
9204 /* Insert next value from for_lcur */
9205 /* note: *for_lcur already has quotes removed, $var expanded, etc */
9206 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
9209 if (rword == RES_IN) {
9210 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9212 if (rword == RES_DONE) {
9213 continue; /* "done" has no cmds too */
9216 #if ENABLE_HUSH_CASE
9217 if (rword == RES_CASE) {
9218 debug_printf_exec("CASE cond_code:%d\n", cond_code);
9219 case_word = expand_string_to_string(pi->cmds->argv[0],
9220 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
9221 debug_printf_exec("CASE word1:'%s'\n", case_word);
9222 //unbackslash(case_word);
9223 //debug_printf_exec("CASE word2:'%s'\n", case_word);
9226 if (rword == RES_MATCH) {
9229 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
9230 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9232 /* all prev words didn't match, does this one match? */
9233 argv = pi->cmds->argv;
9236 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9237 pattern = expand_string_to_string(*argv,
9238 EXP_FLAG_ESC_GLOB_CHARS,
9241 /* TODO: which FNM_xxx flags to use? */
9242 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
9243 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9244 pattern, case_word, cond_code);
9246 if (cond_code == 0) {
9247 /* match! we will execute this branch */
9249 case_word = NULL; /* make future "word)" stop */
9256 if (rword == RES_CASE_BODY) { /* inside of a case branch */
9257 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
9259 continue; /* not matched yet, skip this pipe */
9261 if (rword == RES_ESAC) {
9262 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9264 /* "case" did not match anything: still set $? (to 0) */
9265 G.last_exitcode = rcode = EXIT_SUCCESS;
9269 /* Just pressing <enter> in shell should check for jobs.
9270 * OTOH, in non-interactive shell this is useless
9271 * and only leads to extra job checks */
9272 if (pi->num_cmds == 0) {
9273 if (G_interactive_fd)
9274 goto check_jobs_and_continue;
9278 /* After analyzing all keywords and conditions, we decided
9279 * to execute this pipe. NB: have to do checkjobs(NULL)
9280 * after run_pipe to collect any background children,
9281 * even if list execution is to be stopped. */
9282 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
9283 #if ENABLE_HUSH_LOOPS
9284 G.flag_break_continue = 0;
9286 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9288 /* We ran a builtin, function, or group.
9289 * rcode is already known
9290 * and we don't need to wait for anything. */
9291 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9292 G.last_exitcode = rcode;
9293 check_and_run_traps();
9294 #if ENABLE_HUSH_LOOPS
9295 /* Was it "break" or "continue"? */
9296 if (G.flag_break_continue) {
9297 smallint fbc = G.flag_break_continue;
9298 /* We might fall into outer *loop*,
9299 * don't want to break it too */
9301 G.depth_break_continue--;
9302 if (G.depth_break_continue == 0)
9303 G.flag_break_continue = 0;
9304 /* else: e.g. "continue 2" should *break* once, *then* continue */
9305 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9306 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
9307 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9310 /* "continue": simulate end of loop */
9315 if (G_flag_return_in_progress == 1) {
9316 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9319 } else if (pi->followup == PIPE_BG) {
9320 /* What does bash do with attempts to background builtins? */
9321 /* even bash 3.2 doesn't do that well with nested bg:
9322 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9323 * I'm NOT treating inner &'s as jobs */
9325 if (G.run_list_level == 1)
9326 insert_job_into_table(pi);
9328 /* Last command's pid goes to $! */
9329 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
9330 G.last_bg_pid_exitcode = 0;
9331 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
9332 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
9333 rcode = EXIT_SUCCESS;
9337 if (G.run_list_level == 1 && G_interactive_fd) {
9338 /* Waits for completion, then fg's main shell */
9339 rcode = checkjobs_and_fg_shell(pi);
9340 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
9344 /* This one just waits for completion */
9345 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9346 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9348 G.last_exitcode = rcode;
9349 check_and_run_traps();
9352 /* Handle "set -e" */
9353 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9354 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9355 if (G.errexit_depth == 0)
9358 G.errexit_depth = sv_errexit_depth;
9360 /* Analyze how result affects subsequent commands */
9362 if (rword == RES_IF || rword == RES_ELIF)
9365 check_jobs_and_continue:
9366 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9367 dont_check_jobs_but_continue: ;
9368 #if ENABLE_HUSH_LOOPS
9369 /* Beware of "while false; true; do ..."! */
9371 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
9372 /* check for RES_DONE is needed for "while ...; do \n done" case */
9374 if (rword == RES_WHILE) {
9376 /* "while false; do...done" - exitcode 0 */
9377 G.last_exitcode = rcode = EXIT_SUCCESS;
9378 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
9382 if (rword == RES_UNTIL) {
9384 debug_printf_exec(": until expr is true: breaking\n");
9395 #if ENABLE_HUSH_LOOPS
9400 #if ENABLE_HUSH_CASE
9404 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9408 /* Select which version we will use */
9409 static int run_and_free_list(struct pipe *pi)
9412 debug_printf_exec("run_and_free_list entered\n");
9413 if (!G.o_opt[OPT_O_NOEXEC]) {
9414 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9415 rcode = run_list(pi);
9417 /* free_pipe_list has the side effect of clearing memory.
9418 * In the long run that function can be merged with run_list,
9419 * but doing that now would hobble the debugging effort. */
9421 debug_printf_exec("run_and_free_list return %d\n", rcode);
9426 static void install_sighandlers(unsigned mask)
9428 sighandler_t old_handler;
9430 while ((mask >>= 1) != 0) {
9434 old_handler = install_sighandler(sig, pick_sighandler(sig));
9435 /* POSIX allows shell to re-enable SIGCHLD
9436 * even if it was SIG_IGN on entry.
9437 * Therefore we skip IGN check for it:
9441 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9442 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9444 //if (sig == SIGHUP) continue; - TODO?
9445 if (old_handler == SIG_IGN) {
9446 /* oops... restore back to IGN, and record this fact */
9447 install_sighandler(sig, old_handler);
9448 #if ENABLE_HUSH_TRAP
9450 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9452 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9458 /* Called a few times only (or even once if "sh -c") */
9459 static void install_special_sighandlers(void)
9463 /* Which signals are shell-special? */
9464 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
9465 if (G_interactive_fd) {
9466 mask |= SPECIAL_INTERACTIVE_SIGS;
9467 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
9468 mask |= SPECIAL_JOBSTOP_SIGS;
9470 /* Careful, do not re-install handlers we already installed */
9471 if (G.special_sig_mask != mask) {
9472 unsigned diff = mask & ~G.special_sig_mask;
9473 G.special_sig_mask = mask;
9474 install_sighandlers(diff);
9480 /* Set handlers to restore tty pgrp and exit */
9481 static void install_fatal_sighandlers(void)
9485 /* We will restore tty pgrp on these signals */
9487 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9488 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
9489 + (1 << SIGBUS ) * HUSH_DEBUG
9490 + (1 << SIGSEGV) * HUSH_DEBUG
9491 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
9493 /* bash 3.2 seems to handle these just like 'fatal' ones */
9496 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
9497 * if we aren't interactive... but in this case
9498 * we never want to restore pgrp on exit, and this fn is not called
9500 /*+ (1 << SIGHUP )*/
9501 /*+ (1 << SIGTERM)*/
9502 /*+ (1 << SIGINT )*/
9504 G_fatal_sig_mask = mask;
9506 install_sighandlers(mask);
9510 static int set_mode(int state, char mode, const char *o_opt)
9515 G.o_opt[OPT_O_NOEXEC] = state;
9518 IF_HUSH_MODE_X(G_x_mode = state;)
9522 /* "set -+o" without parameter.
9523 * in bash, set -o produces this output:
9527 * We always use the second form.
9529 const char *p = o_opt_strings;
9532 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9538 idx = index_in_strings(o_opt_strings, o_opt);
9540 G.o_opt[idx] = state;
9544 G.o_opt[OPT_O_ERREXIT] = state;
9547 return EXIT_FAILURE;
9549 return EXIT_SUCCESS;
9552 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
9553 int hush_main(int argc, char **argv)
9556 OPT_login = (1 << 0),
9560 unsigned builtin_argc;
9562 struct variable *cur_var;
9563 struct variable *shell_ver;
9566 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
9567 G.last_exitcode = EXIT_SUCCESS;
9569 #if ENABLE_HUSH_FAST
9570 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9573 G.argv0_for_re_execing = argv[0];
9576 /* Deal with HUSH_VERSION */
9577 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9578 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
9579 shell_ver = xzalloc(sizeof(*shell_ver));
9580 shell_ver->flg_export = 1;
9581 shell_ver->flg_read_only = 1;
9582 /* Code which handles ${var<op>...} needs writable values for all variables,
9583 * therefore we xstrdup: */
9584 shell_ver->varstr = xstrdup(hush_version_str);
9586 /* Create shell local variables from the values
9587 * currently living in the environment */
9588 G.top_var = shell_ver;
9589 cur_var = G.top_var;
9592 char *value = strchr(*e, '=');
9593 if (value) { /* paranoia */
9594 cur_var->next = xzalloc(sizeof(*cur_var));
9595 cur_var = cur_var->next;
9596 cur_var->varstr = *e;
9597 cur_var->max_len = strlen(*e);
9598 cur_var->flg_export = 1;
9602 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
9603 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9604 putenv(shell_ver->varstr);
9607 set_pwd_var(SETFLAG_EXPORT);
9609 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9610 /* Set (but not export) PS1/2 unless already set */
9611 if (!get_local_var_value("PS1"))
9612 set_local_var_from_halves("PS1", "\\w \\$ ");
9613 if (!get_local_var_value("PS2"))
9614 set_local_var_from_halves("PS2", "> ");
9617 #if BASH_HOSTNAME_VAR
9618 /* Set (but not export) HOSTNAME unless already set */
9619 if (!get_local_var_value("HOSTNAME")) {
9622 set_local_var_from_halves("HOSTNAME", uts.nodename);
9624 /* bash also exports SHLVL and _,
9625 * and sets (but doesn't export) the following variables:
9627 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9628 * BASH_VERSION='3.2.0(1)-release'
9630 * MACHTYPE=i386-pc-linux-gnu
9632 * PPID=<NNNNN> - we also do it elsewhere
9643 * PIPESTATUS=([0]="0")
9644 * HISTFILE=/<xxx>/.bash_history
9648 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9650 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9659 #if ENABLE_HUSH_LINENO_VAR
9660 if (ENABLE_HUSH_LINENO_VAR) {
9661 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9662 set_local_var(p, /*flags*/ 0);
9663 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9667 #if ENABLE_FEATURE_EDITING
9668 G.line_input_state = new_line_input_t(FOR_SHELL);
9671 /* Initialize some more globals to non-zero values */
9672 cmdedit_update_prompt();
9674 die_func = restore_ttypgrp_and__exit;
9676 /* Shell is non-interactive at first. We need to call
9677 * install_special_sighandlers() if we are going to execute "sh <script>",
9678 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9679 * If we later decide that we are interactive, we run install_special_sighandlers()
9680 * in order to intercept (more) signals.
9684 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9685 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9688 int opt = getopt(argc, argv, "+c:exinsl"
9691 # if ENABLE_HUSH_FUNCTIONS
9701 * sh ... -c 'script'
9702 * sh ... -c 'script' ARG0 [ARG1...]
9703 * On NOMMU, if builtin_argc != 0,
9704 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9705 * "" needs to be replaced with NULL
9706 * and BARGV vector fed to builtin function.
9707 * Note: the form without ARG0 never happens:
9708 * sh ... -c 'builtin' BARGV... ""
9711 G.root_pid = getpid();
9712 G.root_ppid = getppid();
9714 G.global_argv = argv + optind;
9715 G.global_argc = argc - optind;
9717 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9718 const struct built_in_command *x;
9720 install_special_sighandlers();
9721 x = find_builtin(optarg);
9722 if (x) { /* paranoia */
9723 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9724 G.global_argv += builtin_argc;
9725 G.global_argv[-1] = NULL; /* replace "" */
9727 G.last_exitcode = x->b_function(argv + optind - 1);
9731 if (!G.global_argv[0]) {
9732 /* -c 'script' (no params): prevent empty $0 */
9733 G.global_argv--; /* points to argv[i] of 'script' */
9734 G.global_argv[0] = argv[0];
9736 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
9737 install_special_sighandlers();
9738 parse_and_run_string(optarg);
9741 /* Well, we cannot just declare interactiveness,
9742 * we have to have some stuff (ctty, etc) */
9743 /* G_interactive_fd++; */
9752 case '<': /* "big heredoc" support */
9753 full_write1_str(optarg);
9756 unsigned long long empty_trap_mask;
9758 G.root_pid = bb_strtou(optarg, &optarg, 16);
9760 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9762 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9764 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
9766 builtin_argc = bb_strtou(optarg, &optarg, 16);
9768 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9769 if (empty_trap_mask != 0) {
9770 IF_HUSH_TRAP(int sig;)
9771 install_special_sighandlers();
9772 # if ENABLE_HUSH_TRAP
9773 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9774 for (sig = 1; sig < NSIG; sig++) {
9775 if (empty_trap_mask & (1LL << sig)) {
9776 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9777 install_sighandler(sig, SIG_IGN);
9782 # if ENABLE_HUSH_LOOPS
9784 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
9786 # if ENABLE_HUSH_FUNCTIONS
9787 /* nommu uses re-exec trick for "... | func | ...",
9788 * should allow "return".
9789 * This accidentally allows returns in subshells.
9791 G_flag_return_in_progress = -1;
9797 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9799 # if ENABLE_HUSH_FUNCTIONS
9801 struct function *funcp = new_function(optarg);
9802 /* funcp->name is already set to optarg */
9803 /* funcp->body is set to NULL. It's a special case. */
9804 funcp->body_as_string = argv[optind];
9813 if (set_mode(1, opt, NULL) == 0) /* no error */
9817 fprintf(stderr, "Usage: sh [FILE]...\n"
9818 " or: sh -c command [args]...\n\n");
9824 } /* option parsing loop */
9826 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9827 G.global_argc = argc - (optind - 1);
9828 G.global_argv = argv + (optind - 1);
9829 G.global_argv[0] = argv[0];
9832 G.root_pid = getpid();
9833 G.root_ppid = getppid();
9836 /* If we are login shell... */
9837 if (flags & OPT_login) {
9839 debug_printf("sourcing /etc/profile\n");
9840 input = fopen_for_read("/etc/profile");
9841 if (input != NULL) {
9842 remember_FILE(input);
9843 install_special_sighandlers();
9844 parse_and_run_file(input);
9845 fclose_and_forget(input);
9847 /* bash: after sourcing /etc/profile,
9848 * tries to source (in the given order):
9849 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9850 * stopping on first found. --noprofile turns this off.
9851 * bash also sources ~/.bash_logout on exit.
9852 * If called as sh, skips .bash_XXX files.
9856 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9857 if (!(flags & OPT_s) && G.global_argv[1]) {
9860 * "bash <script>" (which is never interactive (unless -i?))
9861 * sources $BASH_ENV here (without scanning $PATH).
9862 * If called as sh, does the same but with $ENV.
9863 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9867 debug_printf("running script '%s'\n", G.global_argv[0]);
9868 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9869 input = xfopen_for_read(G.global_argv[0]);
9870 xfunc_error_retval = 1;
9871 remember_FILE(input);
9872 install_special_sighandlers();
9873 parse_and_run_file(input);
9874 #if ENABLE_FEATURE_CLEAN_UP
9875 fclose_and_forget(input);
9880 /* Up to here, shell was non-interactive. Now it may become one.
9881 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9884 /* A shell is interactive if the '-i' flag was given,
9885 * or if all of the following conditions are met:
9887 * no arguments remaining or the -s flag given
9888 * standard input is a terminal
9889 * standard output is a terminal
9890 * Refer to Posix.2, the description of the 'sh' utility.
9893 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9894 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9895 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9896 if (G_saved_tty_pgrp < 0)
9897 G_saved_tty_pgrp = 0;
9899 /* try to dup stdin to high fd#, >= 255 */
9900 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
9901 if (G_interactive_fd < 0) {
9902 /* try to dup to any fd */
9903 G_interactive_fd = dup(STDIN_FILENO);
9904 if (G_interactive_fd < 0) {
9906 G_interactive_fd = 0;
9907 G_saved_tty_pgrp = 0;
9910 // TODO: track & disallow any attempts of user
9911 // to (inadvertently) close/redirect G_interactive_fd
9913 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9914 if (G_interactive_fd) {
9915 close_on_exec_on(G_interactive_fd);
9917 if (G_saved_tty_pgrp) {
9918 /* If we were run as 'hush &', sleep until we are
9919 * in the foreground (tty pgrp == our pgrp).
9920 * If we get started under a job aware app (like bash),
9921 * make sure we are now in charge so we don't fight over
9922 * who gets the foreground */
9924 pid_t shell_pgrp = getpgrp();
9925 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9926 if (G_saved_tty_pgrp == shell_pgrp)
9928 /* send TTIN to ourself (should stop us) */
9929 kill(- shell_pgrp, SIGTTIN);
9933 /* Install more signal handlers */
9934 install_special_sighandlers();
9936 if (G_saved_tty_pgrp) {
9937 /* Set other signals to restore saved_tty_pgrp */
9938 install_fatal_sighandlers();
9939 /* Put ourselves in our own process group
9940 * (bash, too, does this only if ctty is available) */
9941 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9942 /* Grab control of the terminal */
9943 tcsetpgrp(G_interactive_fd, getpid());
9945 enable_restore_tty_pgrp_on_exit();
9947 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9949 const char *hp = get_local_var_value("HISTFILE");
9951 hp = get_local_var_value("HOME");
9953 hp = concat_path_file(hp, ".hush_history");
9958 G.line_input_state->hist_file = hp;
9959 //set_local_var(xasprintf("HISTFILE=%s", ...));
9961 # if ENABLE_FEATURE_SH_HISTFILESIZE
9962 hp = get_local_var_value("HISTFILESIZE");
9963 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9968 install_special_sighandlers();
9970 #elif ENABLE_HUSH_INTERACTIVE
9971 /* No job control compiled in, only prompt/line editing */
9972 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9973 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
9974 if (G_interactive_fd < 0) {
9975 /* try to dup to any fd */
9976 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
9977 if (G_interactive_fd < 0)
9979 G_interactive_fd = 0;
9982 if (G_interactive_fd) {
9983 close_on_exec_on(G_interactive_fd);
9985 install_special_sighandlers();
9987 /* We have interactiveness code disabled */
9988 install_special_sighandlers();
9991 * if interactive but not a login shell, sources ~/.bashrc
9992 * (--norc turns this off, --rcfile <file> overrides)
9995 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9996 /* note: ash and hush share this string */
9997 printf("\n\n%s %s\n"
9998 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10001 "hush - the humble shell"
10005 parse_and_run_file(stdin);
10008 hush_exit(G.last_exitcode);
10015 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
10020 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
10021 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
10023 int argc = string_array_len(argv);
10024 return applet_main_func(argc, argv);
10027 #if ENABLE_HUSH_TEST || BASH_TEST2
10028 static int FAST_FUNC builtin_test(char **argv)
10030 return run_applet_main(argv, test_main);
10033 #if ENABLE_HUSH_ECHO
10034 static int FAST_FUNC builtin_echo(char **argv)
10036 return run_applet_main(argv, echo_main);
10039 #if ENABLE_HUSH_PRINTF
10040 static int FAST_FUNC builtin_printf(char **argv)
10042 return run_applet_main(argv, printf_main);
10046 #if ENABLE_HUSH_HELP
10047 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10049 const struct built_in_command *x;
10052 "Built-in commands:\n"
10053 "------------------\n");
10054 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10056 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10058 return EXIT_SUCCESS;
10062 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
10063 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10065 show_history(G.line_input_state);
10066 return EXIT_SUCCESS;
10070 static char **skip_dash_dash(char **argv)
10073 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10078 static int FAST_FUNC builtin_cd(char **argv)
10080 const char *newdir;
10082 argv = skip_dash_dash(argv);
10084 if (newdir == NULL) {
10085 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
10086 * bash says "bash: cd: HOME not set" and does nothing
10089 const char *home = get_local_var_value("HOME");
10090 newdir = home ? home : "/";
10092 if (chdir(newdir)) {
10093 /* Mimic bash message exactly */
10094 bb_perror_msg("cd: %s", newdir);
10095 return EXIT_FAILURE;
10097 /* Read current dir (get_cwd(1) is inside) and set PWD.
10098 * Note: do not enforce exporting. If PWD was unset or unexported,
10099 * set it again, but do not export. bash does the same.
10101 set_pwd_var(/*flag:*/ 0);
10102 return EXIT_SUCCESS;
10105 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10108 return EXIT_SUCCESS;
10111 static int FAST_FUNC builtin_eval(char **argv)
10113 argv = skip_dash_dash(argv);
10116 return EXIT_SUCCESS;
10120 * eval "echo Hi; done" ("done" is syntax error):
10121 * "echo Hi" will not execute too.
10123 parse_and_run_string(argv[0]);
10125 /* "The eval utility shall construct a command by
10126 * concatenating arguments together, separating
10127 * each with a <space> character."
10133 len += strlen(*pp) + 1;
10135 str = p = xmalloc(len);
10138 p = stpcpy(p, *pp);
10144 parse_and_run_string(str);
10147 return G.last_exitcode;
10150 static int FAST_FUNC builtin_exec(char **argv)
10152 argv = skip_dash_dash(argv);
10153 if (argv[0] == NULL)
10154 return EXIT_SUCCESS; /* bash does this */
10156 /* Careful: we can end up here after [v]fork. Do not restore
10157 * tty pgrp then, only top-level shell process does that */
10158 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10159 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10161 /* Saved-redirect fds, script fds and G_interactive_fd are still
10162 * open here. However, they are all CLOEXEC, and execv below
10163 * closes them. Try interactive "exec ls -l /proc/self/fd",
10164 * it should show no extra open fds in the "ls" process.
10165 * If we'd try to run builtins/NOEXECs, this would need improving.
10167 //close_saved_fds_and_FILE_fds();
10169 /* TODO: if exec fails, bash does NOT exit! We do.
10170 * We'll need to undo trap cleanup (it's inside execvp_or_die)
10171 * and tcsetpgrp, and this is inherently racy.
10173 execvp_or_die(argv);
10176 static int FAST_FUNC builtin_exit(char **argv)
10178 debug_printf_exec("%s()\n", __func__);
10180 /* interactive bash:
10181 * # trap "echo EEE" EXIT
10184 * There are stopped jobs.
10185 * (if there are _stopped_ jobs, running ones don't count)
10188 * EEE (then bash exits)
10190 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
10193 /* note: EXIT trap is run by hush_exit */
10194 argv = skip_dash_dash(argv);
10195 if (argv[0] == NULL)
10196 hush_exit(G.last_exitcode);
10197 /* mimic bash: exit 123abc == exit 255 + error msg */
10198 xfunc_error_retval = 255;
10199 /* bash: exit -2 == exit 254, no error msg */
10200 hush_exit(xatoi(argv[0]) & 0xff);
10203 #if ENABLE_HUSH_TYPE
10204 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10205 static int FAST_FUNC builtin_type(char **argv)
10207 int ret = EXIT_SUCCESS;
10213 if (0) {} /* make conditional compile easier below */
10214 /*else if (find_alias(*argv))
10215 type = "an alias";*/
10216 #if ENABLE_HUSH_FUNCTIONS
10217 else if (find_function(*argv))
10218 type = "a function";
10220 else if (find_builtin(*argv))
10221 type = "a shell builtin";
10222 else if ((path = find_in_path(*argv)) != NULL)
10225 bb_error_msg("type: %s: not found", *argv);
10226 ret = EXIT_FAILURE;
10230 printf("%s is %s\n", *argv, type);
10238 #if ENABLE_HUSH_READ
10239 /* Interruptibility of read builtin in bash
10240 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10242 * Empty trap makes read ignore corresponding signal, for any signal.
10245 * - terminates non-interactive shell;
10246 * - interrupts read in interactive shell;
10247 * if it has non-empty trap:
10248 * - executes trap and returns to command prompt in interactive shell;
10249 * - executes trap and returns to read in non-interactive shell;
10251 * - is ignored (does not interrupt) read in interactive shell;
10252 * - terminates non-interactive shell;
10253 * if it has non-empty trap:
10254 * - executes trap and returns to read;
10256 * - terminates shell (regardless of interactivity);
10257 * if it has non-empty trap:
10258 * - executes trap and returns to read;
10259 * SIGCHLD from children:
10260 * - does not interrupt read regardless of interactivity:
10261 * try: sleep 1 & read x; echo $x
10263 static int FAST_FUNC builtin_read(char **argv)
10266 char *opt_n = NULL;
10267 char *opt_p = NULL;
10268 char *opt_t = NULL;
10269 char *opt_u = NULL;
10270 char *opt_d = NULL; /* optimized out if !BASH */
10274 /* "!": do not abort on errors.
10275 * Option string must start with "sr" to match BUILTIN_READ_xxx
10277 read_flags = getopt32(argv,
10279 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10281 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10284 if (read_flags == (uint32_t)-1)
10285 return EXIT_FAILURE;
10287 ifs = get_local_var_value("IFS"); /* can be NULL */
10290 r = shell_builtin_read(set_local_var_from_halves,
10301 if ((uintptr_t)r == 1 && errno == EINTR) {
10302 unsigned sig = check_and_run_traps();
10307 if ((uintptr_t)r > 1) {
10308 bb_error_msg("%s", r);
10309 r = (char*)(uintptr_t)1;
10312 return (uintptr_t)r;
10316 #if ENABLE_HUSH_UMASK
10317 static int FAST_FUNC builtin_umask(char **argv)
10324 argv = skip_dash_dash(argv);
10326 mode_t old_mask = mask;
10328 /* numeric umasks are taken as-is */
10329 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10330 if (!isdigit(argv[0][0]))
10332 mask = bb_parse_mode(argv[0], mask);
10333 if (!isdigit(argv[0][0]))
10335 if ((unsigned)mask > 0777) {
10338 * bash: umask: 'q': invalid symbolic mode operator
10339 * bash: umask: 999: octal number out of range
10341 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10346 printf("%04o\n", (unsigned) mask);
10347 /* fall through and restore mask which we set to 0 */
10351 return !rc; /* rc != 0 - success */
10355 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
10356 static void print_escaped(const char *s)
10361 const char *p = strchrnul(s, '\'');
10362 /* print 'xxxx', possibly just '' */
10363 printf("'%.*s'", (int)(p - s), s);
10368 /* s points to '; print "'''...'''" */
10370 do putchar('\''); while (*++s == '\'');
10376 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
10377 static int helper_export_local(char **argv, unsigned flags)
10380 char *name = *argv;
10381 char *name_end = strchrnul(name, '=');
10383 /* So far we do not check that name is valid (TODO?) */
10385 if (*name_end == '\0') {
10386 struct variable *var, **vpp;
10388 vpp = get_ptr_to_local_var(name, name_end - name);
10389 var = vpp ? *vpp : NULL;
10391 if (flags & SETFLAG_UNEXPORT) {
10392 /* export -n NAME (without =VALUE) */
10394 var->flg_export = 0;
10395 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10397 } /* else: export -n NOT_EXISTING_VAR: no-op */
10400 if (flags & SETFLAG_EXPORT) {
10401 /* export NAME (without =VALUE) */
10403 var->flg_export = 1;
10404 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10405 putenv(var->varstr);
10409 if (flags & SETFLAG_MAKE_RO) {
10410 /* readonly NAME (without =VALUE) */
10412 var->flg_read_only = 1;
10416 # if ENABLE_HUSH_LOCAL
10417 /* Is this "local" bltin? */
10418 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
10419 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10420 if (var && var->var_nest_level == lvl) {
10421 /* "local x=abc; ...; local x" - ignore second local decl */
10426 /* Exporting non-existing variable.
10427 * bash does not put it in environment,
10428 * but remembers that it is exported,
10429 * and does put it in env when it is set later.
10430 * We just set it to "" and export.
10432 /* Or, it's "local NAME" (without =VALUE).
10433 * bash sets the value to "".
10435 /* Or, it's "readonly NAME" (without =VALUE).
10436 * bash remembers NAME and disallows its creation
10439 name = xasprintf("%s=", name);
10441 /* (Un)exporting/making local NAME=VALUE */
10442 name = xstrdup(name);
10444 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
10445 if (set_local_var(name, flags))
10446 return EXIT_FAILURE;
10448 return EXIT_SUCCESS;
10452 #if ENABLE_HUSH_EXPORT
10453 static int FAST_FUNC builtin_export(char **argv)
10455 unsigned opt_unexport;
10457 #if ENABLE_HUSH_EXPORT_N
10458 /* "!": do not abort on errors */
10459 opt_unexport = getopt32(argv, "!n");
10460 if (opt_unexport == (uint32_t)-1)
10461 return EXIT_FAILURE;
10468 if (argv[0] == NULL) {
10469 char **e = environ;
10475 /* ash emits: export VAR='VAL'
10476 * bash: declare -x VAR="VAL"
10477 * we follow ash example */
10478 const char *s = *e++;
10479 const char *p = strchr(s, '=');
10481 if (!p) /* wtf? take next variable */
10484 printf("export %.*s", (int)(p - s) + 1, s);
10485 print_escaped(p + 1);
10489 /*fflush_all(); - done after each builtin anyway */
10491 return EXIT_SUCCESS;
10494 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
10498 #if ENABLE_HUSH_LOCAL
10499 static int FAST_FUNC builtin_local(char **argv)
10501 if (G.func_nest_level == 0) {
10502 bb_error_msg("%s: not in a function", argv[0]);
10503 return EXIT_FAILURE; /* bash compat */
10506 /* Since all builtins run in a nested variable level,
10507 * need to use level - 1 here. Or else the variable will be removed at once
10508 * after builtin returns.
10510 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
10514 #if ENABLE_HUSH_READONLY
10515 static int FAST_FUNC builtin_readonly(char **argv)
10518 if (*argv == NULL) {
10519 /* bash: readonly [-p]: list all readonly VARs
10520 * (-p has no effect in bash)
10522 struct variable *e;
10523 for (e = G.top_var; e; e = e->next) {
10524 if (e->flg_read_only) {
10525 //TODO: quote value: readonly VAR='VAL'
10526 printf("readonly %s\n", e->varstr);
10529 return EXIT_SUCCESS;
10531 return helper_export_local(argv, SETFLAG_MAKE_RO);
10535 #if ENABLE_HUSH_UNSET
10536 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10537 static int FAST_FUNC builtin_unset(char **argv)
10542 /* "!": do not abort on errors */
10543 /* "+": stop at 1st non-option */
10544 opts = getopt32(argv, "!+vf");
10545 if (opts == (unsigned)-1)
10546 return EXIT_FAILURE;
10548 bb_error_msg("unset: -v and -f are exclusive");
10549 return EXIT_FAILURE;
10553 ret = EXIT_SUCCESS;
10555 if (!(opts & 2)) { /* not -f */
10556 if (unset_local_var(*argv)) {
10557 /* unset <nonexistent_var> doesn't fail.
10558 * Error is when one tries to unset RO var.
10559 * Message was printed by unset_local_var. */
10560 ret = EXIT_FAILURE;
10563 # if ENABLE_HUSH_FUNCTIONS
10574 #if ENABLE_HUSH_SET
10575 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10576 * built-in 'set' handler
10578 * set [-abCefhmnuvx] [-o option] [argument...]
10579 * set [+abCefhmnuvx] [+o option] [argument...]
10580 * set -- [argument...]
10583 * Implementations shall support the options in both their hyphen and
10584 * plus-sign forms. These options can also be specified as options to sh.
10586 * Write out all variables and their values: set
10587 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10588 * Turn on the -x and -v options: set -xv
10589 * Unset all positional parameters: set --
10590 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10591 * Set the positional parameters to the expansion of x, even if x expands
10592 * with a leading '-' or '+': set -- $x
10594 * So far, we only support "set -- [argument...]" and some of the short names.
10596 static int FAST_FUNC builtin_set(char **argv)
10599 char **pp, **g_argv;
10600 char *arg = *++argv;
10603 struct variable *e;
10604 for (e = G.top_var; e; e = e->next)
10606 return EXIT_SUCCESS;
10610 if (strcmp(arg, "--") == 0) {
10614 if (arg[0] != '+' && arg[0] != '-')
10616 for (n = 1; arg[n]; ++n) {
10617 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10619 if (arg[n] == 'o' && argv[1])
10622 } while ((arg = *++argv) != NULL);
10623 /* Now argv[0] is 1st argument */
10626 return EXIT_SUCCESS;
10629 /* NB: G.global_argv[0] ($0) is never freed/changed */
10630 g_argv = G.global_argv;
10631 if (G.global_args_malloced) {
10637 G.global_args_malloced = 1;
10638 pp = xzalloc(sizeof(pp[0]) * 2);
10639 pp[0] = g_argv[0]; /* retain $0 */
10642 /* This realloc's G.global_argv */
10643 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10645 G.global_argc = 1 + string_array_len(pp + 1);
10647 return EXIT_SUCCESS;
10649 /* Nothing known, so abort */
10651 bb_error_msg("%s: %s: invalid option", "set", arg);
10652 return EXIT_FAILURE;
10656 static int FAST_FUNC builtin_shift(char **argv)
10659 argv = skip_dash_dash(argv);
10661 n = bb_strtou(argv[0], NULL, 10);
10662 if (errno || n < 0) {
10663 /* shared string with ash.c */
10664 bb_error_msg("Illegal number: %s", argv[0]);
10666 * ash aborts in this case.
10667 * bash prints error message and set $? to 1.
10668 * Interestingly, for "shift 99999" bash does not
10669 * print error message, but does set $? to 1
10670 * (and does no shifting at all).
10674 if (n >= 0 && n < G.global_argc) {
10675 if (G_global_args_malloced) {
10678 free(G.global_argv[m++]);
10680 G.global_argc -= n;
10681 memmove(&G.global_argv[1], &G.global_argv[n+1],
10682 G.global_argc * sizeof(G.global_argv[0]));
10683 return EXIT_SUCCESS;
10685 return EXIT_FAILURE;
10688 #if ENABLE_HUSH_GETOPTS
10689 static int FAST_FUNC builtin_getopts(char **argv)
10691 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10694 If a required argument is not found, and getopts is not silent,
10695 a question mark (?) is placed in VAR, OPTARG is unset, and a
10696 diagnostic message is printed. If getopts is silent, then a
10697 colon (:) is placed in VAR and OPTARG is set to the option
10700 Test that VAR is a valid variable name?
10702 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10705 const char *cp, *optstring, *var;
10706 int c, n, exitcode, my_opterr;
10709 optstring = *++argv;
10710 if (!optstring || !(var = *++argv)) {
10711 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10712 return EXIT_FAILURE;
10716 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10718 argv = G.global_argv;
10722 if (optstring[0] != ':') {
10723 cp = get_local_var_value("OPTERR");
10724 /* 0 if "OPTERR=0", 1 otherwise */
10725 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
10728 /* getopts stops on first non-option. Add "+" to force that */
10729 /*if (optstring[0] != '+')*/ {
10730 char *s = alloca(strlen(optstring) + 2);
10731 sprintf(s, "+%s", optstring);
10735 /* Naively, now we should just
10736 * cp = get_local_var_value("OPTIND");
10737 * optind = cp ? atoi(cp) : 0;
10739 * opterr = my_opterr;
10740 * c = getopt(string_array_len(argv), argv, optstring);
10741 * and be done? Not so fast...
10742 * Unlike normal getopt() usage in C programs, here
10743 * each successive call will (usually) have the same argv[] CONTENTS,
10744 * but not the ADDRESSES. Worse yet, it's possible that between
10745 * invocations of "getopts", there will be calls to shell builtins
10746 * which use getopt() internally. Example:
10747 * while getopts "abc" RES -a -bc -abc de; do
10750 * This would not work correctly: getopt() call inside "unset"
10751 * modifies internal libc state which is tracking position in
10752 * multi-option strings ("-abc"). At best, it can skip options
10753 * or return the same option infinitely. With glibc implementation
10754 * of getopt(), it would use outright invalid pointers and return
10755 * garbage even _without_ "unset" mangling internal state.
10757 * We resort to resetting getopt() state and calling it N times,
10758 * until we get Nth result (or failure).
10759 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10763 n = string_array_len(argv);
10766 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10767 c = getopt(n, argv, optstring);
10771 } while (count <= G.getopt_count);
10773 /* Set OPTIND. Prevent resetting of the magic counter! */
10774 set_local_var_from_halves("OPTIND", utoa(optind));
10775 G.getopt_count = count; /* "next time, give me N+1'th result" */
10776 GETOPT_RESET(); /* just in case */
10779 /* Always set or unset, never left as-is, even on exit/error:
10780 * "If no option was found, or if the option that was found
10781 * does not have an option-argument, OPTARG shall be unset."
10785 /* If ":optstring" and unknown option is seen,
10786 * it is stored to OPTARG.
10788 if (optstring[1] == ':') {
10794 set_local_var_from_halves("OPTARG", cp);
10796 unset_local_var("OPTARG");
10798 /* Convert -1 to "?" */
10799 exitcode = EXIT_SUCCESS;
10800 if (c < 0) { /* -1: end of options */
10801 exitcode = EXIT_FAILURE;
10807 set_local_var_from_halves(var, cbuf);
10813 static int FAST_FUNC builtin_source(char **argv)
10815 char *arg_path, *filename;
10818 char *args_need_save;
10819 #if ENABLE_HUSH_FUNCTIONS
10823 argv = skip_dash_dash(argv);
10824 filename = argv[0];
10826 /* bash says: "bash: .: filename argument required" */
10827 return 2; /* bash compat */
10830 if (!strchr(filename, '/')) {
10831 arg_path = find_in_path(filename);
10833 filename = arg_path;
10834 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
10836 bb_simple_perror_msg(filename);
10837 return EXIT_FAILURE;
10840 input = remember_FILE(fopen_or_warn(filename, "r"));
10843 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10844 /* POSIX: non-interactive shell should abort here,
10845 * not merely fail. So far no one complained :)
10847 return EXIT_FAILURE;
10850 #if ENABLE_HUSH_FUNCTIONS
10851 sv_flg = G_flag_return_in_progress;
10852 /* "we are inside sourced file, ok to use return" */
10853 G_flag_return_in_progress = -1;
10855 args_need_save = argv[1]; /* used as a boolean variable */
10856 if (args_need_save)
10857 save_and_replace_G_args(&sv, argv);
10859 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10860 G.last_exitcode = 0;
10861 parse_and_run_file(input);
10862 fclose_and_forget(input);
10864 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10865 restore_G_args(&sv, argv);
10866 #if ENABLE_HUSH_FUNCTIONS
10867 G_flag_return_in_progress = sv_flg;
10870 return G.last_exitcode;
10873 #if ENABLE_HUSH_TRAP
10874 static int FAST_FUNC builtin_trap(char **argv)
10880 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10885 /* No args: print all trapped */
10886 for (i = 0; i < NSIG; ++i) {
10888 printf("trap -- ");
10889 print_escaped(G_traps[i]);
10890 /* note: bash adds "SIG", but only if invoked
10891 * as "bash". If called as "sh", or if set -o posix,
10892 * then it prints short signal names.
10893 * We are printing short names: */
10894 printf(" %s\n", get_signame(i));
10897 /*fflush_all(); - done after each builtin anyway */
10898 return EXIT_SUCCESS;
10902 /* If first arg is a number: reset all specified signals */
10903 sig = bb_strtou(*argv, NULL, 10);
10907 ret = EXIT_SUCCESS;
10909 sighandler_t handler;
10911 sig = get_signum(*argv++);
10913 ret = EXIT_FAILURE;
10914 /* Mimic bash message exactly */
10915 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
10919 free(G_traps[sig]);
10920 G_traps[sig] = xstrdup(new_cmd);
10922 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
10923 get_signame(sig), sig, G_traps[sig]);
10925 /* There is no signal for 0 (EXIT) */
10930 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10932 /* We are removing trap handler */
10933 handler = pick_sighandler(sig);
10934 install_sighandler(sig, handler);
10939 if (!argv[1]) { /* no second arg */
10940 bb_error_msg("trap: invalid arguments");
10941 return EXIT_FAILURE;
10944 /* First arg is "-": reset all specified to default */
10945 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10946 /* Everything else: set arg as signal handler
10947 * (includes "" case, which ignores signal) */
10948 if (argv[0][0] == '-') {
10949 if (argv[0][1] == '\0') { /* "-" */
10950 /* new_cmd remains NULL: "reset these sigs" */
10953 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10956 /* else: "-something", no special meaning */
10961 goto process_sig_list;
10965 #if ENABLE_HUSH_JOB
10966 static struct pipe *parse_jobspec(const char *str)
10971 if (sscanf(str, "%%%u", &jobnum) != 1) {
10973 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10975 bb_error_msg("bad argument '%s'", str);
10978 /* It is "%%", "%+" or "%" - current job */
10979 jobnum = G.last_jobid;
10981 bb_error_msg("no current job");
10985 for (pi = G.job_list; pi; pi = pi->next) {
10986 if (pi->jobid == jobnum) {
10990 bb_error_msg("%u: no such job", jobnum);
10994 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10997 const char *status_string;
10999 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11000 for (job = G.job_list; job; job = job->next) {
11001 if (job->alive_cmds == job->stopped_cmds)
11002 status_string = "Stopped";
11004 status_string = "Running";
11006 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11009 clean_up_last_dead_job();
11011 return EXIT_SUCCESS;
11014 /* built-in 'fg' and 'bg' handler */
11015 static int FAST_FUNC builtin_fg_bg(char **argv)
11020 if (!G_interactive_fd)
11021 return EXIT_FAILURE;
11023 /* If they gave us no args, assume they want the last backgrounded task */
11025 for (pi = G.job_list; pi; pi = pi->next) {
11026 if (pi->jobid == G.last_jobid) {
11030 bb_error_msg("%s: no current job", argv[0]);
11031 return EXIT_FAILURE;
11034 pi = parse_jobspec(argv[1]);
11036 return EXIT_FAILURE;
11038 /* TODO: bash prints a string representation
11039 * of job being foregrounded (like "sleep 1 | cat") */
11040 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
11041 /* Put the job into the foreground. */
11042 tcsetpgrp(G_interactive_fd, pi->pgrp);
11045 /* Restart the processes in the job */
11046 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11047 for (i = 0; i < pi->num_cmds; i++) {
11048 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
11050 pi->stopped_cmds = 0;
11052 i = kill(- pi->pgrp, SIGCONT);
11054 if (errno == ESRCH) {
11055 delete_finished_job(pi);
11056 return EXIT_SUCCESS;
11058 bb_perror_msg("kill (SIGCONT)");
11061 if (argv[0][0] == 'f') {
11062 remove_job_from_table(pi); /* FG job shouldn't be in job table */
11063 return checkjobs_and_fg_shell(pi);
11065 return EXIT_SUCCESS;
11069 #if ENABLE_HUSH_KILL
11070 static int FAST_FUNC builtin_kill(char **argv)
11074 # if ENABLE_HUSH_JOB
11075 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11083 if (argv[i][0] != '%')
11086 * "kill %N" - job kill
11087 * Converting to pgrp / pid kill
11089 pi = parse_jobspec(argv[i]);
11091 /* Eat bad jobspec */
11095 argv[j - 1] = argv[j];
11102 * In jobs started under job control, we signal
11103 * entire process group by kill -PGRP_ID.
11104 * This happens, f.e., in interactive shell.
11106 * Otherwise, we signal each child via
11107 * kill PID1 PID2 PID3.
11109 * sh -c 'sleep 1|sleep 1 & kill %1'
11110 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11111 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11113 n = G_interactive_fd ? 1 : pi->num_cmds;
11114 dst = alloca(n * sizeof(int)*4);
11116 if (G_interactive_fd)
11117 dst += sprintf(dst, " -%u", (int)pi->pgrp);
11118 else for (j = 0; j < n; j++) {
11119 struct command *cmd = &pi->cmds[j];
11120 /* Skip exited members of the job */
11124 * kill_main has matching code to expect
11125 * leading space. Needed to not confuse
11126 * negative pids with "kill -SIGNAL_NO" syntax
11128 dst += sprintf(dst, " %u", (int)cmd->pid);
11131 } while (argv[++i]);
11135 if (argv[1] || ret == 0) {
11136 ret = run_applet_main(argv, kill_main);
11138 /* else: ret = 1, "kill %bad_jobspec" case */
11143 #if ENABLE_HUSH_WAIT
11144 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
11145 #if !ENABLE_HUSH_JOB
11146 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11148 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
11155 if (!sigisemptyset(&G.pending_set))
11158 /* waitpid is not interruptible by SA_RESTARTed
11159 * signals which we use. Thus, this ugly dance:
11162 /* Make sure possible SIGCHLD is stored in kernel's
11163 * pending signal mask before we call waitpid.
11164 * Or else we may race with SIGCHLD, lose it,
11165 * and get stuck in sigsuspend...
11167 sigfillset(&oldset); /* block all signals, remember old set */
11168 sigprocmask(SIG_SETMASK, &oldset, &oldset);
11170 if (!sigisemptyset(&G.pending_set)) {
11171 /* Crap! we raced with some signal! */
11175 /*errno = 0; - checkjobs does this */
11176 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
11177 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
11178 debug_printf_exec("checkjobs:%d\n", ret);
11179 #if ENABLE_HUSH_JOB
11180 if (waitfor_pipe) {
11181 int rcode = job_exited_or_stopped(waitfor_pipe);
11182 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11185 sigprocmask(SIG_SETMASK, &oldset, NULL);
11190 /* if ECHILD, there are no children (ret is -1 or 0) */
11191 /* if ret == 0, no children changed state */
11192 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
11193 if (errno == ECHILD || ret) {
11195 if (ret < 0) /* if ECHILD, may need to fix "ret" */
11197 sigprocmask(SIG_SETMASK, &oldset, NULL);
11200 /* Wait for SIGCHLD or any other signal */
11201 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11202 /* Note: sigsuspend invokes signal handler */
11203 sigsuspend(&oldset);
11205 sigprocmask(SIG_SETMASK, &oldset, NULL);
11207 /* So, did we get a signal? */
11208 sig = check_and_run_traps();
11209 if (sig /*&& sig != SIGCHLD - always true */) {
11210 /* Do this for any (non-ignored) signal, not only for ^C */
11214 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11219 static int FAST_FUNC builtin_wait(char **argv)
11224 argv = skip_dash_dash(argv);
11225 if (argv[0] == NULL) {
11226 /* Don't care about wait results */
11227 /* Note 1: must wait until there are no more children */
11228 /* Note 2: must be interruptible */
11230 * $ sleep 3 & sleep 6 & wait
11231 * [1] 30934 sleep 3
11232 * [2] 30935 sleep 6
11235 * $ sleep 3 & sleep 6 & wait
11236 * [1] 30936 sleep 3
11237 * [2] 30937 sleep 6
11239 * ^C <-- after ~4 sec from keyboard
11242 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
11246 pid_t pid = bb_strtou(*argv, NULL, 10);
11247 if (errno || pid <= 0) {
11248 #if ENABLE_HUSH_JOB
11249 if (argv[0][0] == '%') {
11250 struct pipe *wait_pipe;
11251 ret = 127; /* bash compat for bad jobspecs */
11252 wait_pipe = parse_jobspec(*argv);
11254 ret = job_exited_or_stopped(wait_pipe);
11256 ret = wait_for_child_or_signal(wait_pipe, 0);
11258 /* waiting on "last dead job" removes it */
11259 clean_up_last_dead_job();
11262 /* else: parse_jobspec() already emitted error msg */
11266 /* mimic bash message */
11267 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
11268 ret = EXIT_FAILURE;
11269 continue; /* bash checks all argv[] */
11272 /* Do we have such child? */
11273 ret = waitpid(pid, &status, WNOHANG);
11277 if (errno == ECHILD) {
11278 if (pid == G.last_bg_pid) {
11279 /* "wait $!" but last bg task has already exited. Try:
11280 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11281 * In bash it prints exitcode 0, then 3.
11282 * In dash, it is 127.
11284 ret = G.last_bg_pid_exitcode;
11286 /* Example: "wait 1". mimic bash message */
11287 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
11291 bb_perror_msg("wait %s", *argv);
11293 continue; /* bash checks all argv[] */
11296 /* Yes, and it still runs */
11297 ret = wait_for_child_or_signal(NULL, pid);
11299 /* Yes, and it just exited */
11300 process_wait_result(NULL, pid, status);
11301 ret = WEXITSTATUS(status);
11302 if (WIFSIGNALED(status))
11303 ret = 128 + WTERMSIG(status);
11311 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11312 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11315 def = bb_strtou(argv[1], NULL, 10);
11316 if (errno || def < def_min || argv[2]) {
11317 bb_error_msg("%s: bad arguments", argv[0]);
11325 #if ENABLE_HUSH_LOOPS
11326 static int FAST_FUNC builtin_break(char **argv)
11329 if (G.depth_of_loop == 0) {
11330 bb_error_msg("%s: only meaningful in a loop", argv[0]);
11331 /* if we came from builtin_continue(), need to undo "= 1" */
11332 G.flag_break_continue = 0;
11333 return EXIT_SUCCESS; /* bash compat */
11335 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
11337 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11338 if (depth == UINT_MAX)
11339 G.flag_break_continue = BC_BREAK;
11340 if (G.depth_of_loop < depth)
11341 G.depth_break_continue = G.depth_of_loop;
11343 return EXIT_SUCCESS;
11346 static int FAST_FUNC builtin_continue(char **argv)
11348 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11349 return builtin_break(argv);
11353 #if ENABLE_HUSH_FUNCTIONS
11354 static int FAST_FUNC builtin_return(char **argv)
11358 if (G_flag_return_in_progress != -1) {
11359 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11360 return EXIT_FAILURE; /* bash compat */
11363 G_flag_return_in_progress = 1;
11366 * out of range: wraps around at 256, does not error out
11367 * non-numeric param:
11368 * f() { false; return qwe; }; f; echo $?
11369 * bash: return: qwe: numeric argument required <== we do this
11370 * 255 <== we also do this
11372 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11377 #if ENABLE_HUSH_TIMES
11378 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11380 static const uint8_t times_tbl[] ALIGN1 = {
11381 ' ', offsetof(struct tms, tms_utime),
11382 '\n', offsetof(struct tms, tms_stime),
11383 ' ', offsetof(struct tms, tms_cutime),
11384 '\n', offsetof(struct tms, tms_cstime),
11391 clk_tck = bb_clk_tck();
11396 unsigned sec, frac;
11398 t = *(clock_t *)(((char *) &buf) + p[1]);
11400 frac = t % clk_tck;
11401 printf("%um%u.%03us%c",
11402 sec / 60, sec % 60,
11403 (frac * 1000) / clk_tck,
11408 return EXIT_SUCCESS;
11412 #if ENABLE_HUSH_MEMLEAK
11413 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11418 # ifdef M_TRIM_THRESHOLD
11419 /* Optional. Reduces probability of false positives */
11422 /* Crude attempt to find where "free memory" starts,
11423 * sans fragmentation. */
11425 l = (unsigned long)p;
11428 if (l < (unsigned long)p) l = (unsigned long)p;
11434 struct mallinfo mi = mallinfo();
11435 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11436 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11440 if (!G.memleak_value)
11441 G.memleak_value = l;
11443 l -= G.memleak_value;
11450 /* Exitcode is "how many kilobytes we leaked since 1st call" */