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 (68 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 command 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)
363 #ifndef F_DUPFD_CLOEXEC
364 # define F_DUPFD_CLOEXEC F_DUPFD
367 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
370 #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
371 # include "embedded_scripts.h"
373 # define NUM_SCRIPTS 0
376 /* So far, all bash compat is controlled by one config option */
377 /* Separate defines document which part of code implements what */
378 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
379 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
380 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
381 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
382 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
383 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
387 #define LEAK_HUNTING 0
388 #define BUILD_AS_NOMMU 0
389 /* Enable/disable sanity checks. Ok to enable in production,
390 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
391 * Keeping 1 for now even in released versions.
394 /* Slightly bigger (+200 bytes), but faster hush.
395 * So far it only enables a trick with counting SIGCHLDs and forks,
396 * which allows us to do fewer waitpid's.
397 * (we can detect a case where neither forks were done nor SIGCHLDs happened
398 * and therefore waitpid will return the same result as last time)
400 #define ENABLE_HUSH_FAST 0
401 /* TODO: implement simplified code for users which do not need ${var%...} ops
402 * So far ${var%...} ops are always enabled:
404 #define ENABLE_HUSH_DOLLAR_OPS 1
409 # undef USE_FOR_NOMMU
412 # define USE_FOR_NOMMU(...) __VA_ARGS__
413 # define USE_FOR_MMU(...)
416 #include "NUM_APPLETS.h"
418 /* STANDALONE does not make sense, and won't compile */
419 # undef CONFIG_FEATURE_SH_STANDALONE
420 # undef ENABLE_FEATURE_SH_STANDALONE
421 # undef IF_FEATURE_SH_STANDALONE
422 # undef IF_NOT_FEATURE_SH_STANDALONE
423 # define ENABLE_FEATURE_SH_STANDALONE 0
424 # define IF_FEATURE_SH_STANDALONE(...)
425 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
428 #if !ENABLE_HUSH_INTERACTIVE
429 # undef ENABLE_FEATURE_EDITING
430 # define ENABLE_FEATURE_EDITING 0
431 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
432 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
433 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
434 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
437 /* Do we support ANY keywords? */
438 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
439 # define HAS_KEYWORDS 1
440 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
441 # define IF_HAS_NO_KEYWORDS(...)
443 # define HAS_KEYWORDS 0
444 # define IF_HAS_KEYWORDS(...)
445 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
448 /* If you comment out one of these below, it will be #defined later
449 * to perform debug printfs to stderr: */
450 #define debug_printf(...) do {} while (0)
451 /* Finer-grained debug switches */
452 #define debug_printf_parse(...) do {} while (0)
453 #define debug_printf_heredoc(...) do {} while (0)
454 #define debug_print_tree(a, b) do {} while (0)
455 #define debug_printf_exec(...) do {} while (0)
456 #define debug_printf_env(...) do {} while (0)
457 #define debug_printf_jobs(...) do {} while (0)
458 #define debug_printf_expand(...) do {} while (0)
459 #define debug_printf_varexp(...) do {} while (0)
460 #define debug_printf_glob(...) do {} while (0)
461 #define debug_printf_redir(...) do {} while (0)
462 #define debug_printf_list(...) do {} while (0)
463 #define debug_printf_subst(...) do {} while (0)
464 #define debug_printf_prompt(...) do {} while (0)
465 #define debug_printf_clean(...) do {} while (0)
467 #define ERR_PTR ((void*)(long)1)
469 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
471 #define _SPECIAL_VARS_STR "_*@$!?#"
472 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
473 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
474 #if BASH_PATTERN_SUBST
475 /* Support / and // replace ops */
476 /* Note that // is stored as \ in "encoded" string representation */
477 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
478 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
479 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
481 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
482 # define VAR_SUBST_OPS "%#:-=+?"
483 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
486 #define SPECIAL_VAR_SYMBOL_STR "\3"
487 #define SPECIAL_VAR_SYMBOL 3
488 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
489 #define SPECIAL_VAR_QUOTED_SVS 1
493 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
495 /* This supports saving pointers malloced in vfork child,
496 * to be freed in the parent.
499 typedef struct nommu_save_t {
500 struct variable *old_vars;
502 char **argv_from_re_execing;
515 #if ENABLE_HUSH_LOOPS
522 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
527 /* three pseudo-keywords support contrived "case" syntax: */
528 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
529 RES_MATCH , /* "word)" */
530 RES_CASE_BODY, /* "this command is inside CASE" */
537 typedef struct o_string {
539 int length; /* position where data is appended */
542 /* At least some part of the string was inside '' or "",
543 * possibly empty one: word"", wo''rd etc. */
544 smallint has_quoted_part;
545 smallint has_empty_slot;
546 smallint ended_in_ifs;
549 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
551 /* Protect newly added chars against globbing
552 * by prepending \ to *, ?, [, \ */
553 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
555 /* Used for initialization: o_string foo = NULL_O_STRING; */
556 #define NULL_O_STRING { NULL }
558 #ifndef debug_printf_parse
559 static const char *const assignment_flag[] = {
561 "DEFINITELY_ASSIGNMENT",
567 /* We almost can use standard FILE api, but we need an ability to move
568 * its fd when redirects coincide with it. No api exists for that
569 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
570 * HFILE is our internal alternative. Only supports reading.
571 * Since we now can, we incorporate linked list of all opened HFILEs
572 * into the struct (used to be a separate mini-list).
574 typedef struct HFILE {
577 struct HFILE *next_hfile;
583 typedef struct in_str {
590 /* The descrip member of this structure is only used to make
591 * debugging output pretty */
592 static const struct {
594 signed char default_fd;
597 { O_RDONLY, 0, "<" },
598 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
599 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
600 { O_CREAT|O_RDWR, 1, "<>" },
601 { O_RDONLY, 0, "<<" },
602 /* Should not be needed. Bogus default_fd helps in debugging */
603 /* { O_RDONLY, 77, "<<" }, */
606 struct redir_struct {
607 struct redir_struct *next;
608 char *rd_filename; /* filename */
609 int rd_fd; /* fd to redirect */
610 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
612 smallint rd_type; /* (enum redir_type) */
613 /* note: for heredocs, rd_filename contains heredoc delimiter,
614 * and subsequently heredoc itself; and rd_dup is a bitmask:
615 * bit 0: do we need to trim leading tabs?
616 * bit 1: is heredoc quoted (<<'delim' syntax) ?
619 typedef enum redir_type {
621 REDIRECT_OVERWRITE = 1,
624 REDIRECT_HEREDOC = 4,
625 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
628 REDIRFD_SYNTAX_ERR = -2,
629 REDIRFD_TO_FILE = -1,
630 /* otherwise, rd_fd is redirected to rd_dup */
632 HEREDOC_SKIPTABS = 1,
638 pid_t pid; /* 0 if exited */
639 unsigned assignment_cnt; /* how many argv[i] are assignments? */
640 #if ENABLE_HUSH_LINENO_VAR
643 smallint cmd_type; /* CMD_xxx */
645 #define CMD_SUBSHELL 1
646 #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
647 /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
650 # define CMD_SINGLEWORD_NOGLOB 2
652 #if ENABLE_HUSH_FUNCTIONS
653 # define CMD_FUNCDEF 3
656 smalluint cmd_exitcode;
657 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
660 char *group_as_string;
662 #if ENABLE_HUSH_FUNCTIONS
663 struct function *child_func;
664 /* This field is used to prevent a bug here:
665 * while...do f1() {a;}; f1; f1() {b;}; f1; done
666 * When we execute "f1() {a;}" cmd, we create new function and clear
667 * cmd->group, cmd->group_as_string, cmd->argv[0].
668 * When we execute "f1() {b;}", we notice that f1 exists,
669 * and that its "parent cmd" struct is still "alive",
670 * we put those fields back into cmd->xxx
671 * (struct function has ->parent_cmd ptr to facilitate that).
672 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
673 * Without this trick, loop would execute a;b;b;b;...
674 * instead of correct sequence a;b;a;b;...
675 * When command is freed, it severs the link
676 * (sets ->child_func->parent_cmd to NULL).
679 char **argv; /* command name and arguments */
680 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
681 * and on execution these are substituted with their values.
682 * Substitution can make _several_ words out of one argv[n]!
683 * Example: argv[0]=='.^C*^C.' here: echo .$*.
684 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
686 struct redir_struct *redirects; /* I/O redirections */
688 /* Is there anything in this command at all? */
689 #define IS_NULL_CMD(cmd) \
690 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
694 int num_cmds; /* total number of commands in pipe */
695 int alive_cmds; /* number of commands running (not exited) */
696 int stopped_cmds; /* number of commands alive, but stopped */
698 unsigned jobid; /* job number */
699 pid_t pgrp; /* process group ID for the job */
700 char *cmdtext; /* name of job */
702 struct command *cmds; /* array of commands in pipe */
703 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
704 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
705 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
707 typedef enum pipe_style {
713 /* Is there anything in this pipe at all? */
714 #define IS_NULL_PIPE(pi) \
715 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
717 /* This holds pointers to the various results of parsing */
718 struct parse_context {
719 /* linked list of pipes */
720 struct pipe *list_head;
721 /* last pipe (being constructed right now) */
723 /* last command in pipe (being constructed right now) */
724 struct command *command;
725 /* last redirect in command->redirects list */
726 struct redir_struct *pending_redirect;
731 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
734 smallint ctx_inverted; /* "! cmd | cmd" */
736 smallint ctx_dsemicolon; /* ";;" seen */
738 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
740 /* group we are enclosed in:
741 * example: "if pipe1; pipe2; then pipe3; fi"
742 * when we see "if" or "then", we malloc and copy current context,
743 * and make ->stack point to it. then we parse pipeN.
744 * when closing "then" / fi" / whatever is found,
745 * we move list_head into ->stack->command->group,
746 * copy ->stack into current context, and delete ->stack.
747 * (parsing of { list } and ( list ) doesn't use this method)
749 struct parse_context *stack;
753 MAYBE_ASSIGNMENT = 0,
754 DEFINITELY_ASSIGNMENT = 1,
756 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
760 /* On program start, environ points to initial environment.
761 * putenv adds new pointers into it, unsetenv removes them.
762 * Neither of these (de)allocates the strings.
763 * setenv allocates new strings in malloc space and does putenv,
764 * and thus setenv is unusable (leaky) for shell's purposes */
765 #define setenv(...) setenv_is_leaky_dont_use()
767 struct variable *next;
768 char *varstr; /* points to "name=" portion */
769 int max_len; /* if > 0, name is part of initial env; else name is malloced */
770 uint16_t var_nest_level;
771 smallint flg_export; /* putenv should be done on this var */
772 smallint flg_read_only;
780 #if ENABLE_HUSH_FUNCTIONS
782 struct function *next;
784 struct command *parent_cmd;
787 char *body_as_string;
793 /* set -/+o OPT support. (TODO: make it optional)
794 * bash supports the following opts:
805 * interactive-comments on
823 static const char o_opt_strings[] ALIGN1 =
827 #if ENABLE_HUSH_MODE_X
835 #if ENABLE_HUSH_MODE_X
841 /* "Globals" within this file */
842 /* Sorted roughly by size (smaller offsets == smaller code) */
844 /* interactive_fd != 0 means we are an interactive shell.
845 * If we are, then saved_tty_pgrp can also be != 0, meaning
846 * that controlling tty is available. With saved_tty_pgrp == 0,
847 * job control still works, but terminal signals
848 * (^C, ^Z, ^Y, ^\) won't work at all, and background
849 * process groups can only be created with "cmd &".
850 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
851 * to give tty to the foreground process group,
852 * and will take it back when the group is stopped (^Z)
855 #if ENABLE_HUSH_INTERACTIVE
856 /* 'interactive_fd' is a fd# open to ctty, if we have one
857 * _AND_ if we decided to act interactively */
860 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
861 # define G_interactive_fd (G.interactive_fd)
863 # define G_interactive_fd 0
865 #if ENABLE_FEATURE_EDITING
866 line_input_t *line_input_state;
871 #if ENABLE_HUSH_RANDOM_SUPPORT
877 pid_t saved_tty_pgrp;
878 struct pipe *job_list;
879 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
881 # define G_saved_tty_pgrp 0
883 /* How deeply are we in context where "set -e" is ignored */
885 /* "set -e" rules (do we follow them correctly?):
886 * Exit if pipe, list, or compound command exits with a non-zero status.
887 * Shell does not exit if failed command is part of condition in
888 * if/while, part of && or || list except the last command, any command
889 * in a pipe but the last, or if the command's return value is being
890 * inverted with !. If a compound command other than a subshell returns a
891 * non-zero status because a command failed while -e was being ignored, the
892 * shell does not exit. A trap on ERR, if set, is executed before the shell
893 * exits [ERR is a bashism].
895 * If a compound command or function executes in a context where -e is
896 * ignored, none of the commands executed within are affected by the -e
897 * setting. If a compound command or function sets -e while executing in a
898 * context where -e is ignored, that setting does not have any effect until
899 * the compound command or the command containing the function call completes.
902 char o_opt[NUM_OPT_O];
903 #if ENABLE_HUSH_MODE_X
904 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
908 #if ENABLE_HUSH_INTERACTIVE
909 smallint promptmode; /* 0: PS1, 1: PS2 */
911 smallint flag_SIGINT;
912 #if ENABLE_HUSH_LOOPS
913 smallint flag_break_continue;
915 #if ENABLE_HUSH_FUNCTIONS
916 /* 0: outside of a function (or sourced file)
917 * -1: inside of a function, ok to use return builtin
918 * 1: return is invoked, skip all till end of func
920 smallint flag_return_in_progress;
921 # define G_flag_return_in_progress (G.flag_return_in_progress)
923 # define G_flag_return_in_progress 0
925 smallint exiting; /* used to prevent EXIT trap recursion */
926 /* These support $?, $#, and $1 */
927 smalluint last_exitcode;
928 smalluint expand_exitcode;
929 smalluint last_bg_pid_exitcode;
931 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
932 smalluint global_args_malloced;
933 # define G_global_args_malloced (G.global_args_malloced)
935 # define G_global_args_malloced 0
937 /* how many non-NULL argv's we have. NB: $# + 1 */
941 char *argv0_for_re_execing;
943 #if ENABLE_HUSH_LOOPS
944 unsigned depth_break_continue;
945 unsigned depth_of_loop;
947 #if ENABLE_HUSH_GETOPTS
948 unsigned getopt_count;
951 char *ifs_whitespace; /* = G.ifs or malloced */
953 struct variable *top_var;
954 char **expanded_assignments;
955 struct variable **shadowed_vars_pp;
956 unsigned var_nest_level;
957 #if ENABLE_HUSH_FUNCTIONS
958 # if ENABLE_HUSH_LOCAL
959 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
961 struct function *top_func;
963 /* Signal and trap handling */
965 unsigned count_SIGCHLD;
966 unsigned handled_SIGCHLD;
967 smallint we_have_children;
969 #if ENABLE_HUSH_LINENO_VAR
974 /* Which signals have non-DFL handler (even with no traps set)?
975 * Set at the start to:
976 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
977 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
978 * The rest is cleared right before execv syscalls.
979 * Other than these two times, never modified.
981 unsigned special_sig_mask;
983 unsigned fatal_sig_mask;
984 # define G_fatal_sig_mask (G.fatal_sig_mask)
986 # define G_fatal_sig_mask 0
989 char **traps; /* char *traps[NSIG] */
990 # define G_traps G.traps
992 # define G_traps ((char**)NULL)
994 sigset_t pending_set;
995 #if ENABLE_HUSH_MEMLEAK
996 unsigned long memleak_value;
998 #if ENABLE_HUSH_MODE_X
999 unsigned x_mode_depth;
1000 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1001 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1002 * for all subsequent output.
1005 o_string x_mode_buf;
1010 struct sigaction sa;
1011 #if ENABLE_FEATURE_EDITING
1012 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1015 #define G (*ptr_to_globals)
1016 /* Not #defining name to G.name - this quickly gets unwieldy
1017 * (too many defines). Also, I actually prefer to see when a variable
1018 * is global, thus "G." prefix is a useful hint */
1019 #define INIT_G() do { \
1020 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
1021 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1022 sigfillset(&G.sa.sa_mask); \
1023 G.sa.sa_flags = SA_RESTART; \
1027 /* Function prototypes for builtins */
1028 static int builtin_cd(char **argv) FAST_FUNC;
1029 #if ENABLE_HUSH_ECHO
1030 static int builtin_echo(char **argv) FAST_FUNC;
1032 static int builtin_eval(char **argv) FAST_FUNC;
1033 static int builtin_exec(char **argv) FAST_FUNC;
1034 static int builtin_exit(char **argv) FAST_FUNC;
1035 #if ENABLE_HUSH_EXPORT
1036 static int builtin_export(char **argv) FAST_FUNC;
1038 #if ENABLE_HUSH_READONLY
1039 static int builtin_readonly(char **argv) FAST_FUNC;
1042 static int builtin_fg_bg(char **argv) FAST_FUNC;
1043 static int builtin_jobs(char **argv) FAST_FUNC;
1045 #if ENABLE_HUSH_GETOPTS
1046 static int builtin_getopts(char **argv) FAST_FUNC;
1048 #if ENABLE_HUSH_HELP
1049 static int builtin_help(char **argv) FAST_FUNC;
1051 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1052 static int builtin_history(char **argv) FAST_FUNC;
1054 #if ENABLE_HUSH_LOCAL
1055 static int builtin_local(char **argv) FAST_FUNC;
1057 #if ENABLE_HUSH_MEMLEAK
1058 static int builtin_memleak(char **argv) FAST_FUNC;
1060 #if ENABLE_HUSH_PRINTF
1061 static int builtin_printf(char **argv) FAST_FUNC;
1063 static int builtin_pwd(char **argv) FAST_FUNC;
1064 #if ENABLE_HUSH_READ
1065 static int builtin_read(char **argv) FAST_FUNC;
1068 static int builtin_set(char **argv) FAST_FUNC;
1070 static int builtin_shift(char **argv) FAST_FUNC;
1071 static int builtin_source(char **argv) FAST_FUNC;
1072 #if ENABLE_HUSH_TEST || BASH_TEST2
1073 static int builtin_test(char **argv) FAST_FUNC;
1075 #if ENABLE_HUSH_TRAP
1076 static int builtin_trap(char **argv) FAST_FUNC;
1078 #if ENABLE_HUSH_TYPE
1079 static int builtin_type(char **argv) FAST_FUNC;
1081 #if ENABLE_HUSH_TIMES
1082 static int builtin_times(char **argv) FAST_FUNC;
1084 static int builtin_true(char **argv) FAST_FUNC;
1085 #if ENABLE_HUSH_UMASK
1086 static int builtin_umask(char **argv) FAST_FUNC;
1088 #if ENABLE_HUSH_UNSET
1089 static int builtin_unset(char **argv) FAST_FUNC;
1091 #if ENABLE_HUSH_KILL
1092 static int builtin_kill(char **argv) FAST_FUNC;
1094 #if ENABLE_HUSH_WAIT
1095 static int builtin_wait(char **argv) FAST_FUNC;
1097 #if ENABLE_HUSH_LOOPS
1098 static int builtin_break(char **argv) FAST_FUNC;
1099 static int builtin_continue(char **argv) FAST_FUNC;
1101 #if ENABLE_HUSH_FUNCTIONS
1102 static int builtin_return(char **argv) FAST_FUNC;
1105 /* Table of built-in functions. They can be forked or not, depending on
1106 * context: within pipes, they fork. As simple commands, they do not.
1107 * When used in non-forking context, they can change global variables
1108 * in the parent shell process. If forked, of course they cannot.
1109 * For example, 'unset foo | whatever' will parse and run, but foo will
1110 * still be set at the end. */
1111 struct built_in_command {
1113 int (*b_function)(char **argv) FAST_FUNC;
1114 #if ENABLE_HUSH_HELP
1115 const char *b_descr;
1116 # define BLTIN(cmd, func, help) { cmd, func, help }
1118 # define BLTIN(cmd, func, help) { cmd, func }
1122 static const struct built_in_command bltins1[] = {
1123 BLTIN("." , builtin_source , "Run commands in file"),
1124 BLTIN(":" , builtin_true , NULL),
1126 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1128 #if ENABLE_HUSH_LOOPS
1129 BLTIN("break" , builtin_break , "Exit loop"),
1131 BLTIN("cd" , builtin_cd , "Change directory"),
1132 #if ENABLE_HUSH_LOOPS
1133 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1135 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1136 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1137 BLTIN("exit" , builtin_exit , NULL),
1138 #if ENABLE_HUSH_EXPORT
1139 BLTIN("export" , builtin_export , "Set environment variables"),
1142 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1144 #if ENABLE_HUSH_GETOPTS
1145 BLTIN("getopts" , builtin_getopts , NULL),
1147 #if ENABLE_HUSH_HELP
1148 BLTIN("help" , builtin_help , NULL),
1150 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1151 BLTIN("history" , builtin_history , "Show history"),
1154 BLTIN("jobs" , builtin_jobs , "List jobs"),
1156 #if ENABLE_HUSH_KILL
1157 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1159 #if ENABLE_HUSH_LOCAL
1160 BLTIN("local" , builtin_local , "Set local variables"),
1162 #if ENABLE_HUSH_MEMLEAK
1163 BLTIN("memleak" , builtin_memleak , NULL),
1165 #if ENABLE_HUSH_READ
1166 BLTIN("read" , builtin_read , "Input into variable"),
1168 #if ENABLE_HUSH_READONLY
1169 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1171 #if ENABLE_HUSH_FUNCTIONS
1172 BLTIN("return" , builtin_return , "Return from function"),
1175 BLTIN("set" , builtin_set , "Set positional parameters"),
1177 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1179 BLTIN("source" , builtin_source , NULL),
1181 #if ENABLE_HUSH_TIMES
1182 BLTIN("times" , builtin_times , NULL),
1184 #if ENABLE_HUSH_TRAP
1185 BLTIN("trap" , builtin_trap , "Trap signals"),
1187 BLTIN("true" , builtin_true , NULL),
1188 #if ENABLE_HUSH_TYPE
1189 BLTIN("type" , builtin_type , "Show command type"),
1191 #if ENABLE_HUSH_ULIMIT
1192 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1194 #if ENABLE_HUSH_UMASK
1195 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1197 #if ENABLE_HUSH_UNSET
1198 BLTIN("unset" , builtin_unset , "Unset variables"),
1200 #if ENABLE_HUSH_WAIT
1201 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1204 /* These builtins won't be used if we are on NOMMU and need to re-exec
1205 * (it's cheaper to run an external program in this case):
1207 static const struct built_in_command bltins2[] = {
1208 #if ENABLE_HUSH_TEST
1209 BLTIN("[" , builtin_test , NULL),
1212 BLTIN("[[" , builtin_test , NULL),
1214 #if ENABLE_HUSH_ECHO
1215 BLTIN("echo" , builtin_echo , NULL),
1217 #if ENABLE_HUSH_PRINTF
1218 BLTIN("printf" , builtin_printf , NULL),
1220 BLTIN("pwd" , builtin_pwd , NULL),
1221 #if ENABLE_HUSH_TEST
1222 BLTIN("test" , builtin_test , NULL),
1230 /* prevent disasters with G.debug_indent < 0 */
1231 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1232 # define debug_enter() (G.debug_indent++)
1233 # define debug_leave() (G.debug_indent--)
1235 # define indent() ((void)0)
1236 # define debug_enter() ((void)0)
1237 # define debug_leave() ((void)0)
1240 #ifndef debug_printf
1241 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1244 #ifndef debug_printf_parse
1245 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1248 #ifndef debug_printf_heredoc
1249 # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1252 #ifndef debug_printf_exec
1253 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1256 #ifndef debug_printf_env
1257 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1260 #ifndef debug_printf_jobs
1261 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1262 # define DEBUG_JOBS 1
1264 # define DEBUG_JOBS 0
1267 #ifndef debug_printf_expand
1268 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1269 # define DEBUG_EXPAND 1
1271 # define DEBUG_EXPAND 0
1274 #ifndef debug_printf_varexp
1275 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1278 #ifndef debug_printf_glob
1279 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1280 # define DEBUG_GLOB 1
1282 # define DEBUG_GLOB 0
1285 #ifndef debug_printf_redir
1286 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1289 #ifndef debug_printf_list
1290 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1293 #ifndef debug_printf_subst
1294 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1297 #ifndef debug_printf_prompt
1298 # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1301 #ifndef debug_printf_clean
1302 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1303 # define DEBUG_CLEAN 1
1305 # define DEBUG_CLEAN 0
1309 static void debug_print_strings(const char *prefix, char **vv)
1312 fdprintf(2, "%s:\n", prefix);
1314 fdprintf(2, " '%s'\n", *vv++);
1317 # define debug_print_strings(prefix, vv) ((void)0)
1321 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1324 static void *xxmalloc(int lineno, size_t size)
1326 void *ptr = xmalloc((size + 0xff) & ~0xff);
1327 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1330 static void *xxrealloc(int lineno, void *ptr, size_t size)
1332 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1333 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1336 static char *xxstrdup(int lineno, const char *str)
1338 char *ptr = xstrdup(str);
1339 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1342 static void xxfree(void *ptr)
1344 fdprintf(2, "free %p\n", ptr);
1347 # define xmalloc(s) xxmalloc(__LINE__, s)
1348 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1349 # define xstrdup(s) xxstrdup(__LINE__, s)
1350 # define free(p) xxfree(p)
1354 /* Syntax and runtime errors. They always abort scripts.
1355 * In interactive use they usually discard unparsed and/or unexecuted commands
1356 * and return to the prompt.
1357 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1360 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1361 # define syntax_error(lineno, msg) syntax_error(msg)
1362 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1363 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1364 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1365 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1368 static void die_if_script(void)
1370 if (!G_interactive_fd) {
1371 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1372 xfunc_error_retval = G.last_exitcode;
1377 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1382 bb_error_msg("hush.c:%u", lineno);
1385 bb_verror_msg(fmt, p, NULL);
1390 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1393 bb_error_msg("syntax error: %s", msg);
1395 bb_error_msg("syntax error");
1399 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1401 bb_error_msg("syntax error at '%s'", msg);
1405 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1407 bb_error_msg("syntax error: unterminated %s", s);
1408 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1412 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1414 char msg[2] = { ch, '\0' };
1415 syntax_error_unterm_str(lineno, msg);
1418 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1424 bb_error_msg("hush.c:%u", lineno);
1426 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1431 # undef msg_and_die_if_script
1432 # undef syntax_error
1433 # undef syntax_error_at
1434 # undef syntax_error_unterm_ch
1435 # undef syntax_error_unterm_str
1436 # undef syntax_error_unexpected_ch
1438 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1439 # define syntax_error(msg) syntax_error(__LINE__, msg)
1440 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1441 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1442 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1443 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1447 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1448 static void cmdedit_update_prompt(void);
1450 # define cmdedit_update_prompt() ((void)0)
1454 /* Utility functions
1456 /* Replace each \x with x in place, return ptr past NUL. */
1457 static char *unbackslash(char *src)
1459 char *dst = src = strchrnul(src, '\\');
1468 /* else: "\<nul>". Do not delete this backslash.
1469 * Testcase: eval 'echo ok\'
1474 if ((*dst++ = *src++) == '\0')
1480 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1501 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1502 v[count1 + count2] = NULL;
1505 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1509 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1511 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1512 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1515 #define add_strings_to_strings(strings, add, need_to_dup) \
1516 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1519 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1520 static char **add_string_to_strings(char **strings, char *add)
1525 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1528 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1530 char **ptr = add_string_to_strings(strings, add);
1531 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1534 #define add_string_to_strings(strings, add) \
1535 xx_add_string_to_strings(__LINE__, strings, add)
1538 static void free_strings(char **strings)
1552 static int dup_CLOEXEC(int fd, int avoid_fd)
1556 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1558 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1559 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1560 } else { /* newfd < 0 */
1569 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1573 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1579 /* fd was not open? */
1584 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1585 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1591 /* Manipulating HFILEs */
1592 static HFILE *hfopen(const char *name)
1599 fd = open(name, O_RDONLY | O_CLOEXEC);
1602 if (O_CLOEXEC == 0) /* ancient libc */
1603 close_on_exec_on(fd);
1606 fp = xmalloc(sizeof(*fp));
1607 fp->is_stdin = (name == NULL);
1609 fp->cur = fp->end = fp->buf;
1610 fp->next_hfile = G.HFILE_list;
1614 static void hfclose(HFILE *fp)
1616 HFILE **pp = &G.HFILE_list;
1620 *pp = cur->next_hfile;
1623 pp = &cur->next_hfile;
1629 static int refill_HFILE_and_getc(HFILE *fp)
1634 /* Already saw EOF */
1637 /* Try to buffer more input */
1639 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1641 bb_perror_msg("read error");
1644 fp->end = fp->buf + n;
1651 return (unsigned char)(*fp->cur++);
1653 /* Inlined for common case of non-empty buffer.
1655 static ALWAYS_INLINE int hfgetc(HFILE *fp)
1657 if (fp->cur < fp->end)
1658 return (unsigned char)(*fp->cur++);
1660 return refill_HFILE_and_getc(fp);
1662 static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1664 HFILE *fl = G.HFILE_list;
1667 /* We use it only on script files, they are all CLOEXEC */
1668 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1669 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1670 return 1; /* "found and moved" */
1672 fl = fl->next_hfile;
1674 #if ENABLE_HUSH_MODE_X
1675 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1676 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1677 return 1; /* "found and moved" */
1680 return 0; /* "not in the list" */
1682 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1683 static void close_all_HFILE_list(void)
1685 HFILE *fl = G.HFILE_list;
1687 /* hfclose would also free HFILE object.
1688 * It is disastrous if we share memory with a vforked parent.
1689 * I'm not sure we never come here after vfork.
1690 * Therefore just close fd, nothing more.
1692 * ">" instead of ">=": we don't close fd#0,
1693 * interactive shell uses hfopen(NULL) as stdin input
1694 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1695 * If we'd close it here, then e.g. interactive "set | sort"
1696 * with NOFORKed sort, would have sort's input fd closed.
1699 /*hfclose(fl); - unsafe */
1701 fl = fl->next_hfile;
1705 static int fd_in_HFILEs(int fd)
1707 HFILE *fl = G.HFILE_list;
1711 fl = fl->next_hfile;
1717 /* Helpers for setting new $n and restoring them back
1719 typedef struct save_arg_t {
1723 IF_HUSH_SET(smallint sv_g_malloced;)
1726 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1728 sv->sv_argv0 = argv[0];
1729 sv->sv_g_argv = G.global_argv;
1730 sv->sv_g_argc = G.global_argc;
1731 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1733 argv[0] = G.global_argv[0]; /* retain $0 */
1734 G.global_argv = argv;
1735 IF_HUSH_SET(G.global_args_malloced = 0;)
1737 G.global_argc = 1 + string_array_len(argv + 1);
1740 static void restore_G_args(save_arg_t *sv, char **argv)
1743 if (G.global_args_malloced) {
1744 /* someone ran "set -- arg1 arg2 ...", undo */
1745 char **pp = G.global_argv;
1746 while (*++pp) /* note: does not free $0 */
1748 free(G.global_argv);
1751 argv[0] = sv->sv_argv0;
1752 G.global_argv = sv->sv_g_argv;
1753 G.global_argc = sv->sv_g_argc;
1754 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1758 /* Basic theory of signal handling in shell
1759 * ========================================
1760 * This does not describe what hush does, rather, it is current understanding
1761 * what it _should_ do. If it doesn't, it's a bug.
1762 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1764 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1765 * is finished or backgrounded. It is the same in interactive and
1766 * non-interactive shells, and is the same regardless of whether
1767 * a user trap handler is installed or a shell special one is in effect.
1768 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1769 * backgrounds (i.e. stops) or kills all members of currently running
1772 * Wait builtin is interruptible by signals for which user trap is set
1773 * or by SIGINT in interactive shell.
1775 * Trap handlers will execute even within trap handlers. (right?)
1777 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1778 * except for handlers set to '' (empty string).
1780 * If job control is off, backgrounded commands ("cmd &")
1781 * have SIGINT, SIGQUIT set to SIG_IGN.
1783 * Commands which are run in command substitution ("`cmd`")
1784 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1786 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1787 * by the shell from its parent.
1789 * Signals which differ from SIG_DFL action
1790 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1793 * SIGTERM (interactive): ignore
1794 * SIGHUP (interactive):
1795 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1796 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1797 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1798 * that all pipe members are stopped. Try this in bash:
1799 * while :; do :; done - ^Z does not background it
1800 * (while :; do :; done) - ^Z backgrounds it
1801 * SIGINT (interactive): wait for last pipe, ignore the rest
1802 * of the command line, show prompt. NB: ^C does not send SIGINT
1803 * to interactive shell while shell is waiting for a pipe,
1804 * since shell is bg'ed (is not in foreground process group).
1805 * Example 1: this waits 5 sec, but does not execute ls:
1806 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1807 * Example 2: this does not wait and does not execute ls:
1808 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1809 * Example 3: this does not wait 5 sec, but executes ls:
1810 * "sleep 5; ls -l" + press ^C
1811 * Example 4: this does not wait and does not execute ls:
1812 * "sleep 5 & wait; ls -l" + press ^C
1814 * (What happens to signals which are IGN on shell start?)
1815 * (What happens with signal mask on shell start?)
1817 * Old implementation
1818 * ==================
1819 * We use in-kernel pending signal mask to determine which signals were sent.
1820 * We block all signals which we don't want to take action immediately,
1821 * i.e. we block all signals which need to have special handling as described
1822 * above, and all signals which have traps set.
1823 * After each pipe execution, we extract any pending signals via sigtimedwait()
1826 * unsigned special_sig_mask: a mask of such "special" signals
1827 * sigset_t blocked_set: current blocked signal set
1830 * clear bit in blocked_set unless it is also in special_sig_mask
1831 * "trap 'cmd' SIGxxx":
1832 * set bit in blocked_set (even if 'cmd' is '')
1833 * after [v]fork, if we plan to be a shell:
1834 * unblock signals with special interactive handling
1835 * (child shell is not interactive),
1836 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1837 * after [v]fork, if we plan to exec:
1838 * POSIX says fork clears pending signal mask in child - no need to clear it.
1839 * Restore blocked signal set to one inherited by shell just prior to exec.
1841 * Note: as a result, we do not use signal handlers much. The only uses
1842 * are to count SIGCHLDs
1843 * and to restore tty pgrp on signal-induced exit.
1846 * Standard says "When a subshell is entered, traps that are not being ignored
1847 * are set to the default actions". bash interprets it so that traps which
1848 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1850 * Problem: the above approach makes it unwieldy to catch signals while
1851 * we are in read builtin, or while we read commands from stdin:
1852 * masked signals are not visible!
1854 * New implementation
1855 * ==================
1856 * We record each signal we are interested in by installing signal handler
1857 * for them - a bit like emulating kernel pending signal mask in userspace.
1858 * We are interested in: signals which need to have special handling
1859 * as described above, and all signals which have traps set.
1860 * Signals are recorded in pending_set.
1861 * After each pipe execution, we extract any pending signals
1864 * unsigned special_sig_mask: a mask of shell-special signals.
1865 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1866 * char *traps[sig] if trap for sig is set (even if it's '').
1867 * sigset_t pending_set: set of sigs we received.
1870 * if sig is in special_sig_mask, set handler back to:
1871 * record_pending_signo, or to IGN if it's a tty stop signal
1872 * if sig is in fatal_sig_mask, set handler back to sigexit.
1873 * else: set handler back to SIG_DFL
1874 * "trap 'cmd' SIGxxx":
1875 * set handler to record_pending_signo.
1877 * set handler to SIG_IGN.
1878 * after [v]fork, if we plan to be a shell:
1879 * set signals with special interactive handling to SIG_DFL
1880 * (because child shell is not interactive),
1881 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1882 * after [v]fork, if we plan to exec:
1883 * POSIX says fork clears pending signal mask in child - no need to clear it.
1885 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1886 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1889 * Standard says "When a subshell is entered, traps that are not being ignored
1890 * are set to the default actions". bash interprets it so that traps which
1891 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1894 SPECIAL_INTERACTIVE_SIGS = 0
1899 SPECIAL_JOBSTOP_SIGS = 0
1908 static void record_pending_signo(int sig)
1910 sigaddset(&G.pending_set, sig);
1911 #if ENABLE_HUSH_FAST
1912 if (sig == SIGCHLD) {
1914 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1919 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1921 struct sigaction old_sa;
1923 /* We could use signal() to install handlers... almost:
1924 * except that we need to mask ALL signals while handlers run.
1925 * I saw signal nesting in strace, race window isn't small.
1926 * SA_RESTART is also needed, but in Linux, signal()
1927 * sets SA_RESTART too.
1929 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1930 /* sigfillset(&G.sa.sa_mask); - already done */
1931 /* G.sa.sa_flags = SA_RESTART; - already done */
1932 G.sa.sa_handler = handler;
1933 sigaction(sig, &G.sa, &old_sa);
1934 return old_sa.sa_handler;
1937 static void hush_exit(int exitcode) NORETURN;
1939 static void restore_ttypgrp_and__exit(void) NORETURN;
1940 static void restore_ttypgrp_and__exit(void)
1942 /* xfunc has failed! die die die */
1943 /* no EXIT traps, this is an escape hatch! */
1945 hush_exit(xfunc_error_retval);
1950 /* Needed only on some libc:
1951 * It was observed that on exit(), fgetc'ed buffered data
1952 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1953 * With the net effect that even after fork(), not vfork(),
1954 * exit() in NOEXECed applet in "sh SCRIPT":
1955 * noexec_applet_here
1956 * echo END_OF_SCRIPT
1957 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1958 * This makes "echo END_OF_SCRIPT" executed twice.
1959 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1960 * and in `cmd` handling.
1961 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1963 static void fflush_and__exit(void) NORETURN;
1964 static void fflush_and__exit(void)
1967 _exit(xfunc_error_retval);
1970 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1971 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1972 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1973 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1975 /* Restores tty foreground process group, and exits.
1976 * May be called as signal handler for fatal signal
1977 * (will resend signal to itself, producing correct exit state)
1978 * or called directly with -EXITCODE.
1979 * We also call it if xfunc is exiting.
1981 static void sigexit(int sig) NORETURN;
1982 static void sigexit(int sig)
1984 /* Careful: we can end up here after [v]fork. Do not restore
1985 * tty pgrp then, only top-level shell process does that */
1986 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1987 /* Disable all signals: job control, SIGPIPE, etc.
1988 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1990 sigprocmask_allsigs(SIG_BLOCK);
1991 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1994 /* Not a signal, just exit */
1998 kill_myself_with_sig(sig); /* does not return */
2002 # define disable_restore_tty_pgrp_on_exit() ((void)0)
2003 # define enable_restore_tty_pgrp_on_exit() ((void)0)
2007 static sighandler_t pick_sighandler(unsigned sig)
2009 sighandler_t handler = SIG_DFL;
2010 if (sig < sizeof(unsigned)*8) {
2011 unsigned sigmask = (1 << sig);
2015 if (G_fatal_sig_mask & sigmask)
2019 /* sig has special handling? */
2020 if (G.special_sig_mask & sigmask) {
2021 handler = record_pending_signo;
2022 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
2023 * in order to ignore them: they will be raised
2024 * in an endless loop when we try to do some
2025 * terminal ioctls! We do have to _ignore_ these.
2027 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2034 /* Restores tty foreground process group, and exits. */
2035 static void hush_exit(int exitcode)
2037 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2038 save_history(G.line_input_state);
2042 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
2044 /* argv[0] is unused */
2045 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
2047 G.exiting = 1; /* prevent EXIT trap recursion */
2048 /* Note: G_traps[0] is not cleared!
2049 * "trap" will still show it, if executed
2054 #if ENABLE_FEATURE_CLEAN_UP
2056 struct variable *cur_var;
2057 if (G.cwd != bb_msg_unknown)
2059 cur_var = G.top_var;
2061 struct variable *tmp = cur_var;
2062 if (!cur_var->max_len)
2063 free(cur_var->varstr);
2064 cur_var = cur_var->next;
2072 sigexit(- (exitcode & 0xff));
2079 //TODO: return a mask of ALL handled sigs?
2080 static int check_and_run_traps(void)
2087 if (sigisemptyset(&G.pending_set))
2092 if (sigismember(&G.pending_set, sig)) {
2093 sigdelset(&G.pending_set, sig);
2096 } while (sig < NSIG);
2099 if (G_traps && G_traps[sig]) {
2100 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
2101 if (G_traps[sig][0]) {
2102 /* We have user-defined handler */
2103 smalluint save_rcode;
2105 /* argv[0] is unused */
2106 argv[1] = xstrdup(G_traps[sig]);
2107 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
2109 save_rcode = G.last_exitcode;
2112 //FIXME: shouldn't it be set to 128 + sig instead?
2113 G.last_exitcode = save_rcode;
2115 } /* else: "" trap, ignoring signal */
2118 /* not a trap: special action */
2121 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2127 //TODO: why are we doing this? ash and dash don't do this,
2128 //they have no handler for SIGHUP at all,
2129 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2131 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2132 /* bash is observed to signal whole process groups,
2133 * not individual processes */
2134 for (job = G.job_list; job; job = job->next) {
2137 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2138 if (kill(- job->pgrp, SIGHUP) == 0)
2139 kill(- job->pgrp, SIGCONT);
2144 #if ENABLE_HUSH_FAST
2146 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2148 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2150 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2151 * This simplifies wait builtin a bit.
2155 default: /* ignored: */
2156 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2157 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2159 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2160 * Example: wait is not interrupted by TERM
2161 * in interactive shell, because TERM is ignored.
2170 static const char *get_cwd(int force)
2172 if (force || G.cwd == NULL) {
2173 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2174 * we must not try to free(bb_msg_unknown) */
2175 if (G.cwd == bb_msg_unknown)
2177 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2179 G.cwd = bb_msg_unknown;
2186 * Shell and environment variable support
2188 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2190 struct variable **pp;
2191 struct variable *cur;
2194 while ((cur = *pp) != NULL) {
2195 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2202 static const char* FAST_FUNC get_local_var_value(const char *name)
2204 struct variable **vpp;
2205 unsigned len = strlen(name);
2207 if (G.expanded_assignments) {
2208 char **cpp = G.expanded_assignments;
2211 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2212 return cp + len + 1;
2217 vpp = get_ptr_to_local_var(name, len);
2219 return (*vpp)->varstr + len + 1;
2221 if (strcmp(name, "PPID") == 0)
2222 return utoa(G.root_ppid);
2223 // bash compat: UID? EUID?
2224 #if ENABLE_HUSH_RANDOM_SUPPORT
2225 if (strcmp(name, "RANDOM") == 0)
2226 return utoa(next_random(&G.random_gen));
2231 static void handle_changed_special_names(const char *name, unsigned name_len)
2233 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2234 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2236 cmdedit_update_prompt();
2240 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2243 #if ENABLE_HUSH_LINENO_VAR
2244 if (strncmp(name, "LINENO", 6) == 0) {
2245 G.lineno_var = NULL;
2249 #if ENABLE_HUSH_GETOPTS
2250 if (strncmp(name, "OPTIND", 6) == 0) {
2258 /* str holds "NAME=VAL" and is expected to be malloced.
2259 * We take ownership of it.
2261 #define SETFLAG_EXPORT (1 << 0)
2262 #define SETFLAG_UNEXPORT (1 << 1)
2263 #define SETFLAG_MAKE_RO (1 << 2)
2264 #define SETFLAG_VARLVL_SHIFT 3
2265 static int set_local_var(char *str, unsigned flags)
2267 struct variable **cur_pp;
2268 struct variable *cur;
2269 char *free_me = NULL;
2272 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
2274 eq_sign = strchr(str, '=');
2275 if (HUSH_DEBUG && !eq_sign)
2276 bb_error_msg_and_die("BUG in setvar");
2278 name_len = eq_sign - str + 1; /* including '=' */
2279 cur_pp = &G.top_var;
2280 while ((cur = *cur_pp) != NULL) {
2281 if (strncmp(cur->varstr, str, name_len) != 0) {
2282 cur_pp = &cur->next;
2286 /* We found an existing var with this name */
2287 if (cur->flg_read_only) {
2288 bb_error_msg("%s: readonly variable", str);
2290 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2291 //but export per se succeeds (does put the var in env). We don't mimic that.
2294 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2295 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2300 if (cur->var_nest_level < local_lvl) {
2301 /* bash 3.2.33(1) and exported vars:
2303 * # f() { local z=a; env | grep ^z; }
2309 if (cur->flg_export)
2310 flags |= SETFLAG_EXPORT;
2311 /* New variable is local ("local VAR=VAL" or
2313 * and existing one is global, or local
2314 * on a lower level that new one.
2315 * Remove it from global variable list:
2317 *cur_pp = cur->next;
2318 if (G.shadowed_vars_pp) {
2319 /* Save in "shadowed" list */
2320 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2321 cur->flg_export ? "exported " : "",
2322 cur->varstr, cur->var_nest_level, str, local_lvl
2324 cur->next = *G.shadowed_vars_pp;
2325 *G.shadowed_vars_pp = cur;
2327 /* Came from pseudo_exec_argv(), no need to save: delete it */
2328 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2329 cur->flg_export ? "exported " : "",
2330 cur->varstr, cur->var_nest_level, str, local_lvl
2332 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2333 free_me = cur->varstr; /* then free it later */
2339 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2340 debug_printf_env("assignement '%s' does not change anything\n", str);
2346 /* Replace the value in the found "struct variable" */
2347 if (cur->max_len != 0) {
2348 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
2349 /* This one is from startup env, reuse space */
2350 debug_printf_env("reusing startup env for '%s'\n", str);
2351 strcpy(cur->varstr, str);
2356 goto set_str_and_exp;
2358 /* max_len == 0 signifies "malloced" var, which we can
2359 * (and have to) free. But we can't free(cur->varstr) here:
2360 * if cur->flg_export is 1, it is in the environment.
2361 * We should either unsetenv+free, or wait until putenv,
2362 * then putenv(new)+free(old).
2364 free_me = cur->varstr;
2365 goto set_str_and_exp;
2368 /* Not found or shadowed - create new variable struct */
2369 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
2370 cur = xzalloc(sizeof(*cur));
2371 cur->var_nest_level = local_lvl;
2372 cur->next = *cur_pp;
2378 #if !BB_MMU || ENABLE_HUSH_READONLY
2379 if (flags & SETFLAG_MAKE_RO) {
2380 cur->flg_read_only = 1;
2383 if (flags & SETFLAG_EXPORT)
2384 cur->flg_export = 1;
2385 if (cur->flg_export) {
2386 if (flags & SETFLAG_UNEXPORT) {
2387 cur->flg_export = 0;
2388 /* unsetenv was already done */
2391 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
2392 i = putenv(cur->varstr);
2393 /* only now we can free old exported malloced string */
2400 handle_changed_special_names(cur->varstr, name_len - 1);
2405 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2407 char *var = xasprintf("%s=%s", name, val);
2408 set_local_var(var, /*flag:*/ 0);
2411 /* Used at startup and after each cd */
2412 static void set_pwd_var(unsigned flag)
2414 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2417 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2418 static int unset_local_var_len(const char *name, int name_len)
2420 struct variable *cur;
2421 struct variable **cur_pp;
2423 cur_pp = &G.top_var;
2424 while ((cur = *cur_pp) != NULL) {
2425 if (strncmp(cur->varstr, name, name_len) == 0
2426 && cur->varstr[name_len] == '='
2428 if (cur->flg_read_only) {
2429 bb_error_msg("%s: readonly variable", name);
2430 return EXIT_FAILURE;
2433 *cur_pp = cur->next;
2434 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2435 bb_unsetenv(cur->varstr);
2442 cur_pp = &cur->next;
2445 /* Handle "unset PS1" et al even if did not find the variable to unset */
2446 handle_changed_special_names(name, name_len);
2448 return EXIT_SUCCESS;
2451 static int unset_local_var(const char *name)
2453 return unset_local_var_len(name, strlen(name));
2459 * Helpers for "var1=val1 var2=val2 cmd" feature
2461 static void add_vars(struct variable *var)
2463 struct variable *next;
2467 var->next = G.top_var;
2469 if (var->flg_export) {
2470 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2471 putenv(var->varstr);
2473 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2479 /* We put strings[i] into variable table and possibly putenv them.
2480 * If variable is read only, we can free the strings[i]
2481 * which attempts to overwrite it.
2482 * The strings[] vector itself is freed.
2484 static void set_vars_and_save_old(char **strings)
2493 struct variable *var_p;
2494 struct variable **var_pp;
2497 eq = strchr(*s, '=');
2498 if (HUSH_DEBUG && !eq)
2499 bb_error_msg_and_die("BUG in varexp4");
2500 var_pp = get_ptr_to_local_var(*s, eq - *s);
2503 if (var_p->flg_read_only) {
2505 bb_error_msg("%s: readonly variable", *s);
2507 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2508 * If VAR is readonly, leaving it in the list
2509 * after asssignment error (msg above)
2510 * causes doubled error message later, on unset.
2512 debug_printf_env("removing/freeing '%s' element\n", *s);
2515 do { *p = p[1]; p++; } while (*p);
2518 /* below, set_local_var() with nest level will
2519 * "shadow" (remove) this variable from
2520 * global linked list.
2523 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2524 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2535 static void reinit_unicode_for_hush(void)
2537 /* Unicode support should be activated even if LANG is set
2538 * _during_ shell execution, not only if it was set when
2539 * shell was started. Therefore, re-check LANG every time:
2541 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2542 || ENABLE_UNICODE_USING_LOCALE
2544 const char *s = get_local_var_value("LC_ALL");
2545 if (!s) s = get_local_var_value("LC_CTYPE");
2546 if (!s) s = get_local_var_value("LANG");
2552 * in_str support (strings, and "strings" read from files).
2555 #if ENABLE_HUSH_INTERACTIVE
2556 /* To test correct lineedit/interactive behavior, type from command line:
2562 * It exercises a lot of corner cases.
2564 # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2565 static void cmdedit_update_prompt(void)
2567 G.PS1 = get_local_var_value("PS1");
2570 G.PS2 = get_local_var_value("PS2");
2575 static const char *setup_prompt_string(void)
2577 const char *prompt_str;
2579 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
2581 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2582 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
2583 if (G.promptmode == 0) { /* PS1 */
2584 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2585 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2587 /* bash uses $PWD value, even if it is set by user.
2588 * It uses current dir only if PWD is unset.
2589 * We always use current dir. */
2590 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2594 debug_printf("prompt_str '%s'\n", prompt_str);
2597 static int get_user_input(struct in_str *i)
2600 const char *prompt_str;
2602 prompt_str = setup_prompt_string();
2603 # if ENABLE_FEATURE_EDITING
2605 reinit_unicode_for_hush();
2606 if (G.flag_SIGINT) {
2607 /* There was ^C'ed, make it look prettier: */
2611 /* buglet: SIGINT will not make new prompt to appear _at once_,
2612 * only after <Enter>. (^C works immediately) */
2613 r = read_line_input(G.line_input_state, prompt_str,
2614 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2616 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2619 check_and_run_traps();
2620 if (r != 0 && !G.flag_SIGINT)
2622 /* ^C or SIGINT: repeat */
2623 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2624 write(STDOUT_FILENO, "^C", 2);
2625 G.last_exitcode = 128 + SIGINT;
2628 /* EOF/error detected */
2630 i->peek_buf[0] = r = EOF;
2633 i->p = G.user_input_buf;
2634 return (unsigned char)*i->p++;
2638 if (i->last_char == '\0' || i->last_char == '\n') {
2639 /* Why check_and_run_traps here? Try this interactively:
2640 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2641 * $ <[enter], repeatedly...>
2642 * Without check_and_run_traps, handler never runs.
2644 check_and_run_traps();
2645 fputs(prompt_str, stdout);
2648 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2649 r = hfgetc(i->file);
2650 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2651 * no ^C masking happens during fgetc, no special code for ^C:
2652 * it generates SIGINT as usual.
2654 check_and_run_traps();
2656 G.last_exitcode = 128 + SIGINT;
2663 /* This is the magic location that prints prompts
2664 * and gets data back from the user */
2665 static int fgetc_interactive(struct in_str *i)
2668 /* If it's interactive stdin, get new line. */
2669 if (G_interactive_fd && i->file->is_stdin) {
2670 /* Returns first char (or EOF), the rest is in i->p[] */
2671 ch = get_user_input(i);
2672 G.promptmode = 1; /* PS2 */
2673 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
2675 /* Not stdin: script file, sourced file, etc */
2676 do ch = hfgetc(i->file); while (ch == '\0');
2681 static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
2684 do ch = hfgetc(i->file); while (ch == '\0');
2687 #endif /* INTERACTIVE */
2689 static int i_getch(struct in_str *i)
2694 /* string-based in_str */
2695 ch = (unsigned char)*i->p;
2704 /* FILE-based in_str */
2706 #if ENABLE_FEATURE_EDITING
2707 /* This can be stdin, check line editing char[] buffer */
2708 if (i->p && *i->p != '\0') {
2709 ch = (unsigned char)*i->p++;
2713 /* peek_buf[] is an int array, not char. Can contain EOF. */
2714 ch = i->peek_buf[0];
2716 int ch2 = i->peek_buf[1];
2717 i->peek_buf[0] = ch2;
2718 if (ch2 == 0) /* very likely, avoid redundant write */
2724 ch = fgetc_interactive(i);
2726 debug_printf("file_get: got '%c' %d\n", ch, ch);
2728 #if ENABLE_HUSH_LINENO_VAR
2731 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2737 static int i_peek(struct in_str *i)
2742 /* string-based in_str */
2743 /* Doesn't report EOF on NUL. None of the callers care. */
2744 return (unsigned char)*i->p;
2747 /* FILE-based in_str */
2749 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2750 /* This can be stdin, check line editing char[] buffer */
2751 if (i->p && *i->p != '\0')
2752 return (unsigned char)*i->p;
2754 /* peek_buf[] is an int array, not char. Can contain EOF. */
2755 ch = i->peek_buf[0];
2759 /* Need to get a new char */
2760 ch = fgetc_interactive(i);
2761 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2763 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2764 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2770 i->peek_buf[0] = ch;
2771 /*i->peek_buf[1] = 0; - already is */
2775 /* Only ever called if i_peek() was called, and did not return EOF.
2776 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2777 * not end-of-line. Therefore we never need to read a new editing line here.
2779 static int i_peek2(struct in_str *i)
2783 /* There are two cases when i->p[] buffer exists.
2784 * (1) it's a string in_str.
2785 * (2) It's a file, and we have a saved line editing buffer.
2786 * In both cases, we know that i->p[0] exists and not NUL, and
2787 * the peek2 result is in i->p[1].
2790 return (unsigned char)i->p[1];
2792 /* Now we know it is a file-based in_str. */
2794 /* peek_buf[] is an int array, not char. Can contain EOF. */
2795 /* Is there 2nd char? */
2796 ch = i->peek_buf[1];
2798 /* We did not read it yet, get it now */
2799 do ch = hfgetc(i->file); while (ch == '\0');
2800 i->peek_buf[1] = ch;
2803 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2807 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2812 ch = i_getch(input);
2815 ch2 = i_peek(input);
2818 /* backslash+newline, skip it */
2823 /* Note: this function _eats_ \<newline> pairs, safe to use plain
2824 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2826 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2834 ch2 = i_peek2(input);
2837 /* backslash+newline, skip it */
2843 static void setup_file_in_str(struct in_str *i, HFILE *fp)
2845 memset(i, 0, sizeof(*i));
2850 static void setup_string_in_str(struct in_str *i, const char *s)
2852 memset(i, 0, sizeof(*i));
2853 /*i->file = NULL */;
2861 #define B_CHUNK (32 * sizeof(char*))
2863 static void o_reset_to_empty_unquoted(o_string *o)
2866 o->has_quoted_part = 0;
2871 static void o_free_and_set_NULL(o_string *o)
2874 memset(o, 0, sizeof(*o));
2877 static ALWAYS_INLINE void o_free(o_string *o)
2882 static void o_grow_by(o_string *o, int len)
2884 if (o->length + len > o->maxlen) {
2885 o->maxlen += (2 * len) | (B_CHUNK-1);
2886 o->data = xrealloc(o->data, 1 + o->maxlen);
2890 static void o_addchr(o_string *o, int ch)
2892 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2893 if (o->length < o->maxlen) {
2894 /* likely. avoid o_grow_by() call */
2896 o->data[o->length] = ch;
2898 o->data[o->length] = '\0';
2906 /* Valid only if we know o_string is not empty */
2907 static void o_delchr(o_string *o)
2910 o->data[o->length] = '\0';
2914 static void o_addblock(o_string *o, const char *str, int len)
2917 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2921 static void o_addstr(o_string *o, const char *str)
2923 o_addblock(o, str, strlen(str));
2926 static void o_addstr_with_NUL(o_string *o, const char *str)
2928 o_addblock(o, str, strlen(str) + 1);
2932 static void nommu_addchr(o_string *o, int ch)
2938 # define nommu_addchr(o, str) ((void)0)
2941 #if ENABLE_HUSH_MODE_X
2942 static void x_mode_addchr(int ch)
2944 o_addchr(&G.x_mode_buf, ch);
2946 static void x_mode_addstr(const char *str)
2948 o_addstr(&G.x_mode_buf, str);
2950 static void x_mode_addblock(const char *str, int len)
2952 o_addblock(&G.x_mode_buf, str, len);
2954 static void x_mode_prefix(void)
2956 int n = G.x_mode_depth;
2957 do x_mode_addchr('+'); while (--n >= 0);
2959 static void x_mode_flush(void)
2961 int len = G.x_mode_buf.length;
2964 if (G.x_mode_fd > 0) {
2965 G.x_mode_buf.data[len] = '\n';
2966 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2968 G.x_mode_buf.length = 0;
2973 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2974 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2975 * Apparently, on unquoted $v bash still does globbing
2976 * ("v='*.txt'; echo $v" prints all .txt files),
2977 * but NOT brace expansion! Thus, there should be TWO independent
2978 * quoting mechanisms on $v expansion side: one protects
2979 * $v from brace expansion, and other additionally protects "$v" against globbing.
2980 * We have only second one.
2983 #if ENABLE_HUSH_BRACE_EXPANSION
2984 # define MAYBE_BRACES "{}"
2986 # define MAYBE_BRACES ""
2989 /* My analysis of quoting semantics tells me that state information
2990 * is associated with a destination, not a source.
2992 static void o_addqchr(o_string *o, int ch)
2995 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
3000 o->data[o->length] = '\\';
3003 o->data[o->length] = ch;
3005 o->data[o->length] = '\0';
3008 static void o_addQchr(o_string *o, int ch)
3011 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3012 && strchr("*?[\\" MAYBE_BRACES, ch)
3015 o->data[o->length] = '\\';
3019 o->data[o->length] = ch;
3021 o->data[o->length] = '\0';
3024 static void o_addqblock(o_string *o, const char *str, int len)
3029 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
3030 if (ordinary_cnt > len) /* paranoia */
3032 o_addblock(o, str, ordinary_cnt);
3033 if (ordinary_cnt == len)
3034 return; /* NUL is already added by o_addblock */
3035 str += ordinary_cnt;
3036 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
3040 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
3042 o->data[o->length] = '\\';
3046 o->data[o->length] = ch;
3049 o->data[o->length] = '\0';
3052 static void o_addQblock(o_string *o, const char *str, int len)
3054 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
3055 o_addblock(o, str, len);
3058 o_addqblock(o, str, len);
3061 static void o_addQstr(o_string *o, const char *str)
3063 o_addQblock(o, str, strlen(str));
3066 /* A special kind of o_string for $VAR and `cmd` expansion.
3067 * It contains char* list[] at the beginning, which is grown in 16 element
3068 * increments. Actual string data starts at the next multiple of 16 * (char*).
3069 * list[i] contains an INDEX (int!) into this string data.
3070 * It means that if list[] needs to grow, data needs to be moved higher up
3071 * but list[i]'s need not be modified.
3072 * NB: remembering how many list[i]'s you have there is crucial.
3073 * o_finalize_list() operation post-processes this structure - calculates
3074 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3076 #if DEBUG_EXPAND || DEBUG_GLOB
3077 static void debug_print_list(const char *prefix, o_string *o, int n)
3079 char **list = (char**)o->data;
3080 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3084 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
3085 prefix, list, n, string_start, o->length, o->maxlen,
3086 !!(o->o_expflags & EXP_FLAG_GLOB),
3088 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3091 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3092 o->data + (int)(uintptr_t)list[i] + string_start,
3093 o->data + (int)(uintptr_t)list[i] + string_start);
3097 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
3099 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
3103 # define debug_print_list(prefix, o, n) ((void)0)
3106 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3107 * in list[n] so that it points past last stored byte so far.
3108 * It returns n+1. */
3109 static int o_save_ptr_helper(o_string *o, int n)
3111 char **list = (char**)o->data;
3115 if (!o->has_empty_slot) {
3116 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3117 string_len = o->length - string_start;
3118 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
3119 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
3120 /* list[n] points to string_start, make space for 16 more pointers */
3121 o->maxlen += 0x10 * sizeof(list[0]);
3122 o->data = xrealloc(o->data, o->maxlen + 1);
3123 list = (char**)o->data;
3124 memmove(list + n + 0x10, list + n, string_len);
3126 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3127 * check. (grep for -prev-ifs-check-).
3128 * Ensure that argv[-1][last] is not garbage
3129 * but zero bytes, to save index check there.
3131 list[n + 0x10 - 1] = 0;
3132 o->length += 0x10 * sizeof(list[0]);
3134 debug_printf_list("list[%d]=%d string_start=%d\n",
3135 n, string_len, string_start);
3138 /* We have empty slot at list[n], reuse without growth */
3139 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3140 string_len = o->length - string_start;
3141 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3142 n, string_len, string_start);
3143 o->has_empty_slot = 0;
3145 o->has_quoted_part = 0;
3146 list[n] = (char*)(uintptr_t)string_len;
3150 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
3151 static int o_get_last_ptr(o_string *o, int n)
3153 char **list = (char**)o->data;
3154 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3156 return ((int)(uintptr_t)list[n-1]) + string_start;
3160 * Globbing routines.
3162 * Most words in commands need to be globbed, even ones which are
3163 * (single or double) quoted. This stems from the possiblity of
3164 * constructs like "abc"* and 'abc'* - these should be globbed.
3165 * Having a different code path for fully-quoted strings ("abc",
3166 * 'abc') would only help performance-wise, but we still need
3167 * code for partially-quoted strings.
3169 * Unfortunately, if we want to match bash and ash behavior in all cases,
3170 * the logic can't be "shell-syntax argument is first transformed
3171 * to a string, then globbed, and if globbing does not match anything,
3172 * it is used verbatim". Here are two examples where it fails:
3176 * The globbing can't be avoided (because of '?' at the end).
3177 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3178 * and are glob-escaped. If this does not match, bash/ash print b\*?
3179 * - IOW: they "unbackslash" the glob pattern.
3180 * Now, look at this:
3182 * v='\\\*'; echo b$v?
3184 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
3185 * should be used as glob pattern with no changes. However, if glob
3186 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
3188 * ash implements this by having an encoded representation of the word
3189 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3190 * Glob pattern is derived from it. If glob fails, the decision what result
3191 * should be is made using that encoded representation. Not glob pattern.
3194 #if ENABLE_HUSH_BRACE_EXPANSION
3195 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
3196 * first, it processes even {a} (no commas), second,
3197 * I didn't manage to make it return strings when they don't match
3198 * existing files. Need to re-implement it.
3202 static int glob_needed(const char *s)
3211 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3217 /* Return pointer to next closing brace or to comma */
3218 static const char *next_brace_sub(const char *cp)
3222 while (*cp != '\0') {
3229 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3235 return *cp != '\0' ? cp : NULL;
3237 /* Recursive brace globber. Note: may garble pattern[]. */
3238 static int glob_brace(char *pattern, o_string *o, int n)
3240 char *new_pattern_buf;
3247 debug_printf_glob("glob_brace('%s')\n", pattern);
3253 if (*begin == '{') {
3254 /* Find the first sub-pattern and at the same time
3255 * find the rest after the closing brace */
3256 next = next_brace_sub(begin);
3258 /* An illegal expression */
3262 /* "{abc}" with no commas - illegal
3263 * brace expr, disregard and skip it */
3269 if (*begin == '\\' && begin[1] != '\0')
3273 debug_printf_glob("begin:%s\n", begin);
3274 debug_printf_glob("next:%s\n", next);
3276 /* Now find the end of the whole brace expression */
3278 while (*rest != '}') {
3279 rest = next_brace_sub(rest);
3281 /* An illegal expression */
3284 debug_printf_glob("rest:%s\n", rest);
3286 rest_len = strlen(++rest) + 1;
3288 /* We are sure the brace expression is well-formed */
3290 /* Allocate working buffer large enough for our work */
3291 new_pattern_buf = xmalloc(strlen(pattern));
3293 /* We have a brace expression. BEGIN points to the opening {,
3294 * NEXT points past the terminator of the first element, and REST
3295 * points past the final }. We will accumulate result names from
3296 * recursive runs for each brace alternative in the buffer using
3301 /* Construct the new glob expression */
3304 mempcpy(new_pattern_buf,
3305 /* We know the prefix for all sub-patterns */
3306 pattern, begin - pattern),
3310 /* Note: glob_brace() may garble new_pattern_buf[].
3311 * That's why we re-copy prefix every time (1st memcpy above).
3313 n = glob_brace(new_pattern_buf, o, n);
3315 /* We saw the last entry */
3319 next = next_brace_sub(next);
3321 free(new_pattern_buf);
3329 memset(&globdata, 0, sizeof(globdata));
3330 gr = glob(pattern, 0, NULL, &globdata);
3331 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3333 if (gr == GLOB_NOMATCH) {
3334 globfree(&globdata);
3335 /* NB: garbles parameter */
3336 unbackslash(pattern);
3337 o_addstr_with_NUL(o, pattern);
3338 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3339 return o_save_ptr_helper(o, n);
3341 if (gr == GLOB_NOSPACE)
3342 bb_die_memory_exhausted();
3343 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3344 * but we didn't specify it. Paranoia again. */
3345 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3347 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3348 char **argv = globdata.gl_pathv;
3350 o_addstr_with_NUL(o, *argv);
3351 n = o_save_ptr_helper(o, n);
3357 globfree(&globdata);
3361 /* Performs globbing on last list[],
3362 * saving each result as a new list[].
3364 static int perform_glob(o_string *o, int n)
3366 char *pattern, *copy;
3368 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3370 return o_save_ptr_helper(o, n);
3371 pattern = o->data + o_get_last_ptr(o, n);
3372 debug_printf_glob("glob pattern '%s'\n", pattern);
3373 if (!glob_needed(pattern)) {
3374 /* unbackslash last string in o in place, fix length */
3375 o->length = unbackslash(pattern) - o->data;
3376 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3377 return o_save_ptr_helper(o, n);
3380 copy = xstrdup(pattern);
3381 /* "forget" pattern in o */
3382 o->length = pattern - o->data;
3383 n = glob_brace(copy, o, n);
3386 debug_print_list("perform_glob returning", o, n);
3390 #else /* !HUSH_BRACE_EXPANSION */
3393 static int glob_needed(const char *s)
3402 if (*s == '*' || *s == '[' || *s == '?')
3408 /* Performs globbing on last list[],
3409 * saving each result as a new list[].
3411 static int perform_glob(o_string *o, int n)
3417 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3419 return o_save_ptr_helper(o, n);
3420 pattern = o->data + o_get_last_ptr(o, n);
3421 debug_printf_glob("glob pattern '%s'\n", pattern);
3422 if (!glob_needed(pattern)) {
3424 /* unbackslash last string in o in place, fix length */
3425 o->length = unbackslash(pattern) - o->data;
3426 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3427 return o_save_ptr_helper(o, n);
3430 memset(&globdata, 0, sizeof(globdata));
3431 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3432 * If we glob "*.\*" and don't find anything, we need
3433 * to fall back to using literal "*.*", but GLOB_NOCHECK
3434 * will return "*.\*"!
3436 gr = glob(pattern, 0, NULL, &globdata);
3437 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3439 if (gr == GLOB_NOMATCH) {
3440 globfree(&globdata);
3443 if (gr == GLOB_NOSPACE)
3444 bb_die_memory_exhausted();
3445 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3446 * but we didn't specify it. Paranoia again. */
3447 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3449 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3450 char **argv = globdata.gl_pathv;
3451 /* "forget" pattern in o */
3452 o->length = pattern - o->data;
3454 o_addstr_with_NUL(o, *argv);
3455 n = o_save_ptr_helper(o, n);
3461 globfree(&globdata);
3463 debug_print_list("perform_glob returning", o, n);
3467 #endif /* !HUSH_BRACE_EXPANSION */
3469 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3470 * Otherwise, just finish current list[] and start new */
3471 static int o_save_ptr(o_string *o, int n)
3473 if (o->o_expflags & EXP_FLAG_GLOB) {
3474 /* If o->has_empty_slot, list[n] was already globbed
3475 * (if it was requested back then when it was filled)
3476 * so don't do that again! */
3477 if (!o->has_empty_slot)
3478 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3480 return o_save_ptr_helper(o, n);
3483 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3484 static char **o_finalize_list(o_string *o, int n)
3490 debug_print_list("finalized", o, n);
3491 debug_printf_expand("finalized n:%d\n", n);
3492 list = (char**)o->data;
3493 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3497 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3502 static void free_pipe_list(struct pipe *pi);
3504 /* Returns pi->next - next pipe in the list */
3505 static struct pipe *free_pipe(struct pipe *pi)
3510 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3511 for (i = 0; i < pi->num_cmds; i++) {
3512 struct command *command;
3513 struct redir_struct *r, *rnext;
3515 command = &pi->cmds[i];
3516 debug_printf_clean(" command %d:\n", i);
3517 if (command->argv) {
3521 for (a = 0, p = command->argv; *p; a++, p++) {
3522 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3525 free_strings(command->argv);
3526 //command->argv = NULL;
3528 /* not "else if": on syntax error, we may have both! */
3529 if (command->group) {
3530 debug_printf_clean(" begin group (cmd_type:%d)\n",
3532 free_pipe_list(command->group);
3533 debug_printf_clean(" end group\n");
3534 //command->group = NULL;
3536 /* else is crucial here.
3537 * If group != NULL, child_func is meaningless */
3538 #if ENABLE_HUSH_FUNCTIONS
3539 else if (command->child_func) {
3540 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3541 command->child_func->parent_cmd = NULL;
3545 free(command->group_as_string);
3546 //command->group_as_string = NULL;
3548 for (r = command->redirects; r; r = rnext) {
3549 debug_printf_clean(" redirect %d%s",
3550 r->rd_fd, redir_table[r->rd_type].descrip);
3551 /* guard against the case >$FOO, where foo is unset or blank */
3552 if (r->rd_filename) {
3553 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3554 free(r->rd_filename);
3555 //r->rd_filename = NULL;
3557 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3561 //command->redirects = NULL;
3563 free(pi->cmds); /* children are an array, they get freed all at once */
3567 //pi->cmdtext = NULL;
3575 static void free_pipe_list(struct pipe *pi)
3579 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3581 debug_printf_clean("pipe followup code %d\n", pi->followup);
3587 /*** Parsing routines ***/
3589 #ifndef debug_print_tree
3590 static void debug_print_tree(struct pipe *pi, int lvl)
3592 static const char *const PIPE[] = {
3598 static const char *RES[] = {
3599 [RES_NONE ] = "NONE" ,
3602 [RES_THEN ] = "THEN" ,
3603 [RES_ELIF ] = "ELIF" ,
3604 [RES_ELSE ] = "ELSE" ,
3607 # if ENABLE_HUSH_LOOPS
3608 [RES_FOR ] = "FOR" ,
3609 [RES_WHILE] = "WHILE",
3610 [RES_UNTIL] = "UNTIL",
3612 [RES_DONE ] = "DONE" ,
3614 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3617 # if ENABLE_HUSH_CASE
3618 [RES_CASE ] = "CASE" ,
3619 [RES_CASE_IN ] = "CASE_IN" ,
3620 [RES_MATCH] = "MATCH",
3621 [RES_CASE_BODY] = "CASE_BODY",
3622 [RES_ESAC ] = "ESAC" ,
3624 [RES_XXXX ] = "XXXX" ,
3625 [RES_SNTX ] = "SNTX" ,
3627 static const char *const CMDTYPE[] = {
3631 # if ENABLE_HUSH_FUNCTIONS
3640 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3643 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3645 pi->followup, PIPE[pi->followup]
3648 while (prn < pi->num_cmds) {
3649 struct command *command = &pi->cmds[prn];
3650 char **argv = command->argv;
3652 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3654 command->assignment_cnt);
3655 #if ENABLE_HUSH_LINENO_VAR
3656 fdprintf(2, " LINENO:%u", command->lineno);
3658 if (command->group) {
3659 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3660 CMDTYPE[command->cmd_type],
3663 , " group_as_string:", command->group_as_string
3668 debug_print_tree(command->group, lvl+1);
3672 if (argv) while (*argv) {
3673 fdprintf(2, " '%s'", *argv);
3676 if (command->redirects)
3677 fdprintf(2, " {redir}");
3685 #endif /* debug_print_tree */
3687 static struct pipe *new_pipe(void)
3690 pi = xzalloc(sizeof(struct pipe));
3691 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3695 /* Command (member of a pipe) is complete, or we start a new pipe
3696 * if ctx->command is NULL.
3697 * No errors possible here.
3699 static int done_command(struct parse_context *ctx)
3701 /* The command is really already in the pipe structure, so
3702 * advance the pipe counter and make a new, null command. */
3703 struct pipe *pi = ctx->pipe;
3704 struct command *command = ctx->command;
3706 #if 0 /* Instead we emit error message at run time */
3707 if (ctx->pending_redirect) {
3708 /* For example, "cmd >" (no filename to redirect to) */
3709 syntax_error("invalid redirect");
3710 ctx->pending_redirect = NULL;
3715 if (IS_NULL_CMD(command)) {
3716 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3720 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3721 //debug_print_tree(ctx->list_head, 20);
3723 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3726 /* Only real trickiness here is that the uncommitted
3727 * command structure is not counted in pi->num_cmds. */
3728 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3729 ctx->command = command = &pi->cmds[pi->num_cmds];
3731 memset(command, 0, sizeof(*command));
3732 #if ENABLE_HUSH_LINENO_VAR
3733 command->lineno = G.lineno;
3734 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
3736 return pi->num_cmds; /* used only for 0/nonzero check */
3739 static void done_pipe(struct parse_context *ctx, pipe_style type)
3743 debug_printf_parse("done_pipe entered, followup %d\n", type);
3744 /* Close previous command */
3745 not_null = done_command(ctx);
3747 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3748 ctx->ctx_inverted = 0;
3749 ctx->pipe->res_word = ctx->ctx_res_w;
3751 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3752 /* Necessary since && and || have precedence over &:
3753 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3754 * in a backgrounded subshell.
3757 struct command *command;
3759 /* Is this actually this construct, all pipes end with && or ||? */
3760 pi = ctx->list_head;
3761 while (pi != ctx->pipe) {
3762 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3767 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3768 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3769 pi = xzalloc(sizeof(*pi));
3770 pi->followup = PIPE_BG;
3772 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3773 command = &pi->cmds[0];
3774 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3775 command->cmd_type = CMD_NORMAL;
3776 command->group = ctx->list_head;
3778 command->group_as_string = xstrndup(
3779 ctx->as_string.data,
3780 ctx->as_string.length - 1 /* do not copy last char, "&" */
3783 /* Replace all pipes in ctx with one newly created */
3784 ctx->list_head = ctx->pipe = pi;
3787 ctx->pipe->followup = type;
3790 /* Without this check, even just <enter> on command line generates
3791 * tree of three NOPs (!). Which is harmless but annoying.
3792 * IOW: it is safe to do it unconditionally. */
3795 || ctx->ctx_res_w == RES_FI
3797 #if ENABLE_HUSH_LOOPS
3798 || ctx->ctx_res_w == RES_DONE
3799 || ctx->ctx_res_w == RES_FOR
3800 || ctx->ctx_res_w == RES_IN
3802 #if ENABLE_HUSH_CASE
3803 || ctx->ctx_res_w == RES_ESAC
3807 debug_printf_parse("done_pipe: adding new pipe: "
3808 "not_null:%d ctx->ctx_res_w:%d\n",
3809 not_null, ctx->ctx_res_w);
3811 ctx->pipe->next = new_p;
3813 /* RES_THEN, RES_DO etc are "sticky" -
3814 * they remain set for pipes inside if/while.
3815 * This is used to control execution.
3816 * RES_FOR and RES_IN are NOT sticky (needed to support
3817 * cases where variable or value happens to match a keyword):
3819 #if ENABLE_HUSH_LOOPS
3820 if (ctx->ctx_res_w == RES_FOR
3821 || ctx->ctx_res_w == RES_IN)
3822 ctx->ctx_res_w = RES_NONE;
3824 #if ENABLE_HUSH_CASE
3825 if (ctx->ctx_res_w == RES_MATCH)
3826 ctx->ctx_res_w = RES_CASE_BODY;
3827 if (ctx->ctx_res_w == RES_CASE)
3828 ctx->ctx_res_w = RES_CASE_IN;
3830 ctx->command = NULL; /* trick done_command below */
3831 /* Create the memory for command, roughly:
3832 * ctx->pipe->cmds = new struct command;
3833 * ctx->command = &ctx->pipe->cmds[0];
3836 //debug_print_tree(ctx->list_head, 10);
3838 debug_printf_parse("done_pipe return\n");
3841 static void initialize_context(struct parse_context *ctx)
3843 memset(ctx, 0, sizeof(*ctx));
3844 if (MAYBE_ASSIGNMENT != 0)
3845 ctx->is_assignment = MAYBE_ASSIGNMENT;
3846 ctx->pipe = ctx->list_head = new_pipe();
3847 /* Create the memory for command, roughly:
3848 * ctx->pipe->cmds = new struct command;
3849 * ctx->command = &ctx->pipe->cmds[0];
3854 /* If a reserved word is found and processed, parse context is modified
3855 * and 1 is returned.
3858 struct reserved_combo {
3861 unsigned char assignment_flag;
3865 FLAG_END = (1 << RES_NONE ),
3867 FLAG_IF = (1 << RES_IF ),
3868 FLAG_THEN = (1 << RES_THEN ),
3869 FLAG_ELIF = (1 << RES_ELIF ),
3870 FLAG_ELSE = (1 << RES_ELSE ),
3871 FLAG_FI = (1 << RES_FI ),
3873 # if ENABLE_HUSH_LOOPS
3874 FLAG_FOR = (1 << RES_FOR ),
3875 FLAG_WHILE = (1 << RES_WHILE),
3876 FLAG_UNTIL = (1 << RES_UNTIL),
3877 FLAG_DO = (1 << RES_DO ),
3878 FLAG_DONE = (1 << RES_DONE ),
3879 FLAG_IN = (1 << RES_IN ),
3881 # if ENABLE_HUSH_CASE
3882 FLAG_MATCH = (1 << RES_MATCH),
3883 FLAG_ESAC = (1 << RES_ESAC ),
3885 FLAG_START = (1 << RES_XXXX ),
3888 static const struct reserved_combo* match_reserved_word(o_string *word)
3890 /* Mostly a list of accepted follow-up reserved words.
3891 * FLAG_END means we are done with the sequence, and are ready
3892 * to turn the compound list into a command.
3893 * FLAG_START means the word must start a new compound list.
3895 static const struct reserved_combo reserved_list[] = {
3897 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3898 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3899 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3900 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3901 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3902 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3904 # if ENABLE_HUSH_LOOPS
3905 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3906 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3907 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3908 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3909 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3910 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3912 # if ENABLE_HUSH_CASE
3913 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3914 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3917 const struct reserved_combo *r;
3919 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3920 if (strcmp(word->data, r->literal) == 0)
3925 /* Return NULL: not a keyword, else: keyword
3927 static const struct reserved_combo* reserved_word(struct parse_context *ctx)
3929 # if ENABLE_HUSH_CASE
3930 static const struct reserved_combo reserved_match = {
3931 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3934 const struct reserved_combo *r;
3936 if (ctx->word.has_quoted_part)
3938 r = match_reserved_word(&ctx->word);
3940 return r; /* NULL */
3942 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3943 # if ENABLE_HUSH_CASE
3944 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3945 /* "case word IN ..." - IN part starts first MATCH part */
3946 r = &reserved_match;
3949 if (r->flag == 0) { /* '!' */
3950 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3951 syntax_error("! ! command");
3952 ctx->ctx_res_w = RES_SNTX;
3954 ctx->ctx_inverted = 1;
3957 if (r->flag & FLAG_START) {
3958 struct parse_context *old;
3960 old = xmemdup(ctx, sizeof(*ctx));
3961 debug_printf_parse("push stack %p\n", old);
3962 initialize_context(ctx);
3964 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3965 syntax_error_at(ctx->word.data);
3966 ctx->ctx_res_w = RES_SNTX;
3969 /* "{...} fi" is ok. "{...} if" is not
3971 * if { echo foo; } then { echo bar; } fi */
3972 if (ctx->command->group)
3973 done_pipe(ctx, PIPE_SEQ);
3976 ctx->ctx_res_w = r->res;
3977 ctx->old_flag = r->flag;
3978 ctx->is_assignment = r->assignment_flag;
3979 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
3981 if (ctx->old_flag & FLAG_END) {
3982 struct parse_context *old;
3984 done_pipe(ctx, PIPE_SEQ);
3985 debug_printf_parse("pop stack %p\n", ctx->stack);
3987 old->command->group = ctx->list_head;
3988 old->command->cmd_type = CMD_NORMAL;
3990 /* At this point, the compound command's string is in
3991 * ctx->as_string... except for the leading keyword!
3992 * Consider this example: "echo a | if true; then echo a; fi"
3993 * ctx->as_string will contain "true; then echo a; fi",
3994 * with "if " remaining in old->as_string!
3998 int len = old->as_string.length;
3999 /* Concatenate halves */
4000 o_addstr(&old->as_string, ctx->as_string.data);
4001 o_free(&ctx->as_string);
4002 /* Find where leading keyword starts in first half */
4003 str = old->as_string.data + len;
4004 if (str > old->as_string.data)
4005 str--; /* skip whitespace after keyword */
4006 while (str > old->as_string.data && isalpha(str[-1]))
4008 /* Ugh, we're done with this horrid hack */
4009 old->command->group_as_string = xstrdup(str);
4010 debug_printf_parse("pop, remembering as:'%s'\n",
4011 old->command->group_as_string);
4014 *ctx = *old; /* physical copy */
4019 #endif /* HAS_KEYWORDS */
4021 /* Word is complete, look at it and update parsing context.
4022 * Normal return is 0. Syntax errors return 1.
4023 * Note: on return, word is reset, but not o_free'd!
4025 static int done_word(struct parse_context *ctx)
4027 struct command *command = ctx->command;
4029 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4030 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
4031 debug_printf_parse("done_word return 0: true null, ignored\n");
4035 if (ctx->pending_redirect) {
4036 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4037 * only if run as "bash", not "sh" */
4038 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
4040 * If the redirection operator is "<<" or "<<-", the word
4041 * that follows the redirection operator shall be
4042 * subjected to quote removal; it is unspecified whether
4043 * any of the other expansions occur. For the other
4044 * redirection operators, the word that follows the
4045 * redirection operator shall be subjected to tilde
4046 * expansion, parameter expansion, command substitution,
4047 * arithmetic expansion, and quote removal.
4048 * Pathname expansion shall not be performed
4049 * on the word by a non-interactive shell; an interactive
4050 * shell may perform it, but shall do so only when
4051 * the expansion would result in one word."
4053 //bash does not do parameter/command substitution or arithmetic expansion
4054 //for _heredoc_ redirection word: these constructs look for exact eof marker
4058 // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4060 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
4061 /* Cater for >\file case:
4062 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4063 * Same with heredocs:
4064 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4066 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4067 unbackslash(ctx->pending_redirect->rd_filename);
4068 /* Is it <<"HEREDOC"? */
4069 if (ctx->word.has_quoted_part) {
4070 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4073 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
4074 ctx->pending_redirect = NULL;
4077 # if ENABLE_HUSH_CASE
4078 if (ctx->ctx_dsemicolon
4079 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4081 /* already done when ctx_dsemicolon was set to 1: */
4082 /* ctx->ctx_res_w = RES_MATCH; */
4083 ctx->ctx_dsemicolon = 0;
4086 if (!command->argv /* if it's the first word... */
4087 # if ENABLE_HUSH_LOOPS
4088 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4089 && ctx->ctx_res_w != RES_IN
4091 # if ENABLE_HUSH_CASE
4092 && ctx->ctx_res_w != RES_CASE
4095 const struct reserved_combo *reserved;
4096 reserved = reserved_word(ctx);
4097 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
4099 # if ENABLE_HUSH_LINENO_VAR
4103 * If we don't close the pipe _now_, immediately after "do", lineno logic
4104 * sees "cmd" as starting at "do" - i.e., at the previous line.
4107 IF_HUSH_IF(|| reserved->res == RES_THEN)
4108 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4109 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4110 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4112 done_pipe(ctx, PIPE_SEQ);
4115 o_reset_to_empty_unquoted(&ctx->word);
4116 debug_printf_parse("done_word return %d\n",
4117 (ctx->ctx_res_w == RES_SNTX));
4118 return (ctx->ctx_res_w == RES_SNTX);
4120 # if defined(CMD_SINGLEWORD_NOGLOB)
4123 || strcmp(ctx->word.data, "[[") == 0
4125 /* In bash, local/export/readonly are special, args
4126 * are assignments and therefore expansion of them
4127 * should be "one-word" expansion:
4128 * $ export i=`echo 'a b'` # one arg: "i=a b"
4130 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4131 * ls: cannot access i=a: No such file or directory
4132 * ls: cannot access b: No such file or directory
4133 * Note: bash 3.2.33(1) does this only if export word
4134 * itself is not quoted:
4135 * $ export i=`echo 'aaa bbb'`; echo "$i"
4137 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4140 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4141 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4142 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
4144 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4149 #endif /* HAS_KEYWORDS */
4151 if (command->group) {
4152 /* "{ echo foo; } echo bar" - bad */
4153 syntax_error_at(ctx->word.data);
4154 debug_printf_parse("done_word return 1: syntax error, "
4155 "groups and arglists don't mix\n");
4159 /* If this word wasn't an assignment, next ones definitely
4160 * can't be assignments. Even if they look like ones. */
4161 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4162 && ctx->is_assignment != WORD_IS_KEYWORD
4164 ctx->is_assignment = NOT_ASSIGNMENT;
4166 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
4167 command->assignment_cnt++;
4168 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4170 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4171 ctx->is_assignment = MAYBE_ASSIGNMENT;
4173 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4174 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
4175 debug_print_strings("word appended to argv", command->argv);
4178 #if ENABLE_HUSH_LOOPS
4179 if (ctx->ctx_res_w == RES_FOR) {
4180 if (ctx->word.has_quoted_part
4181 || !is_well_formed_var_name(command->argv[0], '\0')
4183 /* bash says just "not a valid identifier" */
4184 syntax_error("not a valid identifier in for");
4187 /* Force FOR to have just one word (variable name) */
4188 /* NB: basically, this makes hush see "for v in ..."
4189 * syntax as if it is "for v; in ...". FOR and IN become
4190 * two pipe structs in parse tree. */
4191 done_pipe(ctx, PIPE_SEQ);
4194 #if ENABLE_HUSH_CASE
4195 /* Force CASE to have just one word */
4196 if (ctx->ctx_res_w == RES_CASE) {
4197 done_pipe(ctx, PIPE_SEQ);
4201 o_reset_to_empty_unquoted(&ctx->word);
4203 debug_printf_parse("done_word return 0\n");
4208 /* Peek ahead in the input to find out if we have a "&n" construct,
4209 * as in "2>&1", that represents duplicating a file descriptor.
4211 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4212 * REDIRFD_SYNTAX_ERR if syntax error,
4213 * REDIRFD_TO_FILE if no & was seen,
4214 * or the number found.
4217 #define parse_redir_right_fd(as_string, input) \
4218 parse_redir_right_fd(input)
4220 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4226 return REDIRFD_TO_FILE;
4228 ch = i_getch(input); /* get the & */
4229 nommu_addchr(as_string, ch);
4232 ch = i_getch(input);
4233 nommu_addchr(as_string, ch);
4234 return REDIRFD_CLOSE;
4238 while (ch != EOF && isdigit(ch)) {
4239 d = d*10 + (ch-'0');
4241 ch = i_getch(input);
4242 nommu_addchr(as_string, ch);
4247 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4249 bb_error_msg("ambiguous redirect");
4250 return REDIRFD_SYNTAX_ERR;
4253 /* Return code is 0 normal, 1 if a syntax error is detected
4255 static int parse_redirect(struct parse_context *ctx,
4258 struct in_str *input)
4260 struct command *command = ctx->command;
4261 struct redir_struct *redir;
4262 struct redir_struct **redirp;
4265 dup_num = REDIRFD_TO_FILE;
4266 if (style != REDIRECT_HEREDOC) {
4267 /* Check for a '>&1' type redirect */
4268 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4269 if (dup_num == REDIRFD_SYNTAX_ERR)
4272 int ch = i_peek_and_eat_bkslash_nl(input);
4273 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4274 if (dup_num) { /* <<-... */
4275 ch = i_getch(input);
4276 nommu_addchr(&ctx->as_string, ch);
4281 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4282 int ch = i_peek_and_eat_bkslash_nl(input);
4284 /* >|FILE redirect ("clobbering" >).
4285 * Since we do not support "set -o noclobber" yet,
4286 * >| and > are the same for now. Just eat |.
4288 ch = i_getch(input);
4289 nommu_addchr(&ctx->as_string, ch);
4293 /* Create a new redir_struct and append it to the linked list */
4294 redirp = &command->redirects;
4295 while ((redir = *redirp) != NULL) {
4296 redirp = &(redir->next);
4298 *redirp = redir = xzalloc(sizeof(*redir));
4299 /* redir->next = NULL; */
4300 /* redir->rd_filename = NULL; */
4301 redir->rd_type = style;
4302 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4304 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4305 redir_table[style].descrip);
4307 redir->rd_dup = dup_num;
4308 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4309 /* Erik had a check here that the file descriptor in question
4310 * is legit; I postpone that to "run time"
4311 * A "-" representation of "close me" shows up as a -3 here */
4312 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4313 redir->rd_fd, redir->rd_dup);
4315 #if 0 /* Instead we emit error message at run time */
4316 if (ctx->pending_redirect) {
4317 /* For example, "cmd > <file" */
4318 syntax_error("invalid redirect");
4321 /* Set ctx->pending_redirect, so we know what to do at the
4322 * end of the next parsed word. */
4323 ctx->pending_redirect = redir;
4328 /* If a redirect is immediately preceded by a number, that number is
4329 * supposed to tell which file descriptor to redirect. This routine
4330 * looks for such preceding numbers. In an ideal world this routine
4331 * needs to handle all the following classes of redirects...
4332 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4333 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4334 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4335 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4337 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4339 * ... If n is quoted, the number shall not be recognized as part of
4340 * the redirection expression. For example:
4342 * writes the character 2 into file a"
4343 * We are getting it right by setting ->has_quoted_part on any \<char>
4345 * A -1 return means no valid number was found,
4346 * the caller should use the appropriate default for this redirection.
4348 static int redirect_opt_num(o_string *o)
4352 if (o->data == NULL)
4354 num = bb_strtou(o->data, NULL, 10);
4355 if (errno || num < 0)
4357 o_reset_to_empty_unquoted(o);
4362 #define fetch_till_str(as_string, input, word, skip_tabs) \
4363 fetch_till_str(input, word, skip_tabs)
4365 static char *fetch_till_str(o_string *as_string,
4366 struct in_str *input,
4370 o_string heredoc = NULL_O_STRING;
4372 int prev = 0; /* not \ */
4375 /* Starting with "" is necessary for this case:
4381 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4386 ch = i_getch(input);
4388 nommu_addchr(as_string, ch);
4389 if (ch == '\n' || ch == EOF) {
4391 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4392 /* End-of-line, and not a line continuation */
4393 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4394 heredoc.data[past_EOL] = '\0';
4395 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
4396 return heredoc.data;
4399 /* This is a new line.
4400 * Remember position and backslash-escaping status.
4402 o_addchr(&heredoc, ch);
4405 past_EOL = heredoc.length;
4406 /* Get 1st char of next line, possibly skipping leading tabs */
4408 ch = i_getch(input);
4410 nommu_addchr(as_string, ch);
4411 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4412 /* If this immediately ended the line,
4413 * go back to end-of-line checks.
4416 goto check_heredoc_end;
4419 /* Backslash-line continuation in an unquoted
4420 * heredoc. This does not need special handling
4421 * for heredoc body (unquoted heredocs are
4422 * expanded on "execution" and that would take
4423 * care of this case too), but not the case
4424 * of line continuation *in terminator*:
4430 heredoc.data[--heredoc.length] = '\0';
4431 prev = 0; /* not '\' */
4437 return NULL; /* error */
4439 o_addchr(&heredoc, ch);
4440 nommu_addchr(as_string, ch);
4441 if (prev == '\\' && ch == '\\')
4442 /* Correctly handle foo\\<eol> (not a line cont.) */
4443 prev = 0; /* not '\' */
4449 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4450 * and load them all. There should be exactly heredoc_cnt of them.
4453 #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4454 fetch_heredocs(pi, heredoc_cnt, input)
4456 static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
4458 while (pi && heredoc_cnt) {
4460 struct command *cmd = pi->cmds;
4462 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4464 cmd->argv ? cmd->argv[0] : "NONE"
4466 for (i = 0; i < pi->num_cmds; i++) {
4467 struct redir_struct *redir = cmd->redirects;
4469 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
4470 i, cmd->argv ? cmd->argv[0] : "NONE");
4472 if (redir->rd_type == REDIRECT_HEREDOC) {
4475 redir->rd_type = REDIRECT_HEREDOC2;
4476 /* redir->rd_dup is (ab)used to indicate <<- */
4477 p = fetch_till_str(as_string, input,
4478 redir->rd_filename, redir->rd_dup);
4480 syntax_error("unexpected EOF in here document");
4483 free(redir->rd_filename);
4484 redir->rd_filename = p;
4487 redir = redir->next;
4490 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4491 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4492 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4493 if (heredoc_cnt < 0)
4494 return heredoc_cnt; /* error */
4504 static int run_list(struct pipe *pi);
4506 #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4507 parse_stream(heredoc_cnt_ptr, input, end_trigger)
4509 static struct pipe *parse_stream(char **pstring,
4510 int *heredoc_cnt_ptr,
4511 struct in_str *input,
4514 /* Returns number of heredocs not yet consumed,
4517 static int parse_group(struct parse_context *ctx,
4518 struct in_str *input, int ch)
4520 /* ctx->word contains characters seen prior to ( or {.
4521 * Typically it's empty, but for function defs,
4522 * it contains function name (without '()'). */
4524 # define as_string NULL
4526 char *as_string = NULL;
4528 struct pipe *pipe_list;
4529 int heredoc_cnt = 0;
4531 struct command *command = ctx->command;
4533 debug_printf_parse("parse_group entered\n");
4534 #if ENABLE_HUSH_FUNCTIONS
4535 if (ch == '(' && !ctx->word.has_quoted_part) {
4536 if (ctx->word.length)
4540 goto skip; /* (... */
4541 if (command->argv[1]) { /* word word ... (... */
4542 syntax_error_unexpected_ch('(');
4545 /* it is "word(..." or "word (..." */
4547 ch = i_getch(input);
4548 while (ch == ' ' || ch == '\t');
4550 syntax_error_unexpected_ch(ch);
4553 nommu_addchr(&ctx->as_string, ch);
4555 ch = i_getch(input);
4556 while (ch == ' ' || ch == '\t' || ch == '\n');
4557 if (ch != '{' && ch != '(') {
4558 syntax_error_unexpected_ch(ch);
4561 nommu_addchr(&ctx->as_string, ch);
4562 command->cmd_type = CMD_FUNCDEF;
4567 #if 0 /* Prevented by caller */
4568 if (command->argv /* word [word]{... */
4569 || ctx->word.length /* word{... */
4570 || ctx->word.has_quoted_part /* ""{... */
4573 debug_printf_parse("parse_group return -1: "
4574 "syntax error, groups and arglists don't mix\n");
4579 IF_HUSH_FUNCTIONS(skip:)
4584 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4585 command->cmd_type = CMD_SUBSHELL;
4587 /* bash does not allow "{echo...", requires whitespace */
4589 if (ch != ' ' && ch != '\t' && ch != '\n'
4590 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4592 syntax_error_unexpected_ch(ch);
4596 ch = i_getch(input);
4597 nommu_addchr(&ctx->as_string, ch);
4601 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4602 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4603 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
4606 o_addstr(&ctx->as_string, as_string);
4609 /* empty ()/{} or parse error? */
4610 if (!pipe_list || pipe_list == ERR_PTR) {
4611 /* parse_stream already emitted error msg */
4614 debug_printf_parse("parse_group return -1: "
4615 "parse_stream returned %p\n", pipe_list);
4619 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4620 command->group_as_string = as_string;
4621 debug_printf_parse("end of group, remembering as:'%s'\n",
4622 command->group_as_string);
4625 #if ENABLE_HUSH_FUNCTIONS
4626 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4627 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4628 struct command *cmd2;
4630 cmd2 = xzalloc(sizeof(*cmd2));
4631 cmd2->cmd_type = CMD_SUBSHELL;
4632 cmd2->group = pipe_list;
4635 cmd2->group_as_string = command->group_as_string;
4636 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4639 pipe_list = new_pipe();
4640 pipe_list->cmds = cmd2;
4641 pipe_list->num_cmds = 1;
4645 command->group = pipe_list;
4647 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4649 /* command remains "open", available for possible redirects */
4653 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4654 /* Subroutines for copying $(...) and `...` things */
4656 static int add_till_single_quote(o_string *dest, struct in_str *input)
4659 int ch = i_getch(input);
4661 syntax_error_unterm_ch('\'');
4669 static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4672 int ch = i_getch(input);
4674 syntax_error_unterm_ch('\'');
4679 o_addqchr(dest, ch);
4682 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4683 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4684 static int add_till_double_quote(o_string *dest, struct in_str *input)
4687 int ch = i_getch(input);
4689 syntax_error_unterm_ch('"');
4694 if (ch == '\\') { /* \x. Copy both chars. */
4696 ch = i_getch(input);
4700 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4705 //if (ch == '$') ...
4708 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4710 * "Within the backquoted style of command substitution, backslash
4711 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4712 * The search for the matching backquote shall be satisfied by the first
4713 * backquote found without a preceding backslash; during this search,
4714 * if a non-escaped backquote is encountered within a shell comment,
4715 * a here-document, an embedded command substitution of the $(command)
4716 * form, or a quoted string, undefined results occur. A single-quoted
4717 * or double-quoted string that begins, but does not end, within the
4718 * "`...`" sequence produces undefined results."
4720 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4722 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4725 int ch = i_getch(input);
4729 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4730 ch = i_getch(input);
4734 && (!in_dquote || ch != '"')
4736 o_addchr(dest, '\\');
4740 syntax_error_unterm_ch('`');
4746 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4747 * quoting and nested ()s.
4748 * "With the $(command) style of command substitution, all characters
4749 * following the open parenthesis to the matching closing parenthesis
4750 * constitute the command. Any valid shell script can be used for command,
4751 * except a script consisting solely of redirections which produces
4752 * unspecified results."
4754 * echo $(echo '(TEST)' BEST) (TEST) BEST
4755 * echo $(echo 'TEST)' BEST) TEST) BEST
4756 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4758 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4759 * can contain arbitrary constructs, just like $(cmd).
4760 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4761 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4763 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4764 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4767 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4768 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4769 char end_char2 = end_ch >> 8;
4771 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4773 #if ENABLE_HUSH_INTERACTIVE
4774 G.promptmode = 1; /* PS2 */
4776 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4779 ch = i_getch(input);
4781 syntax_error_unterm_ch(end_ch);
4785 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4791 /* we look for closing )) of $((EXPR)) */
4792 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4793 i_getch(input); /* eat second ')' */
4798 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
4799 if (ch == '(' || ch == '{') {
4800 ch = (ch == '(' ? ')' : '}');
4801 if (!add_till_closing_bracket(dest, input, ch))
4807 if (!add_till_single_quote(dest, input))
4813 if (!add_till_double_quote(dest, input))
4819 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4825 /* \x. Copy verbatim. Important for \(, \) */
4826 ch = i_getch(input);
4828 syntax_error_unterm_ch(end_ch);
4833 /* "backslash+newline", ignore both */
4834 o_delchr(dest); /* undo insertion of '\' */
4839 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
4843 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
4846 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4848 /* Return code: 0 for OK, 1 for syntax error */
4850 #define parse_dollar(as_string, dest, input, quote_mask) \
4851 parse_dollar(dest, input, quote_mask)
4852 #define as_string NULL
4854 static int parse_dollar(o_string *as_string,
4856 struct in_str *input, unsigned char quote_mask)
4858 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4860 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4863 ch = i_getch(input);
4864 nommu_addchr(as_string, ch);
4866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4868 debug_printf_parse(": '%c'\n", ch);
4869 o_addchr(dest, ch | quote_mask);
4871 ch = i_peek_and_eat_bkslash_nl(input);
4872 if (!isalnum(ch) && ch != '_') {
4873 /* End of variable name reached */
4876 ch = i_getch(input);
4877 nommu_addchr(as_string, ch);
4879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4880 } else if (isdigit(ch)) {
4882 ch = i_getch(input);
4883 nommu_addchr(as_string, ch);
4884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4885 debug_printf_parse(": '%c'\n", ch);
4886 o_addchr(dest, ch | quote_mask);
4887 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4888 } else switch (ch) {
4890 case '!': /* last bg pid */
4891 case '?': /* last exit code */
4892 case '#': /* number of args */
4893 case '*': /* args */
4894 case '@': /* args */
4895 goto make_one_char_var;
4899 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4901 ch = i_getch(input); /* eat '{' */
4902 nommu_addchr(as_string, ch);
4904 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4905 /* It should be ${?}, or ${#var},
4906 * or even ${?+subst} - operator acting on a special variable,
4907 * or the beginning of variable name.
4910 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4913 syntax_error_unterm_str("${name}");
4914 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4917 nommu_addchr(as_string, ch);
4921 /* It's possible to just call add_till_closing_bracket() at this point.
4922 * However, this regresses some of our testsuite cases
4923 * which check invalid constructs like ${%}.
4924 * Oh well... let's check that the var name part is fine... */
4930 debug_printf_parse(": '%c'\n", ch);
4932 ch = i_getch(input);
4933 nommu_addchr(as_string, ch);
4937 if (!isalnum(ch) && ch != '_') {
4939 unsigned char last_ch;
4940 /* handle parameter expansions
4941 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4943 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4944 if (len_single_ch != '#'
4945 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4946 || i_peek(input) != '}'
4948 goto bad_dollar_syntax;
4950 /* else: it's "length of C" ${#C} op,
4951 * where C is a single char
4952 * special var name, e.g. ${#!}.
4955 /* Eat everything until closing '}' (or ':') */
4959 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4961 /* It's ${var:N[:M]} thing */
4962 end_ch = '}' * 0x100 + ':';
4964 if (BASH_PATTERN_SUBST
4967 /* It's ${var/[/]pattern[/repl]} thing */
4968 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4970 nommu_addchr(as_string, '/');
4973 end_ch = '}' * 0x100 + '/';
4976 /* The pattern can't be empty.
4977 * IOW: if the first char after "${v//" is a slash,
4978 * it does not terminate the pattern - it's the first char of the pattern:
4979 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4980 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4982 if (i_peek(input) == '/') {
4983 o_addchr(dest, i_getch(input));
4988 #if ENABLE_HUSH_DOLLAR_OPS
4989 last_ch = add_till_closing_bracket(dest, input, end_ch);
4990 if (last_ch == 0) /* error? */
4993 #error Simple code to only allow ${var} is not implemented
4996 o_addstr(as_string, dest->data + pos);
4997 o_addchr(as_string, last_ch);
5000 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5001 && (end_ch & 0xff00)
5003 /* close the first block: */
5004 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5005 /* while parsing N from ${var:N[:M]}
5006 * or pattern from ${var/[/]pattern[/repl]} */
5007 if ((end_ch & 0xff) == last_ch) {
5008 /* got ':' or '/'- parse the rest */
5013 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
5014 /* it's ${var:N} - emulate :999999999 */
5015 o_addstr(dest, "999999999");
5016 } /* else: it's ${var/[/]pattern} */
5020 len_single_ch = 0; /* it can't be ${#C} op */
5022 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5025 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
5029 ch = i_getch(input);
5030 nommu_addchr(as_string, ch);
5031 # if ENABLE_FEATURE_SH_MATH
5032 if (i_peek_and_eat_bkslash_nl(input) == '(') {
5033 ch = i_getch(input);
5034 nommu_addchr(as_string, ch);
5035 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5036 o_addchr(dest, /*quote_mask |*/ '+');
5039 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5040 return 0; /* error */
5042 o_addstr(as_string, dest->data + pos);
5043 o_addchr(as_string, ')');
5044 o_addchr(as_string, ')');
5046 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5050 # if ENABLE_HUSH_TICK
5051 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5052 o_addchr(dest, quote_mask | '`');
5055 if (!add_till_closing_bracket(dest, input, ')'))
5056 return 0; /* error */
5058 o_addstr(as_string, dest->data + pos);
5059 o_addchr(as_string, ')');
5061 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5069 /* TODO: $_ and $-: */
5070 /* $_ Shell or shell script name; or last argument of last command
5071 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5072 * but in command's env, set to full pathname used to invoke it */
5073 /* $- Option flags set by set builtin or shell options (-i etc) */
5074 ch = i_getch(input);
5075 nommu_addchr(as_string, ch);
5076 ch = i_peek_and_eat_bkslash_nl(input);
5077 if (isalnum(ch)) { /* it's $_name or $_123 */
5084 o_addQchr(dest, '$');
5086 debug_printf_parse("parse_dollar return 1 (ok)\n");
5092 #define encode_string(as_string, dest, input, dquote_end) \
5093 encode_string(dest, input, dquote_end)
5094 #define as_string NULL
5096 static int encode_string(o_string *as_string,
5098 struct in_str *input,
5105 ch = i_getch(input);
5107 nommu_addchr(as_string, ch);
5108 if (ch == dquote_end) { /* may be only '"' or EOF */
5109 debug_printf_parse("encode_string return 1 (ok)\n");
5112 /* note: can't move it above ch == dquote_end check! */
5114 syntax_error_unterm_ch('"');
5115 return 0; /* error */
5119 next = i_peek(input);
5121 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
5122 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5125 /* Testcase: in interactive shell a file with
5126 * echo "unterminated string\<eof>
5129 syntax_error_unterm_ch('"');
5130 return 0; /* error */
5133 * "The backslash retains its special meaning [in "..."]
5134 * only when followed by one of the following characters:
5135 * $, `, ", \, or <newline>. A double quote may be quoted
5136 * within double quotes by preceding it with a backslash."
5137 * NB: in (unquoted) heredoc, above does not apply to ",
5138 * therefore we check for it by "next == dquote_end" cond.
5140 if (next == dquote_end || strchr("$`\\\n", next)) {
5141 ch = i_getch(input); /* eat next */
5143 goto again; /* skip \<newline> */
5144 } /* else: ch remains == '\\', and we double it below: */
5145 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
5146 nommu_addchr(as_string, ch);
5150 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5151 debug_printf_parse("encode_string return 0: "
5152 "parse_dollar returned 0 (error)\n");
5157 #if ENABLE_HUSH_TICK
5159 //unsigned pos = dest->length;
5160 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5161 o_addchr(dest, 0x80 | '`');
5162 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5163 return 0; /* error */
5164 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5165 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5169 o_addQchr(dest, ch);
5175 * Scan input until EOF or end_trigger char.
5176 * Return a list of pipes to execute, or NULL on EOF
5177 * or if end_trigger character is met.
5178 * On syntax error, exit if shell is not interactive,
5179 * reset parsing machinery and start parsing anew,
5180 * or return ERR_PTR.
5182 static struct pipe *parse_stream(char **pstring,
5183 int *heredoc_cnt_ptr,
5184 struct in_str *input,
5187 struct parse_context ctx;
5190 /* Single-quote triggers a bypass of the main loop until its mate is
5191 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
5193 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5194 end_trigger ? end_trigger : 'X');
5197 initialize_context(&ctx);
5199 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5202 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
5204 /* We used to separate words on $IFS here. This was wrong.
5205 * $IFS is used only for word splitting when $var is expanded,
5206 * here we should use blank chars as separators, not $IFS
5211 const char *is_blank;
5212 const char *is_special;
5216 redir_type redir_style;
5218 ch = i_getch(input);
5219 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5220 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5225 syntax_error_unterm_str("here document");
5228 if (end_trigger == ')') {
5229 syntax_error_unterm_ch('(');
5232 if (end_trigger == '}') {
5233 syntax_error_unterm_ch('{');
5237 if (done_word(&ctx)) {
5240 o_free_and_set_NULL(&ctx.word);
5241 done_pipe(&ctx, PIPE_SEQ);
5243 /* If we got nothing... */
5244 /* (this makes bare "&" cmd a no-op.
5245 * bash says: "syntax error near unexpected token '&'") */
5246 if (pi->num_cmds == 0
5247 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
5253 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
5255 *pstring = ctx.as_string.data;
5257 o_free(&ctx.as_string);
5259 // heredoc_cnt must be 0 here anyway
5260 //if (heredoc_cnt_ptr)
5261 // *heredoc_cnt_ptr = heredoc_cnt;
5263 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5264 debug_printf_parse("parse_stream return %p\n", pi);
5268 /* Handle "'" and "\" first, as they won't play nice with
5269 * i_peek_and_eat_bkslash_nl() anyway:
5277 ch = i_getch(input);
5279 continue; /* drop \<newline>, get next char */
5280 nommu_addchr(&ctx.as_string, '\\');
5281 o_addchr(&ctx.word, '\\');
5283 /* Testcase: eval 'echo Ok\' */
5284 /* bash-4.3.43 was removing backslash,
5285 * but 4.4.19 retains it, most other shells too
5287 continue; /* get next char */
5289 /* Example: echo Hello \2>file
5290 * we need to know that word 2 is quoted
5292 ctx.word.has_quoted_part = 1;
5293 nommu_addchr(&ctx.as_string, ch);
5294 o_addchr(&ctx.word, ch);
5295 continue; /* get next char */
5297 nommu_addchr(&ctx.as_string, ch);
5299 ctx.word.has_quoted_part = 1;
5300 next = i_getch(input);
5301 if (next == '\'' && !ctx.pending_redirect)
5302 goto insert_empty_quoted_str_marker;
5307 syntax_error_unterm_ch('\'');
5310 nommu_addchr(&ctx.as_string, ch);
5313 if (ch == SPECIAL_VAR_SYMBOL) {
5314 /* Convert raw ^C to corresponding special variable reference */
5315 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5316 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5318 o_addqchr(&ctx.word, ch);
5319 ch = i_getch(input);
5321 continue; /* get next char */
5326 next = i_peek_and_eat_bkslash_nl(input);
5328 is_special = "{}<>;&|()#" /* special outside of "str" */
5329 "$\"" IF_HUSH_TICK("`") /* always special */
5330 SPECIAL_VAR_SYMBOL_STR;
5331 /* Are { and } special here? */
5332 if (ctx.command->argv /* word [word]{... - non-special */
5333 || ctx.word.length /* word{... - non-special */
5334 || ctx.word.has_quoted_part /* ""{... - non-special */
5335 || (next != ';' /* }; - special */
5336 && next != ')' /* }) - special */
5337 && next != '(' /* {( - special */
5338 && next != '&' /* }& and }&& ... - special */
5339 && next != '|' /* }|| ... - special */
5340 && !strchr(defifs, next) /* {word - non-special */
5343 /* They are not special, skip "{}" */
5346 is_special = strchr(is_special, ch);
5347 is_blank = strchr(defifs, ch);
5349 if (!is_special && !is_blank) { /* ordinary char */
5351 o_addQchr(&ctx.word, ch);
5352 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5353 || ctx.is_assignment == WORD_IS_KEYWORD)
5355 && is_well_formed_var_name(ctx.word.data, '=')
5357 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5358 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5364 #if ENABLE_HUSH_LINENO_VAR
5366 * "while ...; do<whitespace><newline>
5368 * would think that "cmd" starts in <whitespace> -
5369 * i.e., at the previous line.
5370 * We need to skip all whitespace before newlines.
5372 while (ch != '\n') {
5373 next = i_peek(input);
5374 if (next != ' ' && next != '\t' && next != '\n')
5375 break; /* next char is not ws */
5376 ch = i_getch(input);
5378 /* ch == last eaten whitespace char */
5380 if (done_word(&ctx)) {
5384 /* Is this a case when newline is simply ignored?
5386 * "cmd | <newline> cmd ..."
5387 * "case ... in <newline> word) ..."
5389 if (IS_NULL_CMD(ctx.command)
5390 && ctx.word.length == 0
5391 && !ctx.word.has_quoted_part
5394 /* This newline can be ignored. But...
5395 * Without check #1, interactive shell
5396 * ignores even bare <newline>,
5397 * and shows the continuation prompt:
5398 * ps1_prompt$ <enter>
5399 * ps2> _ <=== wrong, should be ps1
5400 * Without check #2, "cmd & <newline>"
5401 * is similarly mistreated.
5402 * (BTW, this makes "cmd & cmd"
5403 * and "cmd && cmd" non-orthogonal.
5404 * Really, ask yourself, why
5405 * "cmd && <newline>" doesn't start
5406 * cmd but waits for more input?
5407 * The only reason is that it might be
5408 * a "cmd1 && <nl> cmd2 &" construct,
5409 * cmd1 may need to run in BG).
5411 struct pipe *pi = ctx.list_head;
5412 if (pi->num_cmds != 0 /* check #1 */
5413 && pi->followup != PIPE_BG /* check #2 */
5418 /* Treat newline as a command separator. */
5419 done_pipe(&ctx, PIPE_SEQ);
5420 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
5422 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5423 if (heredoc_cnt != 0)
5426 ctx.is_assignment = MAYBE_ASSIGNMENT;
5427 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5429 /* note: if (is_blank) continue;
5430 * will still trigger for us */
5434 /* "cmd}" or "cmd }..." without semicolon or &:
5435 * } is an ordinary char in this case, even inside { cmd; }
5436 * Pathological example: { ""}; } should exec "}" cmd
5439 if (ctx.word.length != 0 /* word} */
5440 || ctx.word.has_quoted_part /* ""} */
5444 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5445 /* Generally, there should be semicolon: "cmd; }"
5446 * However, bash allows to omit it if "cmd" is
5447 * a group. Examples:
5450 * { echo 0 >&2 | { echo 1; } }
5451 * { while false; do :; done }
5452 * { case a in b) ;; esac }
5454 if (ctx.command->group)
5458 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5459 /* Can't be an end of {cmd}, skip the check */
5460 goto skip_end_trigger;
5461 /* else: } does terminate a group */
5464 if (end_trigger && end_trigger == ch
5465 && (ch != ';' || heredoc_cnt == 0)
5466 #if ENABLE_HUSH_CASE
5468 || ctx.ctx_res_w != RES_MATCH
5469 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
5473 if (done_word(&ctx)) {
5476 done_pipe(&ctx, PIPE_SEQ);
5477 ctx.is_assignment = MAYBE_ASSIGNMENT;
5478 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5479 /* Do we sit outside of any if's, loops or case's? */
5481 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5483 o_free_and_set_NULL(&ctx.word);
5485 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5487 *pstring = ctx.as_string.data;
5489 o_free(&ctx.as_string);
5491 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5492 /* Example: bare "{ }", "()" */
5493 G.last_exitcode = 2; /* bash compat */
5494 syntax_error_unexpected_ch(ch);
5497 if (heredoc_cnt_ptr)
5498 *heredoc_cnt_ptr = heredoc_cnt;
5499 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5500 debug_printf_parse("parse_stream return %p: "
5501 "end_trigger char found\n",
5504 return ctx.list_head;
5511 /* Catch <, > before deciding whether this word is
5512 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5515 redir_fd = redirect_opt_num(&ctx.word);
5516 if (done_word(&ctx)) {
5519 redir_style = REDIRECT_OVERWRITE;
5521 redir_style = REDIRECT_APPEND;
5522 ch = i_getch(input);
5523 nommu_addchr(&ctx.as_string, ch);
5526 else if (next == '(') {
5527 syntax_error(">(process) not supported");
5531 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5533 continue; /* get next char */
5535 redir_fd = redirect_opt_num(&ctx.word);
5536 if (done_word(&ctx)) {
5539 redir_style = REDIRECT_INPUT;
5541 redir_style = REDIRECT_HEREDOC;
5543 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
5544 ch = i_getch(input);
5545 nommu_addchr(&ctx.as_string, ch);
5546 } else if (next == '>') {
5547 redir_style = REDIRECT_IO;
5548 ch = i_getch(input);
5549 nommu_addchr(&ctx.as_string, ch);
5552 else if (next == '(') {
5553 syntax_error("<(process) not supported");
5557 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5559 continue; /* get next char */
5561 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
5562 /* skip "#comment" */
5563 /* note: we do not add it to &ctx.as_string */
5565 * comment inside $() goes to the next \n, even inside quoted string (!):
5566 * cmd "$(cmd2 #comment)" - syntax error
5567 * cmd "`cmd2 #comment`" - ok
5568 * We accept both (comment ends where command subst ends, in both cases).
5573 nommu_addchr(&ctx.as_string, '\n');
5576 ch = i_getch(input);
5580 continue; /* get next char */
5586 if (ctx.is_assignment == MAYBE_ASSIGNMENT
5587 /* check that we are not in word in "a=1 2>word b=1": */
5588 && !ctx.pending_redirect
5590 /* ch is a special char and thus this word
5591 * cannot be an assignment */
5592 ctx.is_assignment = NOT_ASSIGNMENT;
5593 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5596 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5599 case SPECIAL_VAR_SYMBOL:
5600 /* Convert raw ^C to corresponding special variable reference */
5601 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5602 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5605 /* non-comment #: "echo a#b" etc */
5606 o_addchr(&ctx.word, ch);
5607 continue; /* get next char */
5609 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
5610 debug_printf_parse("parse_stream parse error: "
5611 "parse_dollar returned 0 (error)\n");
5614 continue; /* get next char */
5616 ctx.word.has_quoted_part = 1;
5617 if (next == '"' && !ctx.pending_redirect) {
5618 i_getch(input); /* eat second " */
5619 insert_empty_quoted_str_marker:
5620 nommu_addchr(&ctx.as_string, next);
5621 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5622 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5623 continue; /* get next char */
5625 if (ctx.is_assignment == NOT_ASSIGNMENT)
5626 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5627 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
5629 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5630 continue; /* get next char */
5631 #if ENABLE_HUSH_TICK
5633 USE_FOR_NOMMU(unsigned pos;)
5635 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5636 o_addchr(&ctx.word, '`');
5637 USE_FOR_NOMMU(pos = ctx.word.length;)
5638 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
5641 o_addstr(&ctx.as_string, ctx.word.data + pos);
5642 o_addchr(&ctx.as_string, '`');
5644 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5645 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
5646 continue; /* get next char */
5650 #if ENABLE_HUSH_CASE
5653 if (done_word(&ctx)) {
5656 done_pipe(&ctx, PIPE_SEQ);
5657 #if ENABLE_HUSH_CASE
5658 /* Eat multiple semicolons, detect
5659 * whether it means something special */
5661 ch = i_peek_and_eat_bkslash_nl(input);
5664 ch = i_getch(input);
5665 nommu_addchr(&ctx.as_string, ch);
5666 if (ctx.ctx_res_w == RES_CASE_BODY) {
5667 ctx.ctx_dsemicolon = 1;
5668 ctx.ctx_res_w = RES_MATCH;
5674 /* We just finished a cmd. New one may start
5675 * with an assignment */
5676 ctx.is_assignment = MAYBE_ASSIGNMENT;
5677 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5678 continue; /* get next char */
5680 if (done_word(&ctx)) {
5684 ch = i_getch(input);
5685 nommu_addchr(&ctx.as_string, ch);
5686 done_pipe(&ctx, PIPE_AND);
5688 done_pipe(&ctx, PIPE_BG);
5692 if (done_word(&ctx)) {
5695 #if ENABLE_HUSH_CASE
5696 if (ctx.ctx_res_w == RES_MATCH)
5697 break; /* we are in case's "word | word)" */
5699 if (next == '|') { /* || */
5700 ch = i_getch(input);
5701 nommu_addchr(&ctx.as_string, ch);
5702 done_pipe(&ctx, PIPE_OR);
5704 /* we could pick up a file descriptor choice here
5705 * with redirect_opt_num(), but bash doesn't do it.
5706 * "echo foo 2| cat" yields "foo 2". */
5711 #if ENABLE_HUSH_CASE
5712 /* "case... in [(]word)..." - skip '(' */
5713 if (ctx.ctx_res_w == RES_MATCH
5714 && ctx.command->argv == NULL /* not (word|(... */
5715 && ctx.word.length == 0 /* not word(... */
5716 && ctx.word.has_quoted_part == 0 /* not ""(... */
5718 continue; /* get next char */
5723 int n = parse_group(&ctx, input, ch);
5727 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5732 #if ENABLE_HUSH_CASE
5733 if (ctx.ctx_res_w == RES_MATCH)
5738 /* proper use of this character is caught by end_trigger:
5739 * if we see {, we call parse_group(..., end_trigger='}')
5740 * and it will match } earlier (not here). */
5741 G.last_exitcode = 2;
5742 syntax_error_unexpected_ch(ch);
5746 bb_error_msg_and_die("BUG: unexpected %c", ch);
5751 G.last_exitcode = 1;
5754 struct parse_context *pctx;
5755 IF_HAS_KEYWORDS(struct parse_context *p2;)
5757 /* Clean up allocated tree.
5758 * Sample for finding leaks on syntax error recovery path.
5759 * Run it from interactive shell, watch pmap `pidof hush`.
5760 * while if false; then false; fi; do break; fi
5761 * Samples to catch leaks at execution:
5762 * while if (true | { true;}); then echo ok; fi; do break; done
5763 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5767 /* Update pipe/command counts,
5768 * otherwise freeing may miss some */
5769 done_pipe(pctx, PIPE_SEQ);
5770 debug_printf_clean("freeing list %p from ctx %p\n",
5771 pctx->list_head, pctx);
5772 debug_print_tree(pctx->list_head, 0);
5773 free_pipe_list(pctx->list_head);
5774 debug_printf_clean("freed list %p\n", pctx->list_head);
5776 o_free(&pctx->as_string);
5778 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5782 IF_HAS_KEYWORDS(pctx = p2;)
5783 } while (HAS_KEYWORDS && pctx);
5796 /*** Execution routines ***/
5798 /* Expansion can recurse, need forward decls: */
5799 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5800 #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
5801 expand_string_to_string(str)
5803 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
5804 #if ENABLE_HUSH_TICK
5805 static int process_command_subs(o_string *dest, const char *s);
5807 static int expand_vars_to_list(o_string *output, int n, char *arg);
5809 /* expand_strvec_to_strvec() takes a list of strings, expands
5810 * all variable references within and returns a pointer to
5811 * a list of expanded strings, possibly with larger number
5812 * of strings. (Think VAR="a b"; echo $VAR).
5813 * This new list is allocated as a single malloc block.
5814 * NULL-terminated list of char* pointers is at the beginning of it,
5815 * followed by strings themselves.
5816 * Caller can deallocate entire list by single free(list). */
5818 /* A horde of its helpers come first: */
5820 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5822 while (--len >= 0) {
5825 #if ENABLE_HUSH_BRACE_EXPANSION
5826 if (c == '{' || c == '}') {
5827 /* { -> \{, } -> \} */
5829 /* And now we want to add { or } and continue:
5832 * luckily, just falling through achieves this.
5838 /* \z -> \\\z; \<eol> -> \\<eol> */
5843 o_addchr(o, *str++);
5849 /* Store given string, finalizing the word and starting new one whenever
5850 * we encounter IFS char(s). This is used for expanding variable values.
5851 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5852 * Return in output->ended_in_ifs:
5853 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5855 static int expand_on_ifs(o_string *output, int n, const char *str)
5857 int last_is_ifs = 0;
5862 if (!*str) /* EOL - do not finalize word */
5864 word_len = strcspn(str, G.ifs);
5866 /* We have WORD_LEN leading non-IFS chars */
5867 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5868 o_addblock(output, str, word_len);
5870 /* Protect backslashes against globbing up :)
5871 * Example: "v='\*'; echo b$v" prints "b\*"
5872 * (and does not try to glob on "*")
5874 o_addblock_duplicate_backslash(output, str, word_len);
5875 /*/ Why can't we do it easier? */
5876 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5877 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5881 if (!*str) /* EOL - do not finalize word */
5885 /* We know str here points to at least one IFS char */
5887 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
5888 if (!*str) /* EOL - do not finalize word */
5891 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5892 && strchr(G.ifs, *str) /* the second check would fail */
5894 /* This is a non-whitespace $IFS char */
5895 /* Skip it and IFS whitespace chars, start new word */
5897 str += strspn(str, G.ifs_whitespace);
5901 /* Start new word... but not always! */
5902 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5903 if (output->has_quoted_part
5905 * Case "v=' a'; echo $v":
5906 * here nothing precedes the space in $v expansion,
5907 * therefore we should not finish the word
5908 * (IOW: if there *is* word to finalize, only then do it):
5909 * It's okay if this accesses the byte before first argv[]:
5910 * past call to o_save_ptr() cleared it to zero byte
5911 * (grep for -prev-ifs-check-).
5913 || output->data[output->length - 1]
5916 o_addchr(output, '\0');
5917 debug_print_list("expand_on_ifs", output, n);
5918 n = o_save_ptr(output, n);
5922 output->ended_in_ifs = last_is_ifs;
5923 debug_print_list("expand_on_ifs[1]", output, n);
5927 /* Helper to expand $((...)) and heredoc body. These act as if
5928 * they are in double quotes, with the exception that they are not :).
5929 * Just the rules are similar: "expand only $var and `cmd`"
5931 * Returns malloced string.
5932 * As an optimization, we return NULL if expansion is not needed.
5934 static char *encode_then_expand_string(const char *str)
5937 struct in_str input;
5938 o_string dest = NULL_O_STRING;
5943 if (!*cp) return NULL; /* string has no special chars */
5944 if (*cp == '$') break;
5945 if (*cp == '\\') break;
5946 #if ENABLE_HUSH_TICK
5947 if (*cp == '`') break;
5952 /* We need to expand. Example:
5953 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5955 setup_string_in_str(&input, str);
5956 encode_string(NULL, &dest, &input, EOF);
5957 //TODO: error check (encode_string returns 0 on error)?
5958 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5959 exp_str = expand_string_to_string(dest.data,
5960 EXP_FLAG_ESC_GLOB_CHARS,
5963 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5968 static const char *first_special_char_in_vararg(const char *cp)
5971 if (!*cp) return NULL; /* string has no special chars */
5972 if (*cp == '$') return cp;
5973 if (*cp == '\\') return cp;
5974 if (*cp == '\'') return cp;
5975 if (*cp == '"') return cp;
5976 #if ENABLE_HUSH_TICK
5977 if (*cp == '`') return cp;
5979 /* dquoted "${x:+ARG}" should not glob, therefore
5980 * '*' et al require some non-literal processing: */
5981 if (*cp == '*') return cp;
5982 if (*cp == '?') return cp;
5983 if (*cp == '[') return cp;
5988 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5989 * These can contain single- and double-quoted strings,
5990 * and treated as if the ARG string is initially unquoted. IOW:
5991 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5992 * a dquoted string: "${var#"zz"}"), the difference only comes later
5993 * (word splitting and globbing of the ${var...} result).
5995 #if !BASH_PATTERN_SUBST
5996 #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5997 encode_then_expand_vararg(str, handle_squotes)
5999 static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6001 #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
6002 const int do_unbackslash = 0;
6005 struct in_str input;
6006 o_string dest = NULL_O_STRING;
6008 if (!first_special_char_in_vararg(str)) {
6009 /* string has no special chars */
6013 setup_string_in_str(&input, str);
6014 dest.data = xzalloc(1); /* start as "", not as NULL */
6020 ch = i_getch(&input);
6021 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6022 __func__, ch, ch, !!dest.o_expflags);
6024 if (!dest.o_expflags) {
6027 if (handle_squotes && ch == '\'') {
6028 if (!add_till_single_quote_dquoted(&dest, &input))
6029 goto ret; /* error */
6034 syntax_error_unterm_ch('"');
6035 goto ret; /* error */
6038 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6042 ch = i_getch(&input);
6044 //example? error message? syntax_error_unterm_ch('"');
6045 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6048 o_addqchr(&dest, ch);
6052 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6053 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6058 #if ENABLE_HUSH_TICK
6060 //unsigned pos = dest->length;
6061 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6062 o_addchr(&dest, 0x80 | '`');
6063 if (!add_till_backquote(&dest, &input,
6064 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6067 goto ret; /* error */
6069 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6070 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6074 o_addQchr(&dest, ch);
6077 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6078 exp_str = expand_string_to_string(dest.data,
6079 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6083 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
6088 /* Expanding ARG in ${var+ARG}, ${var-ARG}
6090 static int encode_then_append_var_plusminus(o_string *output, int n,
6091 char *str, int dquoted)
6093 struct in_str input;
6094 o_string dest = NULL_O_STRING;
6096 if (!first_special_char_in_vararg(str)
6097 && '\0' == str[strcspn(str, G.ifs)]
6099 /* string has no special chars
6100 * && string has no $IFS chars
6102 return expand_vars_to_list(output, n, str);
6105 setup_string_in_str(&input, str);
6110 ch = i_getch(&input);
6111 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6112 __func__, ch, ch, dest.o_expflags);
6114 if (!dest.o_expflags) {
6117 if (!dquoted && strchr(G.ifs, ch)) {
6118 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6119 * do not assume we are at the start of the word (PREFIX above).
6122 n = expand_vars_to_list(output, n, dest.data);
6123 o_free_and_set_NULL(&dest);
6124 o_addchr(output, '\0');
6125 n = o_save_ptr(output, n); /* create next word */
6127 if (output->length != o_get_last_ptr(output, n)
6128 || output->has_quoted_part
6131 * f() { for i; do echo "|$i|"; done; }; x=x
6132 * f a${x:+ }b # 1st condition
6135 * f ""${x:+ }b # 2nd condition
6139 o_addchr(output, '\0');
6140 n = o_save_ptr(output, n); /* create next word */
6144 if (!dquoted && ch == '\'') {
6145 if (!add_till_single_quote_dquoted(&dest, &input))
6146 goto ret; /* error */
6147 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6148 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6153 syntax_error_unterm_ch('"');
6154 goto ret; /* error */
6157 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6158 if (dest.o_expflags) {
6159 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6160 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6165 ch = i_getch(&input);
6167 //example? error message? syntax_error_unterm_ch('"');
6168 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6171 o_addqchr(&dest, ch);
6175 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6176 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6181 #if ENABLE_HUSH_TICK
6183 //unsigned pos = dest->length;
6184 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6185 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6186 if (!add_till_backquote(&dest, &input,
6187 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6190 goto ret; /* error */
6192 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6193 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6198 /* Always glob-protect if in dquotes:
6199 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6200 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6202 o_addqchr(&dest, ch);
6204 /* Glob-protect only if char is quoted:
6205 * x=x; echo ${x:+/bin/c*} - prints many filenames
6206 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6208 o_addQchr(&dest, ch);
6213 n = expand_vars_to_list(output, n, dest.data);
6220 #if ENABLE_FEATURE_SH_MATH
6221 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
6223 arith_state_t math_state;
6227 math_state.lookupvar = get_local_var_value;
6228 math_state.setvar = set_local_var_from_halves;
6229 //math_state.endofname = endofname;
6230 exp_str = encode_then_expand_string(arg);
6231 res = arith(&math_state, exp_str ? exp_str : arg);
6234 *errmsg_p = math_state.errmsg;
6235 if (math_state.errmsg)
6236 msg_and_die_if_script(math_state.errmsg);
6241 #if BASH_PATTERN_SUBST
6242 /* ${var/[/]pattern[/repl]} helpers */
6243 static char *strstr_pattern(char *val, const char *pattern, int *size)
6246 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6247 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6254 /* Optimization: if "*pat" did not match the start of "string",
6255 * we know that "tring", "ring" etc will not match too:
6257 if (pattern[0] == '*')
6262 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6264 char *result = NULL;
6265 unsigned res_len = 0;
6266 unsigned repl_len = strlen(repl);
6268 /* Null pattern never matches, including if "var" is empty */
6270 return result; /* NULL, no replaces happened */
6274 char *s = strstr_pattern(val, pattern, &size);
6278 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
6279 strcpy(mempcpy(result + res_len, val, s - val), repl);
6280 res_len += (s - val) + repl_len;
6281 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6287 if (*val && result) {
6288 result = xrealloc(result, res_len + strlen(val) + 1);
6289 strcpy(result + res_len, val);
6290 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6292 debug_printf_varexp("result:'%s'\n", result);
6295 #endif /* BASH_PATTERN_SUBST */
6297 static int append_str_maybe_ifs_split(o_string *output, int n,
6298 int first_ch, const char *val)
6300 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6301 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6302 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6304 n = expand_on_ifs(output, n, val);
6305 } else { /* quoted "$VAR" */
6306 output->has_quoted_part = 1;
6307 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6308 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6310 o_addQstr(output, val);
6315 /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6317 static NOINLINE int expand_one_var(o_string *output, int n,
6318 int first_ch, char *arg, char **pp)
6325 char exp_save = exp_save; /* for compiler */
6326 char *exp_saveptr; /* points to expansion operator */
6327 char *exp_word = exp_word; /* for compiler */
6333 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
6335 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
6337 arg[0] = (arg0 & 0x7f);
6340 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
6341 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6342 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6343 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
6345 /* It must be length operator: ${#var} */
6349 /* Maybe handle parameter expansion */
6350 if (exp_saveptr /* if 2nd char is one of expansion operators */
6351 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
6353 /* ${?:0}, ${#[:]%0} etc */
6354 exp_saveptr = var + 1;
6356 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6357 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6359 exp_op = exp_save = *exp_saveptr;
6361 exp_word = exp_saveptr + 1;
6362 if (exp_op == ':') {
6363 exp_op = *exp_word++;
6364 //TODO: try ${var:} and ${var:bogus} in non-bash config
6366 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
6368 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6373 *exp_saveptr = '\0';
6374 } /* else: it's not an expansion op, but bare ${var} */
6377 /* Look up the variable in question */
6378 if (isdigit(var[0])) {
6379 /* parse_dollar should have vetted var for us */
6380 int nn = xatoi_positive(var);
6381 if (nn < G.global_argc)
6382 val = G.global_argv[nn];
6383 /* else val remains NULL: $N with too big N */
6387 val = utoa(G.root_pid);
6389 case '!': /* bg pid */
6390 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6392 case '?': /* exitcode */
6393 val = utoa(G.last_exitcode);
6395 case '#': /* argc */
6396 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6399 val = get_local_var_value(var);
6403 /* Handle any expansions */
6404 if (exp_op == 'L') {
6405 reinit_unicode_for_hush();
6406 debug_printf_expand("expand: length(%s)=", val);
6407 val = utoa(val ? unicode_strlen(val) : 0);
6408 debug_printf_expand("%s\n", val);
6409 } else if (exp_op) {
6410 if (exp_op == '%' || exp_op == '#') {
6411 /* Standard-mandated substring removal ops:
6412 * ${parameter%word} - remove smallest suffix pattern
6413 * ${parameter%%word} - remove largest suffix pattern
6414 * ${parameter#word} - remove smallest prefix pattern
6415 * ${parameter##word} - remove largest prefix pattern
6417 * Word is expanded to produce a glob pattern.
6418 * Then var's value is matched to it and matching part removed.
6420 //FIXME: ${x#...${...}...}
6421 //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6422 //inner ${...} may have side effects!
6423 if (val && val[0]) {
6427 unsigned scan_flags = pick_scan(exp_op, *exp_word);
6428 if (exp_op == *exp_word) /* ## or %% */
6430 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6431 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6433 exp_word = exp_exp_word;
6434 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6436 * HACK ALERT. We depend here on the fact that
6437 * G.global_argv and results of utoa and get_local_var_value
6438 * are actually in writable memory:
6439 * scan_and_match momentarily stores NULs there.
6442 loc = scan_and_match(t, exp_word, scan_flags);
6443 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
6445 if (loc) { /* match was found */
6446 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
6447 val = loc; /* take right part */
6449 val = to_be_freed = xstrndup(val, loc - val); /* left */
6453 #if BASH_PATTERN_SUBST
6454 else if (exp_op == '/' || exp_op == '\\') {
6455 /* It's ${var/[/]pattern[/repl]} thing.
6456 * Note that in encoded form it has TWO parts:
6457 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6458 * and if // is used, it is encoded as \:
6459 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6461 if (val && val[0]) {
6462 /* pattern uses non-standard expansion.
6463 * repl should be unbackslashed and globbed
6464 * by the usual expansion rules:
6466 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6467 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6468 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6469 * v='a bz'; echo ${v/a*z/\z} #prints "z"
6470 * (note that a*z _pattern_ is never globbed!)
6472 char *pattern, *repl, *t;
6473 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6475 pattern = xstrdup(exp_word);
6476 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6477 *p++ = SPECIAL_VAR_SYMBOL;
6479 p = strchr(p, SPECIAL_VAR_SYMBOL);
6481 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
6482 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6483 /* HACK ALERT. We depend here on the fact that
6484 * G.global_argv and results of utoa and get_local_var_value
6485 * are actually in writable memory:
6486 * replace_pattern momentarily stores NULs there. */
6488 to_be_freed = replace_pattern(t,
6490 (repl ? repl : exp_word),
6492 if (to_be_freed) /* at least one replace happened */
6497 /* Empty variable always gives nothing */
6498 // "v=''; echo ${v/*/w}" prints "", not "w"
6499 /* Just skip "replace" part */
6500 *p++ = SPECIAL_VAR_SYMBOL;
6501 p = strchr(p, SPECIAL_VAR_SYMBOL);
6505 #endif /* BASH_PATTERN_SUBST */
6506 else if (exp_op == ':') {
6507 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
6508 /* It's ${var:N[:M]} bashism.
6509 * Note that in encoded form it has TWO parts:
6510 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6515 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6518 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6519 *p++ = SPECIAL_VAR_SYMBOL;
6521 p = strchr(p, SPECIAL_VAR_SYMBOL);
6523 len = expand_and_evaluate_arith(exp_word, &errmsg);
6526 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
6528 /* negative beg counts from the end */
6529 beg = (arith_t)strlen(val) + beg;
6530 if (beg < 0) /* ${v: -999999} is "" */
6533 debug_printf_varexp("from val:'%s'\n", val);
6535 /* in bash, len=-n means strlen()-n */
6536 len = (arith_t)strlen(val) - beg + len;
6537 if (len < 0) /* bash compat */
6538 msg_and_die_if_script("%s: substring expression < 0", var);
6540 if (len <= 0 || !val || beg >= strlen(val)) {
6544 /* Paranoia. What if user entered 9999999999999
6545 * which fits in arith_t but not int? */
6548 val = to_be_freed = xstrndup(val + beg, len);
6550 debug_printf_varexp("val:'%s'\n", val);
6551 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
6552 msg_and_die_if_script("malformed ${%s:...}", var);
6555 } else { /* one of "-=+?" */
6556 /* Standard-mandated substitution ops:
6557 * ${var?word} - indicate error if unset
6558 * If var is unset, word (or a message indicating it is unset
6559 * if word is null) is written to standard error
6560 * and the shell exits with a non-zero exit status.
6561 * Otherwise, the value of var is substituted.
6562 * ${var-word} - use default value
6563 * If var is unset, word is substituted.
6564 * ${var=word} - assign and use default value
6565 * If var is unset, word is assigned to var.
6566 * In all cases, final value of var is substituted.
6567 * ${var+word} - use alternative value
6568 * If var is unset, null is substituted.
6569 * Otherwise, word is substituted.
6571 * Word is subjected to tilde expansion, parameter expansion,
6572 * command substitution, and arithmetic expansion.
6573 * If word is not needed, it is not expanded.
6575 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6576 * but also treat null var as if it is unset.
6578 * Word-splitting and single quote behavior:
6580 * $ f() { for i; do echo "|$i|"; done; };
6582 * $ x=; f ${x:?'x y' z}
6583 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6584 * $ x=; f "${x:?'x y' z}"
6585 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6587 * $ x=; f ${x:='x y' z}
6591 * $ x=; f "${x:='x y' z}"
6594 * $ x=x; f ${x:+'x y' z}
6597 * $ x=x; f "${x:+'x y' z}"
6600 * $ x=; f ${x:-'x y' z}
6603 * $ x=; f "${x:-'x y' z}"
6606 int use_word = (!val || ((exp_save == ':') && !val[0]));
6608 use_word = !use_word;
6609 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6610 (exp_save == ':') ? "true" : "false", use_word);
6612 if (exp_op == '+' || exp_op == '-') {
6613 /* ${var+word} - use alternative value */
6614 /* ${var-word} - use default value */
6615 n = encode_then_append_var_plusminus(output, n, exp_word,
6616 /*dquoted:*/ (arg0 & 0x80)
6620 /* ${var?word} - indicate error if unset */
6621 /* ${var=word} - assign and use default value */
6622 to_be_freed = encode_then_expand_vararg(exp_word,
6623 /*handle_squotes:*/ !(arg0 & 0x80),
6627 exp_word = to_be_freed;
6628 if (exp_op == '?') {
6629 /* mimic bash message */
6630 msg_and_die_if_script("%s: %s",
6634 : "parameter null or not set"
6635 /* ash has more specific messages, a-la: */
6636 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6638 //TODO: how interactive bash aborts expansion mid-command?
6639 //It aborts the entire line, returns to prompt:
6640 // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6643 // ("echo YO" is not executed, neither the f function call)
6647 if (exp_op == '=') {
6648 /* ${var=[word]} or ${var:=[word]} */
6649 if (isdigit(var[0]) || var[0] == '#') {
6650 /* mimic bash message */
6651 msg_and_die_if_script("$%s: cannot assign in this way", var);
6654 char *new_var = xasprintf("%s=%s", var, val);
6655 set_local_var(new_var, /*flag:*/ 0);
6660 } /* one of "-=+?" */
6662 *exp_saveptr = exp_save;
6668 n = append_str_maybe_ifs_split(output, n, first_ch, val);
6674 /* Expand all variable references in given string, adding words to list[]
6675 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6676 * to be filled). This routine is extremely tricky: has to deal with
6677 * variables/parameters with whitespace, $* and $@, and constructs like
6678 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
6679 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
6681 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
6682 * expansion of right-hand side of assignment == 1-element expand.
6684 char cant_be_null = 0; /* only bit 0x80 matters */
6687 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6688 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
6689 debug_print_list("expand_vars_to_list[0]", output, n);
6691 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6693 #if ENABLE_FEATURE_SH_MATH
6694 char arith_buf[sizeof(arith_t)*3 + 2];
6697 if (output->ended_in_ifs) {
6698 o_addchr(output, '\0');
6699 n = o_save_ptr(output, n);
6700 output->ended_in_ifs = 0;
6703 o_addblock(output, arg, p - arg);
6704 debug_print_list("expand_vars_to_list[1]", output, n);
6706 p = strchr(p, SPECIAL_VAR_SYMBOL);
6708 /* Fetch special var name (if it is indeed one of them)
6709 * and quote bit, force the bit on if singleword expansion -
6710 * important for not getting v=$@ expand to many words. */
6711 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6713 /* Is this variable quoted and thus expansion can't be null?
6714 * "$@" is special. Even if quoted, it can still
6715 * expand to nothing (not even an empty string),
6716 * thus it is excluded. */
6717 if ((first_ch & 0x7f) != '@')
6718 cant_be_null |= first_ch;
6720 switch (first_ch & 0x7f) {
6721 /* Highest bit in first_ch indicates that var is double-quoted */
6725 if (!G.global_argv[1])
6728 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6729 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6730 while (G.global_argv[i]) {
6731 n = expand_on_ifs(output, n, G.global_argv[i]);
6732 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6733 if (G.global_argv[i++][0] && G.global_argv[i]) {
6734 /* this argv[] is not empty and not last:
6735 * put terminating NUL, start new word */
6736 o_addchr(output, '\0');
6737 debug_print_list("expand_vars_to_list[2]", output, n);
6738 n = o_save_ptr(output, n);
6739 debug_print_list("expand_vars_to_list[3]", output, n);
6743 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6744 * and in this case should treat it like '$*' - see 'else...' below */
6745 if (first_ch == (char)('@'|0x80) /* quoted $@ */
6746 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6749 o_addQstr(output, G.global_argv[i]);
6750 if (++i >= G.global_argc)
6752 o_addchr(output, '\0');
6753 debug_print_list("expand_vars_to_list[4]", output, n);
6754 n = o_save_ptr(output, n);
6756 } else { /* quoted $* (or v="$@" case): add as one word */
6758 o_addQstr(output, G.global_argv[i]);
6759 if (!G.global_argv[++i])
6762 o_addchr(output, G.ifs[0]);
6764 output->has_quoted_part = 1;
6768 case SPECIAL_VAR_SYMBOL: {
6769 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6770 /* "Empty variable", used to make "" etc to not disappear */
6771 output->has_quoted_part = 1;
6772 cant_be_null = 0x80;
6776 case SPECIAL_VAR_QUOTED_SVS:
6777 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6778 /* "^C variable", represents literal ^C char (possible in scripts) */
6779 o_addchr(output, SPECIAL_VAR_SYMBOL);
6782 #if ENABLE_HUSH_TICK
6784 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6785 o_string subst_result = NULL_O_STRING;
6787 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6789 /* Can't just stuff it into output o_string,
6790 * expanded result may need to be globbed
6792 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6793 G.last_exitcode = process_command_subs(&subst_result, arg);
6794 G.expand_exitcode = G.last_exitcode;
6795 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6796 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
6797 o_free(&subst_result);
6801 #if ENABLE_FEATURE_SH_MATH
6803 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
6806 arg++; /* skip '+' */
6807 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6808 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6809 res = expand_and_evaluate_arith(arg, NULL);
6810 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6811 sprintf(arith_buf, ARITH_FMT, res);
6812 o_addstr(output, arith_buf);
6817 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
6818 n = expand_one_var(output, n, first_ch, arg, &p);
6820 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6822 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6823 * Do the check to avoid writing to a const string. */
6824 if (*p != SPECIAL_VAR_SYMBOL)
6825 *p = SPECIAL_VAR_SYMBOL;
6827 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6830 /* handle trailing string */
6831 if (output->ended_in_ifs) {
6832 o_addchr(output, '\0');
6833 n = o_save_ptr(output, n);
6835 debug_print_list("expand_vars_to_list[a]", output, n);
6836 /* this part is literal, and it was already pre-quoted
6837 * if needed (much earlier), do not use o_addQstr here!
6839 o_addstr(output, arg);
6840 debug_print_list("expand_vars_to_list[b]", output, n);
6842 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6843 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6844 && !output->has_quoted_part
6847 /* allow to reuse list[n] later without re-growth */
6848 output->has_empty_slot = 1;
6854 static char **expand_variables(char **argv, unsigned expflags)
6858 o_string output = NULL_O_STRING;
6860 output.o_expflags = expflags;
6864 /* go to next list[n] */
6865 output.ended_in_ifs = 0;
6866 n = o_save_ptr(&output, n);
6871 /* expand argv[i] */
6872 n = expand_vars_to_list(&output, n, *argv++);
6873 /* if (!output->has_empty_slot) -- need this?? */
6874 o_addchr(&output, '\0');
6876 debug_print_list("expand_variables", &output, n);
6878 /* output.data (malloced in one block) gets returned in "list" */
6879 list = o_finalize_list(&output, n);
6880 debug_print_strings("expand_variables[1]", list);
6884 static char **expand_strvec_to_strvec(char **argv)
6886 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6889 #if defined(CMD_SINGLEWORD_NOGLOB)
6890 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6892 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6896 /* Used for expansion of right hand of assignments,
6897 * $((...)), heredocs, variable expansion parts.
6899 * NB: should NOT do globbing!
6900 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6902 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
6904 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6905 const int do_unbackslash = 1;
6906 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
6908 char *argv[2], **list;
6910 debug_printf_expand("string_to_string<='%s'\n", str);
6911 /* This is generally an optimization, but it also
6912 * handles "", which otherwise trips over !list[0] check below.
6913 * (is this ever happens that we actually get str="" here?)
6915 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6916 //TODO: Can use on strings with \ too, just unbackslash() them?
6917 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6918 return xstrdup(str);
6921 argv[0] = (char*)str;
6923 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
6925 /* Example where it happens:
6926 * x=; echo ${x:-"$@"}
6928 ((char*)list)[0] = '\0';
6932 bb_error_msg_and_die("BUG in varexp2");
6933 /* actually, just move string 2*sizeof(char*) bytes back */
6934 overlapping_strcpy((char*)list, list[0]);
6936 unbackslash((char*)list);
6938 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6943 static char* expand_strvec_to_string(char **argv)
6947 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6948 /* Convert all NULs to spaces */
6953 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6954 bb_error_msg_and_die("BUG in varexp3");
6955 /* bash uses ' ' regardless of $IFS contents */
6960 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6961 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6966 static char **expand_assignments(char **argv, int count)
6971 G.expanded_assignments = p = NULL;
6972 /* Expand assignments into one string each */
6973 for (i = 0; i < count; i++) {
6974 p = add_string_to_strings(p,
6975 expand_string_to_string(argv[i],
6976 EXP_FLAG_ESC_GLOB_CHARS,
6980 G.expanded_assignments = p;
6982 G.expanded_assignments = NULL;
6987 static void switch_off_special_sigs(unsigned mask)
6990 while ((mask >>= 1) != 0) {
6994 #if ENABLE_HUSH_TRAP
6996 if (G_traps[sig] && !G_traps[sig][0])
6997 /* trap is '', has to remain SIG_IGN */
7000 G_traps[sig] = NULL;
7003 /* We are here only if no trap or trap was not '' */
7004 install_sighandler(sig, SIG_DFL);
7010 void re_execute_shell(char ***to_free, const char *s,
7011 char *g_argv0, char **g_argv,
7012 char **builtin_argv) NORETURN;
7014 static void reset_traps_to_defaults(void)
7016 /* This function is always called in a child shell
7017 * after fork (not vfork, NOMMU doesn't use this function).
7019 IF_HUSH_TRAP(unsigned sig;)
7022 /* Child shells are not interactive.
7023 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7024 * Testcase: (while :; do :; done) + ^Z should background.
7025 * Same goes for SIGTERM, SIGHUP, SIGINT.
7027 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
7028 if (!G_traps && !mask)
7029 return; /* already no traps and no special sigs */
7031 /* Switch off special sigs */
7032 switch_off_special_sigs(mask);
7033 # if ENABLE_HUSH_JOB
7034 G_fatal_sig_mask = 0;
7036 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
7037 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7038 * remain set in G.special_sig_mask */
7040 # if ENABLE_HUSH_TRAP
7044 /* Reset all sigs to default except ones with empty traps */
7045 for (sig = 0; sig < NSIG; sig++) {
7047 continue; /* no trap: nothing to do */
7048 if (!G_traps[sig][0])
7049 continue; /* empty trap: has to remain SIG_IGN */
7050 /* sig has non-empty trap, reset it: */
7052 G_traps[sig] = NULL;
7053 /* There is no signal for trap 0 (EXIT) */
7056 install_sighandler(sig, pick_sighandler(sig));
7063 static void re_execute_shell(char ***to_free, const char *s,
7064 char *g_argv0, char **g_argv,
7065 char **builtin_argv) NORETURN;
7066 static void re_execute_shell(char ***to_free, const char *s,
7067 char *g_argv0, char **g_argv,
7068 char **builtin_argv)
7070 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7071 /* delims + 2 * (number of bytes in printed hex numbers) */
7072 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7073 char *heredoc_argv[4];
7074 struct variable *cur;
7075 # if ENABLE_HUSH_FUNCTIONS
7076 struct function *funcp;
7080 unsigned long long empty_trap_mask;
7082 if (!g_argv0) { /* heredoc */
7083 argv = heredoc_argv;
7084 argv[0] = (char *) G.argv0_for_re_execing;
7085 argv[1] = (char *) "-<";
7086 argv[2] = (char *) s;
7088 pp = &argv[3]; /* used as pointer to empty environment */
7094 if (pp) while (*pp++)
7097 empty_trap_mask = 0;
7100 for (sig = 1; sig < NSIG; sig++) {
7101 if (G_traps[sig] && !G_traps[sig][0])
7102 empty_trap_mask |= 1LL << sig;
7106 sprintf(param_buf, NOMMU_HACK_FMT
7107 , (unsigned) G.root_pid
7108 , (unsigned) G.root_ppid
7109 , (unsigned) G.last_bg_pid
7110 , (unsigned) G.last_exitcode
7113 IF_HUSH_LOOPS(, G.depth_of_loop)
7115 # undef NOMMU_HACK_FMT
7116 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7117 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7120 for (cur = G.top_var; cur; cur = cur->next) {
7121 if (!cur->flg_export || cur->flg_read_only)
7124 # if ENABLE_HUSH_FUNCTIONS
7125 for (funcp = G.top_func; funcp; funcp = funcp->next)
7131 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7132 *pp++ = (char *) G.argv0_for_re_execing;
7134 for (cur = G.top_var; cur; cur = cur->next) {
7135 if (strcmp(cur->varstr, hush_version_str) == 0)
7137 if (cur->flg_read_only) {
7138 *pp++ = (char *) "-R";
7139 *pp++ = cur->varstr;
7140 } else if (!cur->flg_export) {
7141 *pp++ = (char *) "-V";
7142 *pp++ = cur->varstr;
7145 # if ENABLE_HUSH_FUNCTIONS
7146 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7147 *pp++ = (char *) "-F";
7148 *pp++ = funcp->name;
7149 *pp++ = funcp->body_as_string;
7152 /* We can pass activated traps here. Say, -Tnn:trap_string
7154 * However, POSIX says that subshells reset signals with traps
7156 * I tested bash-3.2 and it not only does that with true subshells
7157 * of the form ( list ), but with any forked children shells.
7158 * I set trap "echo W" WINCH; and then tried:
7160 * { echo 1; sleep 20; echo 2; } &
7161 * while true; do echo 1; sleep 20; echo 2; break; done &
7162 * true | { echo 1; sleep 20; echo 2; } | cat
7164 * In all these cases sending SIGWINCH to the child shell
7165 * did not run the trap. If I add trap "echo V" WINCH;
7166 * _inside_ group (just before echo 1), it works.
7168 * I conclude it means we don't need to pass active traps here.
7170 *pp++ = (char *) "-c";
7173 while (*++builtin_argv)
7174 *pp++ = *builtin_argv;
7175 *pp++ = (char *) "";
7180 /* *pp = NULL; - is already there */
7184 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
7185 /* Don't propagate SIG_IGN to the child */
7186 if (SPECIAL_JOBSTOP_SIGS != 0)
7187 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7188 execve(bb_busybox_exec_path, argv, pp);
7189 /* Fallback. Useful for init=/bin/hush usage etc */
7190 if (argv[0][0] == '/')
7191 execve(argv[0], argv, pp);
7192 xfunc_error_retval = 127;
7193 bb_error_msg_and_die("can't re-execute the shell");
7195 #endif /* !BB_MMU */
7198 static int run_and_free_list(struct pipe *pi);
7200 /* Executing from string: eval, sh -c '...'
7201 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7202 * end_trigger controls how often we stop parsing
7203 * NUL: parse all, execute, return
7204 * ';': parse till ';' or newline, execute, repeat till EOF
7206 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7208 /* Why we need empty flag?
7209 * An obscure corner case "false; ``; echo $?":
7210 * empty command in `` should still set $? to 0.
7211 * But we can't just set $? to 0 at the start,
7212 * this breaks "false; echo `echo $?`" case.
7216 struct pipe *pipe_list;
7218 #if ENABLE_HUSH_INTERACTIVE
7219 if (end_trigger == ';') {
7220 G.promptmode = 0; /* PS1 */
7221 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7224 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
7225 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7226 /* If we are in "big" script
7227 * (not in `cmd` or something similar)...
7229 if (pipe_list == ERR_PTR && end_trigger == ';') {
7230 /* Discard cached input (rest of line) */
7231 int ch = inp->last_char;
7232 while (ch != EOF && ch != '\n') {
7233 //bb_error_msg("Discarded:'%c'", ch);
7238 /* This stream isn't empty */
7242 if (!pipe_list && empty)
7243 G.last_exitcode = 0;
7246 debug_print_tree(pipe_list, 0);
7247 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7248 run_and_free_list(pipe_list);
7250 if (G_flag_return_in_progress == 1)
7255 static void parse_and_run_string(const char *s)
7257 struct in_str input;
7258 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7260 setup_string_in_str(&input, s);
7261 parse_and_run_stream(&input, '\0');
7262 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
7265 static void parse_and_run_file(HFILE *fp)
7267 struct in_str input;
7268 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7270 IF_HUSH_LINENO_VAR(G.lineno = 1;)
7271 setup_file_in_str(&input, fp);
7272 parse_and_run_stream(&input, ';');
7273 IF_HUSH_LINENO_VAR(G.lineno = sv;)
7276 #if ENABLE_HUSH_TICK
7277 static int generate_stream_from_string(const char *s, pid_t *pid_p)
7282 char **to_free = NULL;
7286 pid = BB_MMU ? xfork() : xvfork();
7287 if (pid == 0) { /* child */
7288 disable_restore_tty_pgrp_on_exit();
7289 /* Process substitution is not considered to be usual
7290 * 'command execution'.
7291 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7298 close(channel[0]); /* NB: close _first_, then move fd! */
7299 xmove_fd(channel[1], 1);
7300 # if ENABLE_HUSH_TRAP
7301 /* Awful hack for `trap` or $(trap).
7303 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7304 * contains an example where "trap" is executed in a subshell:
7306 * save_traps=$(trap)
7308 * eval "$save_traps"
7310 * Standard does not say that "trap" in subshell shall print
7311 * parent shell's traps. It only says that its output
7312 * must have suitable form, but then, in the above example
7313 * (which is not supposed to be normative), it implies that.
7315 * bash (and probably other shell) does implement it
7316 * (traps are reset to defaults, but "trap" still shows them),
7317 * but as a result, "trap" logic is hopelessly messed up:
7320 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7321 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7322 * # true | trap <--- trap is in subshell - no output (ditto)
7323 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7324 * trap -- 'echo Ho' SIGWINCH
7325 * # echo `(trap)` <--- in subshell in subshell - output
7326 * trap -- 'echo Ho' SIGWINCH
7327 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7328 * trap -- 'echo Ho' SIGWINCH
7330 * The rules when to forget and when to not forget traps
7331 * get really complex and nonsensical.
7333 * Our solution: ONLY bare $(trap) or `trap` is special.
7335 s = skip_whitespace(s);
7336 if (is_prefixed_with(s, "trap")
7337 && skip_whitespace(s + 4)[0] == '\0'
7339 static const char *const argv[] = { NULL, NULL };
7340 builtin_trap((char**)argv);
7341 fflush_all(); /* important */
7346 /* Prevent it from trying to handle ctrl-z etc */
7347 IF_HUSH_JOB(G.run_list_level = 1;)
7348 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7349 reset_traps_to_defaults();
7350 IF_HUSH_MODE_X(G.x_mode_depth++;)
7351 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
7352 parse_and_run_string(s);
7353 _exit(G.last_exitcode);
7355 /* We re-execute after vfork on NOMMU. This makes this script safe:
7356 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7357 * huge=`cat BIG` # was blocking here forever
7360 re_execute_shell(&to_free,
7370 # if ENABLE_HUSH_FAST
7372 //bb_error_msg("[%d] fork in generate_stream_from_string:"
7373 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7374 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7376 enable_restore_tty_pgrp_on_exit();
7384 /* Return code is exit status of the process that is run. */
7385 static int process_command_subs(o_string *dest, const char *s)
7389 int status, ch, eol_cnt;
7391 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
7393 /* Now send results of command back into original context */
7395 while ((ch = getc(fp)) != EOF) {
7403 o_addchr(dest, '\n');
7406 o_addQchr(dest, ch);
7409 debug_printf("done reading from `cmd` pipe, closing it\n");
7411 /* We need to extract exitcode. Test case
7412 * "true; echo `sleep 1; false` $?"
7414 safe_waitpid(pid, &status, 0);
7415 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7416 return WEXITSTATUS(status);
7418 #endif /* ENABLE_HUSH_TICK */
7421 static void setup_heredoc(struct redir_struct *redir)
7423 struct fd_pair pair;
7426 /* the _body_ of heredoc (misleading field name) */
7427 const char *heredoc = redir->rd_filename;
7434 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
7435 expanded = encode_then_expand_string(heredoc);
7439 len = strlen(heredoc);
7441 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7443 xmove_fd(pair.rd, redir->rd_fd);
7445 /* Try writing without forking. Newer kernels have
7446 * dynamically growing pipes. Must use non-blocking write! */
7449 written = write(pair.wr, heredoc, len);
7460 ndelay_off(pair.wr);
7462 /* Okay, pipe buffer was not big enough */
7463 /* Note: we must not create a stray child (bastard? :)
7464 * for the unsuspecting parent process. Child creates a grandchild
7465 * and exits before parent execs the process which consumes heredoc
7466 * (that exec happens after we return from this function) */
7473 disable_restore_tty_pgrp_on_exit();
7474 pid = BB_MMU ? xfork() : xvfork();
7478 close(redir->rd_fd); /* read side of the pipe */
7480 full_write(pair.wr, heredoc, len); /* may loop or block */
7483 /* Delegate blocking writes to another process */
7484 xmove_fd(pair.wr, STDOUT_FILENO);
7485 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7489 #if ENABLE_HUSH_FAST
7491 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7493 enable_restore_tty_pgrp_on_exit();
7499 wait(NULL); /* wait till child has died */
7505 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7506 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7509 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7511 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7512 sq[i].orig_fd = orig;
7513 sq[i].moved_to = moved;
7514 sq[i+1].orig_fd = -1; /* end marker */
7518 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7524 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7525 /* If we collide with an already moved fd... */
7526 if (fd == sq[i].moved_to) {
7527 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
7528 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7529 if (sq[i].moved_to < 0) /* what? */
7533 if (fd == sq[i].orig_fd) {
7534 /* Example: echo Hello >/dev/null 1>&2 */
7535 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7540 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
7541 moved_to = dup_CLOEXEC(fd, avoid_fd);
7542 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7543 if (moved_to < 0 && errno != EBADF)
7545 return append_squirrel(sq, i, fd, moved_to);
7548 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7553 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7554 /* If we collide with an already moved fd... */
7555 if (fd == sq[i].orig_fd) {
7557 * "echo 3>FILE 3>&- 3>FILE"
7558 * "echo 3>&- 3>FILE"
7559 * No need for last redirect to insert
7560 * another "need to close 3" indicator.
7562 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7567 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7568 return append_squirrel(sq, i, fd, -1);
7571 /* fd: redirect wants this fd to be used (e.g. 3>file).
7572 * Move all conflicting internally used fds,
7573 * and remember them so that we can restore them later.
7575 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
7577 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7580 #if ENABLE_HUSH_INTERACTIVE
7581 if (fd == G.interactive_fd) {
7582 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
7583 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
7584 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7585 return 1; /* "we closed fd" */
7588 /* Are we called from setup_redirects(squirrel==NULL)
7589 * in redirect in a [v]forked child?
7592 /* No need to move script fds.
7593 * For NOMMU case, it's actively wrong: we'd change ->fd
7594 * fields in memory for the parent, but parent's fds
7595 * aren't be moved, it would use wrong fd!
7596 * Reproducer: "cmd 3>FILE" in script.
7597 * If we would call move_HFILEs_on_redirect(), child would:
7598 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7600 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7602 //bb_error_msg("sqp == NULL: [v]forked child");
7606 /* If this one of script's fds? */
7607 if (move_HFILEs_on_redirect(fd, avoid_fd))
7608 return 1; /* yes. "we closed fd" (actually moved it) */
7610 /* Are we called for "exec 3>FILE"? Came through
7611 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7612 * This case used to fail for this script:
7615 * ...100000 more lines...
7618 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7619 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7621 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7623 * write(1, "Ok\n", 3) = 3
7625 * write(1, "Ok\n", 3) = 3
7626 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7627 * ^^^^^^^^ oops, wrong fd!!!
7628 * With this case separate from sqp == NULL and *after* move_HFILEs,
7631 if (sqp == ERR_PTR) {
7632 /* Don't preserve redirected fds: exec is _meant_ to change these */
7633 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
7637 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7638 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7639 return 0; /* "we did not close fd" */
7642 static void restore_redirects(struct squirrel *sq)
7646 for (i = 0; sq[i].orig_fd >= 0; i++) {
7647 if (sq[i].moved_to >= 0) {
7648 /* We simply die on error */
7649 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7650 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7652 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7653 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7654 close(sq[i].orig_fd);
7660 /* If moved, G.interactive_fd stays on new fd, not restoring it */
7663 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
7664 static void close_saved_fds_and_FILE_fds(void)
7666 if (G_interactive_fd)
7667 close(G_interactive_fd);
7668 close_all_HFILE_list();
7672 static int internally_opened_fd(int fd, struct squirrel *sq)
7676 #if ENABLE_HUSH_INTERACTIVE
7677 if (fd == G.interactive_fd)
7680 /* If this one of script's fds? */
7681 if (fd_in_HFILEs(fd))
7684 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7685 if (fd == sq[i].moved_to)
7691 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
7692 * and stderr if they are redirected. */
7693 static int setup_redirects(struct command *prog, struct squirrel **sqp)
7695 struct redir_struct *redir;
7697 for (redir = prog->redirects; redir; redir = redir->next) {
7701 if (redir->rd_type == REDIRECT_HEREDOC2) {
7702 /* "rd_fd<<HERE" case */
7703 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
7704 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7706 debug_printf_redir("set heredoc '%s'\n",
7707 redir->rd_filename);
7708 setup_heredoc(redir);
7712 if (redir->rd_dup == REDIRFD_TO_FILE) {
7713 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
7717 if (redir->rd_filename == NULL) {
7719 * "cmd >" (no filename)
7720 * "cmd > <file" (2nd redirect starts too early)
7722 syntax_error("invalid redirect");
7725 mode = redir_table[redir->rd_type].mode;
7726 p = expand_string_to_string(redir->rd_filename,
7727 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
7728 newfd = open_or_warn(p, mode);
7731 /* Error message from open_or_warn can be lost
7732 * if stderr has been redirected, but bash
7733 * and ash both lose it as well
7734 * (though zsh doesn't!)
7738 if (newfd == redir->rd_fd && sqp) {
7739 /* open() gave us precisely the fd we wanted.
7740 * This means that this fd was not busy
7741 * (not opened to anywhere).
7742 * Remember to close it on restore:
7744 *sqp = add_squirrel_closed(*sqp, newfd);
7745 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7748 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7749 newfd = redir->rd_dup;
7752 if (newfd == redir->rd_fd)
7755 /* if "N>FILE": move newfd to redir->rd_fd */
7756 /* if "N>&M": dup newfd to redir->rd_fd */
7757 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7759 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7760 if (newfd == REDIRFD_CLOSE) {
7761 /* "N>&-" means "close me" */
7763 /* ^^^ optimization: saving may already
7764 * have closed it. If not... */
7765 close(redir->rd_fd);
7767 /* Sometimes we do another close on restore, getting EBADF.
7768 * Consider "echo 3>FILE 3>&-"
7769 * first redirect remembers "need to close 3",
7770 * and second redirect closes 3! Restore code then closes 3 again.
7773 /* if newfd is a script fd or saved fd, simulate EBADF */
7774 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
7776 //bb_perror_msg_and_die("can't duplicate file descriptor");
7777 newfd = -1; /* same effect as code above */
7779 xdup2(newfd, redir->rd_fd);
7780 if (redir->rd_dup == REDIRFD_TO_FILE)
7781 /* "rd_fd > FILE" */
7783 /* else: "rd_fd > rd_dup" */
7789 static char *find_in_path(const char *arg)
7792 const char *PATH = get_local_var_value("PATH");
7798 const char *end = strchrnul(PATH, ':');
7799 int sz = end - PATH; /* must be int! */
7803 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7805 /* We have xxx::yyyy in $PATH,
7806 * it means "use current dir" */
7809 if (access(ret, F_OK) == 0)
7822 static const struct built_in_command *find_builtin_helper(const char *name,
7823 const struct built_in_command *x,
7824 const struct built_in_command *end)
7827 if (strcmp(name, x->b_cmd) != 0) {
7831 debug_printf_exec("found builtin '%s'\n", name);
7836 static const struct built_in_command *find_builtin1(const char *name)
7838 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7840 static const struct built_in_command *find_builtin(const char *name)
7842 const struct built_in_command *x = find_builtin1(name);
7845 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7848 static void remove_nested_vars(void)
7850 struct variable *cur;
7851 struct variable **cur_pp;
7853 cur_pp = &G.top_var;
7854 while ((cur = *cur_pp) != NULL) {
7855 if (cur->var_nest_level <= G.var_nest_level) {
7856 cur_pp = &cur->next;
7860 if (cur->flg_export) {
7861 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7862 bb_unsetenv(cur->varstr);
7864 /* Remove from global list */
7865 *cur_pp = cur->next;
7867 if (!cur->max_len) {
7868 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7875 static void enter_var_nest_level(void)
7878 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7880 /* Try: f() { echo -n .; f; }; f
7881 * struct variable::var_nest_level is uint16_t,
7882 * thus limiting recursion to < 2^16.
7883 * In any case, with 8 Mbyte stack SEGV happens
7884 * not too long after 2^16 recursions anyway.
7886 if (G.var_nest_level > 0xff00)
7887 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7890 static void leave_var_nest_level(void)
7893 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7894 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7895 bb_error_msg_and_die("BUG: nesting underflow");
7897 remove_nested_vars();
7900 #if ENABLE_HUSH_FUNCTIONS
7901 static struct function **find_function_slot(const char *name)
7903 struct function *funcp;
7904 struct function **funcpp = &G.top_func;
7906 while ((funcp = *funcpp) != NULL) {
7907 if (strcmp(name, funcp->name) == 0) {
7908 debug_printf_exec("found function '%s'\n", name);
7911 funcpp = &funcp->next;
7916 static ALWAYS_INLINE const struct function *find_function(const char *name)
7918 const struct function *funcp = *find_function_slot(name);
7922 /* Note: takes ownership on name ptr */
7923 static struct function *new_function(char *name)
7925 struct function **funcpp = find_function_slot(name);
7926 struct function *funcp = *funcpp;
7928 if (funcp != NULL) {
7929 struct command *cmd = funcp->parent_cmd;
7930 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7932 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7934 /* Note: if !funcp->body, do not free body_as_string!
7935 * This is a special case of "-F name body" function:
7936 * body_as_string was not malloced! */
7938 free_pipe_list(funcp->body);
7940 free(funcp->body_as_string);
7944 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7945 cmd->argv[0] = funcp->name;
7946 cmd->group = funcp->body;
7948 cmd->group_as_string = funcp->body_as_string;
7952 debug_printf_exec("remembering new function '%s'\n", name);
7953 funcp = *funcpp = xzalloc(sizeof(*funcp));
7954 /*funcp->next = NULL;*/
7961 # if ENABLE_HUSH_UNSET
7962 static void unset_func(const char *name)
7964 struct function **funcpp = find_function_slot(name);
7965 struct function *funcp = *funcpp;
7967 if (funcp != NULL) {
7968 debug_printf_exec("freeing function '%s'\n", funcp->name);
7969 *funcpp = funcp->next;
7970 /* funcp is unlinked now, deleting it.
7971 * Note: if !funcp->body, the function was created by
7972 * "-F name body", do not free ->body_as_string
7973 * and ->name as they were not malloced. */
7975 free_pipe_list(funcp->body);
7978 free(funcp->body_as_string);
7987 #define exec_function(to_free, funcp, argv) \
7988 exec_function(funcp, argv)
7990 static void exec_function(char ***to_free,
7991 const struct function *funcp,
7992 char **argv) NORETURN;
7993 static void exec_function(char ***to_free,
7994 const struct function *funcp,
8000 argv[0] = G.global_argv[0];
8001 G.global_argv = argv;
8002 G.global_argc = n = 1 + string_array_len(argv + 1);
8004 // Example when we are here: "cmd | func"
8005 // func will run with saved-redirect fds open.
8006 // $ f() { echo /proc/self/fd/*; }
8008 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8009 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8012 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8013 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8014 // They are CLOEXEC so external programs won't see them, but
8015 // for "more correctness" we might want to close those extra fds here:
8016 //? close_saved_fds_and_FILE_fds();
8018 /* "we are in a function, ok to use return" */
8019 G_flag_return_in_progress = -1;
8020 enter_var_nest_level();
8021 IF_HUSH_LOCAL(G.func_nest_level++;)
8023 /* On MMU, funcp->body is always non-NULL */
8024 n = run_list(funcp->body);
8028 //? close_saved_fds_and_FILE_fds();
8030 //TODO: check whether "true | func_with_return" works
8032 re_execute_shell(to_free,
8033 funcp->body_as_string,
8040 static int run_function(const struct function *funcp, char **argv)
8046 save_and_replace_G_args(&sv, argv);
8048 /* "We are in function, ok to use return" */
8049 sv_flg = G_flag_return_in_progress;
8050 G_flag_return_in_progress = -1;
8052 /* Make "local" variables properly shadow previous ones */
8053 IF_HUSH_LOCAL(enter_var_nest_level();)
8054 IF_HUSH_LOCAL(G.func_nest_level++;)
8056 /* On MMU, funcp->body is always non-NULL */
8059 /* Function defined by -F */
8060 parse_and_run_string(funcp->body_as_string);
8061 rc = G.last_exitcode;
8065 rc = run_list(funcp->body);
8068 IF_HUSH_LOCAL(G.func_nest_level--;)
8069 IF_HUSH_LOCAL(leave_var_nest_level();)
8071 G_flag_return_in_progress = sv_flg;
8073 restore_G_args(&sv, argv);
8077 #endif /* ENABLE_HUSH_FUNCTIONS */
8081 #define exec_builtin(to_free, x, argv) \
8082 exec_builtin(x, argv)
8084 #define exec_builtin(to_free, x, argv) \
8085 exec_builtin(to_free, argv)
8087 static void exec_builtin(char ***to_free,
8088 const struct built_in_command *x,
8089 char **argv) NORETURN;
8090 static void exec_builtin(char ***to_free,
8091 const struct built_in_command *x,
8097 //? close_saved_fds_and_FILE_fds();
8098 rcode = x->b_function(argv);
8103 /* On NOMMU, we must never block!
8104 * Example: { sleep 99 | read line; } & echo Ok
8106 re_execute_shell(to_free,
8115 static void execvp_or_die(char **argv) NORETURN;
8116 static void execvp_or_die(char **argv)
8119 debug_printf_exec("execing '%s'\n", argv[0]);
8120 /* Don't propagate SIG_IGN to the child */
8121 if (SPECIAL_JOBSTOP_SIGS != 0)
8122 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8123 execvp(argv[0], argv);
8125 if (errno == EACCES) e = 126;
8126 if (errno == ENOENT) e = 127;
8127 bb_perror_msg("can't execute '%s'", argv[0]);
8131 #if ENABLE_HUSH_MODE_X
8132 static void x_mode_print_optionally_squoted(const char *str)
8139 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8140 /* test a char with: bash -c 'set -x; echo "CH"' */
8141 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8142 " " "\001\002\003\004\005\006\007"
8143 "\010\011\012\013\014\015\016\017"
8144 "\020\021\022\023\024\025\026\027"
8145 "\030\031\032\033\034\035\036\037"
8149 /* string has no special chars */
8156 /* print '....' up to EOL or first squote */
8157 len = (int)(strchrnul(cp, '\'') - cp);
8159 x_mode_addchr('\'');
8160 x_mode_addblock(cp, len);
8161 x_mode_addchr('\'');
8166 /* string contains squote(s), print them as \' */
8167 x_mode_addchr('\\');
8168 x_mode_addchr('\'');
8172 static void dump_cmd_in_x_mode(char **argv)
8174 if (G_x_mode && argv) {
8177 /* "+[+++...][ cmd...]\n\0" */
8182 if (argv[n][0] == '\0') {
8183 x_mode_addchr('\'');
8184 x_mode_addchr('\'');
8186 x_mode_print_optionally_squoted(argv[n]);
8194 # define dump_cmd_in_x_mode(argv) ((void)0)
8197 #if ENABLE_HUSH_COMMAND
8198 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8207 char *path = getenv("PATH");
8208 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
8210 _exit(1); /* PROG was not found */
8212 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8214 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
8220 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
8224 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8225 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8226 #define pseudo_exec(nommu_save, command, argv_expanded) \
8227 pseudo_exec(command, argv_expanded)
8230 /* Called after [v]fork() in run_pipe, or from builtin_exec.
8232 * Don't exit() here. If you don't exec, use _exit instead.
8233 * The at_exit handlers apparently confuse the calling process,
8234 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
8236 static void pseudo_exec_argv(nommu_save_t *nommu_save,
8237 char **argv, int assignment_cnt,
8238 char **argv_expanded) NORETURN;
8239 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8240 char **argv, int assignment_cnt,
8241 char **argv_expanded)
8243 const struct built_in_command *x;
8244 struct variable **sv_shadowed;
8246 IF_HUSH_COMMAND(char opt_vV = 0;)
8247 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8249 new_env = expand_assignments(argv, assignment_cnt);
8250 dump_cmd_in_x_mode(new_env);
8252 if (!argv[assignment_cnt]) {
8253 /* Case when we are here: ... | var=val | ...
8254 * (note that we do not exit early, i.e., do not optimize out
8255 * expand_assignments(): think about ... | var=`sleep 1` | ...
8257 free_strings(new_env);
8258 _exit(EXIT_SUCCESS);
8261 sv_shadowed = G.shadowed_vars_pp;
8263 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
8265 G.shadowed_vars_pp = &nommu_save->old_vars;
8268 set_vars_and_save_old(new_env);
8269 G.shadowed_vars_pp = sv_shadowed;
8271 if (argv_expanded) {
8272 argv = argv_expanded;
8274 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8276 nommu_save->argv = argv;
8279 dump_cmd_in_x_mode(argv);
8281 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8282 if (strchr(argv[0], '/') != NULL)
8286 #if ENABLE_HUSH_FUNCTIONS
8287 /* Check if the command matches any functions (this goes before bltins) */
8288 funcp = find_function(argv[0]);
8290 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
8293 #if ENABLE_HUSH_COMMAND
8294 /* "command BAR": run BAR without looking it up among functions
8295 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8296 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8298 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8303 if (p[0] != '-' || !p[1])
8304 continue; /* bash allows "command command command [-OPT] BAR" */
8312 if (p[0] != '-' || !p[1])
8314 continue; /* next arg is also -opts, process it too */
8320 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8325 # if ENABLE_HUSH_FUNCTIONS
8326 if (opt_vV && find_function(argv[0]))
8327 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8331 /* Check if the command matches any of the builtins.
8332 * Depending on context, this might be redundant. But it's
8333 * easier to waste a few CPU cycles than it is to figure out
8334 * if this is one of those cases.
8336 /* Why "BB_MMU ? :" difference in logic? -
8337 * On NOMMU, it is more expensive to re-execute shell
8338 * just in order to run echo or test builtin.
8339 * It's better to skip it here and run corresponding
8340 * non-builtin later. */
8341 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8343 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8344 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
8347 #if ENABLE_FEATURE_SH_STANDALONE
8348 /* Check if the command matches any busybox applets */
8350 int a = find_applet_by_name(argv[0]);
8352 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
8353 # if BB_MMU /* see above why on NOMMU it is not allowed */
8354 if (APPLET_IS_NOEXEC(a)) {
8355 /* Do not leak open fds from opened script files etc.
8356 * Testcase: interactive "ls -l /proc/self/fd"
8357 * should not show tty fd open.
8359 close_saved_fds_and_FILE_fds();
8360 //FIXME: should also close saved redir fds
8361 //This casuses test failures in
8362 //redir_children_should_not_see_saved_fd_2.tests
8363 //redir_children_should_not_see_saved_fd_3.tests
8364 //if you replace "busybox find" with just "find" in them
8365 /* Without this, "rm -i FILE" can't be ^C'ed: */
8366 switch_off_special_sigs(G.special_sig_mask);
8367 debug_printf_exec("running applet '%s'\n", argv[0]);
8368 run_noexec_applet_and_exit(a, argv[0], argv);
8371 /* Re-exec ourselves */
8372 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
8373 /* Don't propagate SIG_IGN to the child */
8374 if (SPECIAL_JOBSTOP_SIGS != 0)
8375 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8376 execv(bb_busybox_exec_path, argv);
8377 /* If they called chroot or otherwise made the binary no longer
8378 * executable, fall through */
8383 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8386 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
8387 execvp_or_die(argv);
8390 /* Called after [v]fork() in run_pipe
8392 static void pseudo_exec(nommu_save_t *nommu_save,
8393 struct command *command,
8394 char **argv_expanded) NORETURN;
8395 static void pseudo_exec(nommu_save_t *nommu_save,
8396 struct command *command,
8397 char **argv_expanded)
8399 #if ENABLE_HUSH_FUNCTIONS
8400 if (command->cmd_type == CMD_FUNCDEF) {
8401 /* Ignore funcdefs in pipes:
8402 * true | f() { cmd }
8408 if (command->argv) {
8409 pseudo_exec_argv(nommu_save, command->argv,
8410 command->assignment_cnt, argv_expanded);
8413 if (command->group) {
8414 /* Cases when we are here:
8417 * ... | ( list ) | ...
8418 * ... | { list } | ...
8422 debug_printf_exec("pseudo_exec: run_list\n");
8423 reset_traps_to_defaults();
8424 rcode = run_list(command->group);
8425 /* OK to leak memory by not calling free_pipe_list,
8426 * since this process is about to exit */
8429 re_execute_shell(&nommu_save->argv_from_re_execing,
8430 command->group_as_string,
8437 /* Case when we are here: ... | >file */
8438 debug_printf_exec("pseudo_exec'ed null command\n");
8439 _exit(EXIT_SUCCESS);
8443 static const char *get_cmdtext(struct pipe *pi)
8449 /* This is subtle. ->cmdtext is created only on first backgrounding.
8450 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8451 * On subsequent bg argv is trashed, but we won't use it */
8455 argv = pi->cmds[0].argv;
8457 pi->cmdtext = xzalloc(1);
8462 len += strlen(*argv) + 1;
8466 argv = pi->cmds[0].argv;
8468 p = stpcpy(p, *argv);
8475 static void remove_job_from_table(struct pipe *pi)
8477 struct pipe *prev_pipe;
8479 if (pi == G.job_list) {
8480 G.job_list = pi->next;
8482 prev_pipe = G.job_list;
8483 while (prev_pipe->next != pi)
8484 prev_pipe = prev_pipe->next;
8485 prev_pipe->next = pi->next;
8489 G.last_jobid = G.job_list->jobid;
8492 static void delete_finished_job(struct pipe *pi)
8494 remove_job_from_table(pi);
8498 static void clean_up_last_dead_job(void)
8500 if (G.job_list && !G.job_list->alive_cmds)
8501 delete_finished_job(G.job_list);
8504 static void insert_job_into_table(struct pipe *pi)
8506 struct pipe *job, **jobp;
8509 clean_up_last_dead_job();
8511 /* Find the end of the list, and find next job ID to use */
8514 while ((job = *jobp) != NULL) {
8521 /* Create a new job struct at the end */
8522 job = *jobp = xmemdup(pi, sizeof(*pi));
8524 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8525 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8526 for (i = 0; i < pi->num_cmds; i++) {
8527 job->cmds[i].pid = pi->cmds[i].pid;
8528 /* all other fields are not used and stay zero */
8530 job->cmdtext = xstrdup(get_cmdtext(pi));
8532 if (G_interactive_fd)
8533 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
8534 G.last_jobid = job->jobid;
8538 static int job_exited_or_stopped(struct pipe *pi)
8542 if (pi->alive_cmds != pi->stopped_cmds)
8545 /* All processes in fg pipe have exited or stopped */
8549 rcode = pi->cmds[i].cmd_exitcode;
8550 /* usually last process gives overall exitstatus,
8551 * but with "set -o pipefail", last *failed* process does */
8552 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8555 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8559 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
8566 dead = WIFEXITED(status) || WIFSIGNALED(status);
8569 if (WIFSTOPPED(status))
8570 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8571 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8572 if (WIFSIGNALED(status))
8573 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8574 childpid, WTERMSIG(status), WEXITSTATUS(status));
8575 if (WIFEXITED(status))
8576 debug_printf_jobs("pid %d exited, exitcode %d\n",
8577 childpid, WEXITSTATUS(status));
8579 /* Were we asked to wait for a fg pipe? */
8581 i = fg_pipe->num_cmds;
8586 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8587 if (fg_pipe->cmds[i].pid != childpid)
8591 fg_pipe->cmds[i].pid = 0;
8592 fg_pipe->alive_cmds--;
8593 ex = WEXITSTATUS(status);
8594 /* bash prints killer signal's name for *last*
8595 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8596 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8598 if (WIFSIGNALED(status)) {
8599 int sig = WTERMSIG(status);
8600 if (i == fg_pipe->num_cmds-1)
8601 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8602 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8603 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8604 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8605 * Maybe we need to use sig | 128? */
8608 fg_pipe->cmds[i].cmd_exitcode = ex;
8610 fg_pipe->stopped_cmds++;
8612 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8613 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
8614 rcode = job_exited_or_stopped(fg_pipe);
8616 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
8617 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8618 * and "killall -STOP cat" */
8619 if (G_interactive_fd) {
8621 if (fg_pipe->alive_cmds != 0)
8622 insert_job_into_table(fg_pipe);
8626 if (fg_pipe->alive_cmds == 0)
8629 /* There are still running processes in the fg_pipe */
8632 /* It wasn't in fg_pipe, look for process in bg pipes */
8636 /* We were asked to wait for bg or orphaned children */
8637 /* No need to remember exitcode in this case */
8638 for (pi = G.job_list; pi; pi = pi->next) {
8639 for (i = 0; i < pi->num_cmds; i++) {
8640 if (pi->cmds[i].pid == childpid)
8641 goto found_pi_and_prognum;
8644 /* Happens when shell is used as init process (init=/bin/sh) */
8645 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8646 return -1; /* this wasn't a process from fg_pipe */
8648 found_pi_and_prognum:
8651 int rcode = WEXITSTATUS(status);
8652 if (WIFSIGNALED(status))
8653 rcode = 128 + WTERMSIG(status);
8654 pi->cmds[i].cmd_exitcode = rcode;
8655 if (G.last_bg_pid == pi->cmds[i].pid)
8656 G.last_bg_pid_exitcode = rcode;
8657 pi->cmds[i].pid = 0;
8659 if (!pi->alive_cmds) {
8660 if (G_interactive_fd) {
8661 printf(JOB_STATUS_FORMAT, pi->jobid,
8662 "Done", pi->cmdtext);
8663 delete_finished_job(pi);
8666 * bash deletes finished jobs from job table only in interactive mode,
8667 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8668 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8669 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8670 * We only retain one "dead" job, if it's the single job on the list.
8671 * This covers most of real-world scenarios where this is useful.
8673 if (pi != G.job_list)
8674 delete_finished_job(pi);
8682 return -1; /* this wasn't a process from fg_pipe */
8685 /* Check to see if any processes have exited -- if they have,
8686 * figure out why and see if a job has completed.
8688 * If non-NULL fg_pipe: wait for its completion or stop.
8689 * Return its exitcode or zero if stopped.
8691 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8692 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8693 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8694 * or 0 if no children changed status.
8696 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8697 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8698 * or 0 if no children changed status.
8700 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8706 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8708 attributes = WUNTRACED;
8709 if (fg_pipe == NULL)
8710 attributes |= WNOHANG;
8713 #if ENABLE_HUSH_FAST
8714 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8715 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8716 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8717 /* There was neither fork nor SIGCHLD since last waitpid */
8718 /* Avoid doing waitpid syscall if possible */
8719 if (!G.we_have_children) {
8723 if (fg_pipe == NULL) { /* is WNOHANG set? */
8724 /* We have children, but they did not exit
8725 * or stop yet (we saw no SIGCHLD) */
8728 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8732 /* Do we do this right?
8733 * bash-3.00# sleep 20 | false
8735 * [3]+ Stopped sleep 20 | false
8736 * bash-3.00# echo $?
8737 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8738 * [hush 1.14.0: yes we do it right]
8742 #if ENABLE_HUSH_FAST
8744 i = G.count_SIGCHLD;
8746 childpid = waitpid(-1, &status, attributes);
8747 if (childpid <= 0) {
8748 if (childpid && errno != ECHILD)
8749 bb_perror_msg("waitpid");
8750 #if ENABLE_HUSH_FAST
8751 else { /* Until next SIGCHLD, waitpid's are useless */
8752 G.we_have_children = (childpid == 0);
8753 G.handled_SIGCHLD = i;
8754 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8757 /* ECHILD (no children), or 0 (no change in children status) */
8761 rcode = process_wait_result(fg_pipe, childpid, status);
8763 /* fg_pipe exited or stopped */
8766 if (childpid == waitfor_pid) {
8767 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
8768 rcode = WEXITSTATUS(status);
8769 if (WIFSIGNALED(status))
8770 rcode = 128 + WTERMSIG(status);
8771 if (WIFSTOPPED(status))
8772 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8773 rcode = 128 + WSTOPSIG(status);
8775 break; /* "wait PID" called us, give it exitcode+1 */
8777 /* This wasn't one of our processes, or */
8778 /* fg_pipe still has running processes, do waitpid again */
8779 } /* while (waitpid succeeds)... */
8785 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
8788 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
8789 if (G_saved_tty_pgrp) {
8790 /* Job finished, move the shell to the foreground */
8791 p = getpgrp(); /* our process group id */
8792 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8793 tcsetpgrp(G_interactive_fd, p);
8799 /* Start all the jobs, but don't wait for anything to finish.
8802 * Return code is normally -1, when the caller has to wait for children
8803 * to finish to determine the exit status of the pipe. If the pipe
8804 * is a simple builtin command, however, the action is done by the
8805 * time run_pipe returns, and the exit code is provided as the
8808 * Returns -1 only if started some children. IOW: we have to
8809 * mask out retvals of builtins etc with 0xff!
8811 * The only case when we do not need to [v]fork is when the pipe
8812 * is single, non-backgrounded, non-subshell command. Examples:
8813 * cmd ; ... { list } ; ...
8814 * cmd && ... { list } && ...
8815 * cmd || ... { list } || ...
8816 * If it is, then we can run cmd as a builtin, NOFORK,
8817 * or (if SH_STANDALONE) an applet, and we can run the { list }
8818 * with run_list. If it isn't one of these, we fork and exec cmd.
8820 * Cases when we must fork:
8821 * non-single: cmd | cmd
8822 * backgrounded: cmd & { list } &
8823 * subshell: ( list ) [&]
8825 #if !ENABLE_HUSH_MODE_X
8826 #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8827 redirect_and_varexp_helper(command, sqp)
8829 static int redirect_and_varexp_helper(
8830 struct command *command,
8831 struct squirrel **sqp,
8832 char **argv_expanded)
8834 /* Assignments occur before redirects. Try:
8835 * a=`sleep 1` sleep 2 3>/qwe/rty
8838 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8839 dump_cmd_in_x_mode(new_env);
8840 dump_cmd_in_x_mode(argv_expanded);
8841 /* this takes ownership of new_env[i] elements, and frees new_env: */
8842 set_vars_and_save_old(new_env);
8844 return setup_redirects(command, sqp);
8846 static NOINLINE int run_pipe(struct pipe *pi)
8848 static const char *const null_ptr = NULL;
8852 struct command *command;
8853 char **argv_expanded;
8855 struct squirrel *squirrel = NULL;
8858 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8861 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8862 * Result should be 3 lines: q w e, qwe, q w e
8864 if (G.ifs_whitespace != G.ifs)
8865 free(G.ifs_whitespace);
8866 G.ifs = get_local_var_value("IFS");
8869 G.ifs_whitespace = (char*)G.ifs;
8870 p = skip_whitespace(G.ifs);
8872 /* Not all $IFS is whitespace */
8874 int len = p - G.ifs;
8875 p = skip_non_whitespace(p);
8876 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8877 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8887 G.ifs_whitespace = (char*)G.ifs;
8890 IF_HUSH_JOB(pi->pgrp = -1;)
8891 pi->stopped_cmds = 0;
8892 command = &pi->cmds[0];
8893 argv_expanded = NULL;
8895 if (pi->num_cmds != 1
8896 || pi->followup == PIPE_BG
8897 || command->cmd_type == CMD_SUBSHELL
8904 debug_printf_exec(": group:%p argv:'%s'\n",
8905 command->group, command->argv ? command->argv[0] : "NONE");
8907 if (command->group) {
8908 #if ENABLE_HUSH_FUNCTIONS
8909 if (command->cmd_type == CMD_FUNCDEF) {
8910 /* "executing" func () { list } */
8911 struct function *funcp;
8913 funcp = new_function(command->argv[0]);
8914 /* funcp->name is already set to argv[0] */
8915 funcp->body = command->group;
8917 funcp->body_as_string = command->group_as_string;
8918 command->group_as_string = NULL;
8920 command->group = NULL;
8921 command->argv[0] = NULL;
8922 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8923 funcp->parent_cmd = command;
8924 command->child_func = funcp;
8926 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8928 return EXIT_SUCCESS;
8932 debug_printf_exec("non-subshell group\n");
8933 rcode = 1; /* exitcode if redir failed */
8934 if (setup_redirects(command, &squirrel) == 0) {
8935 debug_printf_exec(": run_list\n");
8936 //FIXME: we need to pass squirrel down into run_list()
8937 //for SH_STANDALONE case, or else this construct:
8938 // { find /proc/self/fd; true; } >FILE; cmd2
8939 //has no way of closing saved fd#1 for "find",
8940 //and in SH_STANDALONE mode, "find" is not execed,
8941 //therefore CLOEXEC on saved fd does not help.
8942 rcode = run_list(command->group) & 0xff;
8944 restore_redirects(squirrel);
8945 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8947 debug_printf_exec("run_pipe: return %d\n", rcode);
8951 argv = command->argv ? command->argv : (char **) &null_ptr;
8953 const struct built_in_command *x;
8954 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8955 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
8956 struct variable **sv_shadowed;
8957 struct variable *old_vars;
8959 #if ENABLE_HUSH_LINENO_VAR
8961 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8964 if (argv[command->assignment_cnt] == NULL) {
8965 /* Assignments, but no command.
8966 * Ensure redirects take effect (that is, create files).
8970 G.expand_exitcode = 0;
8972 rcode = setup_redirects(command, &squirrel);
8973 restore_redirects(squirrel);
8975 /* Set shell variables */
8977 while (i < command->assignment_cnt) {
8978 char *p = expand_string_to_string(argv[i],
8979 EXP_FLAG_ESC_GLOB_CHARS,
8982 #if ENABLE_HUSH_MODE_X
8988 eq = strchrnul(p, '=');
8990 x_mode_addblock(p, (eq - p));
8991 x_mode_print_optionally_squoted(eq);
8995 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
8996 if (set_local_var(p, /*flag:*/ 0)) {
8997 /* assignment to readonly var / putenv error? */
9002 /* Redirect error sets $? to 1. Otherwise,
9003 * if evaluating assignment value set $?, retain it.
9005 * false; q=`exit 2`; echo $? - should print 2
9006 * false; x=1; echo $? - should print 0
9007 * Because of the 2nd case, we can't just use G.last_exitcode.
9010 rcode = G.expand_exitcode;
9011 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9013 debug_printf_exec("run_pipe: return %d\n", rcode);
9017 /* Expand the rest into (possibly) many strings each */
9018 #if defined(CMD_SINGLEWORD_NOGLOB)
9019 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
9020 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9023 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
9025 /* If someone gives us an empty string: `cmd with empty output` */
9026 if (!argv_expanded[0]) {
9027 free(argv_expanded);
9028 /* `false` still has to set exitcode 1 */
9029 G.expand_exitcode = G.last_exitcode;
9030 goto only_assignments;
9034 sv_shadowed = G.shadowed_vars_pp;
9036 /* Check if argv[0] matches any functions (this goes before bltins) */
9037 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9038 IF_HUSH_FUNCTIONS(x = NULL;)
9039 IF_HUSH_FUNCTIONS(if (!funcp))
9040 x = find_builtin(argv_expanded[0]);
9042 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9043 debug_printf("exec with redirects only\n");
9045 * Variable assignments are executed, but then "forgotten":
9046 * a=`sleep 1;echo A` exec 3>&-; echo $a
9047 * sleeps, but prints nothing.
9049 enter_var_nest_level();
9050 G.shadowed_vars_pp = &old_vars;
9051 rcode = redirect_and_varexp_helper(command,
9052 /*squirrel:*/ ERR_PTR,
9055 G.shadowed_vars_pp = sv_shadowed;
9056 /* rcode=1 can be if redir file can't be opened */
9058 goto clean_up_and_ret1;
9061 /* Bump var nesting, or this will leak exported $a:
9062 * a=b true; env | grep ^a=
9064 enter_var_nest_level();
9065 /* Collect all variables "shadowed" by helper
9066 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9067 * into old_vars list:
9069 G.shadowed_vars_pp = &old_vars;
9070 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9073 /* Do not collect *to old_vars list* vars shadowed
9074 * by e.g. "local VAR" builtin (collect them
9075 * in the previously nested list instead):
9076 * don't want them to be restored immediately
9077 * after "local" completes.
9079 G.shadowed_vars_pp = sv_shadowed;
9081 debug_printf_exec(": builtin '%s' '%s'...\n",
9082 x->b_cmd, argv_expanded[1]);
9084 rcode = x->b_function(argv_expanded) & 0xff;
9087 #if ENABLE_HUSH_FUNCTIONS
9089 debug_printf_exec(": function '%s' '%s'...\n",
9090 funcp->name, argv_expanded[1]);
9091 rcode = run_function(funcp, argv_expanded) & 0xff;
9093 * But do collect *to old_vars list* vars shadowed
9094 * within function execution. To that end, restore
9095 * this pointer _after_ function run:
9097 G.shadowed_vars_pp = sv_shadowed;
9102 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
9103 int n = find_applet_by_name(argv_expanded[0]);
9104 if (n < 0 || !APPLET_IS_NOFORK(n))
9107 enter_var_nest_level();
9108 /* Collect all variables "shadowed" by helper into old_vars list */
9109 G.shadowed_vars_pp = &old_vars;
9110 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9111 G.shadowed_vars_pp = sv_shadowed;
9114 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9115 argv_expanded[0], argv_expanded[1]);
9117 * Note: signals (^C) can't interrupt here.
9118 * We remember them and they will be acted upon
9119 * after applet returns.
9120 * This makes applets which can run for a long time
9121 * and/or wait for user input ineligible for NOFORK:
9122 * for example, "yes" or "rm" (rm -i waits for input).
9124 rcode = run_nofork_applet(n, argv_expanded);
9129 restore_redirects(squirrel);
9131 leave_var_nest_level();
9135 * Try "usleep 99999999" + ^C + "echo $?"
9136 * with FEATURE_SH_NOFORK=y.
9139 /* It was builtin or nofork.
9140 * if this would be a real fork/execed program,
9141 * it should have died if a fatal sig was received.
9142 * But OTOH, there was no separate process,
9143 * the sig was sent to _shell_, not to non-existing
9145 * Let's just handle ^C only, this one is obvious:
9146 * we aren't ok with exitcode 0 when ^C was pressed
9147 * during builtin/nofork.
9149 if (sigismember(&G.pending_set, SIGINT))
9150 rcode = 128 + SIGINT;
9152 free(argv_expanded);
9153 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9155 debug_printf_exec("run_pipe return %d\n", rcode);
9160 /* NB: argv_expanded may already be created, and that
9161 * might include `cmd` runs! Do not rerun it! We *must*
9162 * use argv_expanded if it's non-NULL */
9164 /* Going to fork a child per each pipe member */
9169 while (cmd_no < pi->num_cmds) {
9170 struct fd_pair pipefds;
9172 int sv_var_nest_level = G.var_nest_level;
9173 volatile nommu_save_t nommu_save;
9174 nommu_save.old_vars = NULL;
9175 nommu_save.argv = NULL;
9176 nommu_save.argv_from_re_execing = NULL;
9178 command = &pi->cmds[cmd_no];
9180 if (command->argv) {
9181 debug_printf_exec(": pipe member '%s' '%s'...\n",
9182 command->argv[0], command->argv[1]);
9184 debug_printf_exec(": pipe member with no argv\n");
9187 /* pipes are inserted between pairs of commands */
9190 if (cmd_no < pi->num_cmds)
9191 xpiped_pair(pipefds);
9193 #if ENABLE_HUSH_LINENO_VAR
9195 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9198 command->pid = BB_MMU ? fork() : vfork();
9199 if (!command->pid) { /* child */
9201 disable_restore_tty_pgrp_on_exit();
9202 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9204 /* Every child adds itself to new process group
9205 * with pgid == pid_of_first_child_in_pipe */
9206 if (G.run_list_level == 1 && G_interactive_fd) {
9209 if (pgrp < 0) /* true for 1st process only */
9211 if (setpgid(0, pgrp) == 0
9212 && pi->followup != PIPE_BG
9213 && G_saved_tty_pgrp /* we have ctty */
9215 /* We do it in *every* child, not just first,
9217 tcsetpgrp(G_interactive_fd, pgrp);
9221 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9222 /* 1st cmd in backgrounded pipe
9223 * should have its stdin /dev/null'ed */
9225 if (open(bb_dev_null, O_RDONLY))
9226 xopen("/", O_RDONLY);
9228 xmove_fd(next_infd, 0);
9230 xmove_fd(pipefds.wr, 1);
9233 /* Like bash, explicit redirects override pipes,
9234 * and the pipe fd (fd#1) is available for dup'ing:
9235 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9236 * of cmd1 goes into pipe.
9238 if (setup_redirects(command, NULL)) {
9239 /* Happens when redir file can't be opened:
9240 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9242 * hush: can't open '/qwe/rty': No such file or directory
9244 * (echo BAR is not executed, it hits _exit(1) below)
9249 /* Stores to nommu_save list of env vars putenv'ed
9250 * (NOMMU, on MMU we don't need that) */
9251 /* cast away volatility... */
9252 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9253 /* pseudo_exec() does not return */
9256 /* parent or error */
9257 #if ENABLE_HUSH_FAST
9259 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9261 enable_restore_tty_pgrp_on_exit();
9263 /* Clean up after vforked child */
9264 free(nommu_save.argv);
9265 free(nommu_save.argv_from_re_execing);
9266 G.var_nest_level = sv_var_nest_level;
9267 remove_nested_vars();
9268 add_vars(nommu_save.old_vars);
9270 free(argv_expanded);
9271 argv_expanded = NULL;
9272 if (command->pid < 0) { /* [v]fork failed */
9273 /* Clearly indicate, was it fork or vfork */
9274 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9278 /* Second and next children need to know pid of first one */
9280 pi->pgrp = command->pid;
9286 if (cmd_no < pi->num_cmds)
9288 /* Pass read (output) pipe end to next iteration */
9289 next_infd = pipefds.rd;
9292 if (!pi->alive_cmds) {
9294 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9299 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9303 /* NB: called by pseudo_exec, and therefore must not modify any
9304 * global data until exec/_exit (we can be a child after vfork!) */
9305 static int run_list(struct pipe *pi)
9307 #if ENABLE_HUSH_CASE
9308 char *case_word = NULL;
9310 #if ENABLE_HUSH_LOOPS
9311 struct pipe *loop_top = NULL;
9312 char **for_lcur = NULL;
9313 char **for_list = NULL;
9315 smallint last_followup;
9317 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9318 smalluint cond_code = 0;
9320 enum { cond_code = 0 };
9323 smallint rword; /* RES_foo */
9324 smallint last_rword; /* ditto */
9327 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9330 #if ENABLE_HUSH_LOOPS
9331 /* Check syntax for "for" */
9334 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9335 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9337 /* current word is FOR or IN (BOLD in comments below) */
9338 if (cpipe->next == NULL) {
9339 syntax_error("malformed for");
9341 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9344 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9345 if (cpipe->next->res_word == RES_DO)
9347 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9348 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9349 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9351 syntax_error("malformed for");
9353 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9360 /* Past this point, all code paths should jump to ret: label
9361 * in order to return, no direct "return" statements please.
9362 * This helps to ensure that no memory is leaked. */
9370 last_rword = RES_XXXX;
9372 last_followup = PIPE_SEQ;
9373 rcode = G.last_exitcode;
9375 /* Go through list of pipes, (maybe) executing them. */
9376 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
9378 int sv_errexit_depth;
9382 if (G_flag_return_in_progress == 1)
9385 IF_HAS_KEYWORDS(rword = pi->res_word;)
9386 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9387 rword, cond_code, last_rword);
9389 sv_errexit_depth = G.errexit_depth;
9392 rword == RES_IF || rword == RES_ELIF ||
9394 pi->followup != PIPE_SEQ
9398 #if ENABLE_HUSH_LOOPS
9399 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9400 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9402 /* start of a loop: remember where loop starts */
9407 /* Still in the same "if...", "then..." or "do..." branch? */
9408 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9409 if ((rcode == 0 && last_followup == PIPE_OR)
9410 || (rcode != 0 && last_followup == PIPE_AND)
9412 /* It is "<true> || CMD" or "<false> && CMD"
9413 * and we should not execute CMD */
9414 debug_printf_exec("skipped cmd because of || or &&\n");
9415 last_followup = pi->followup;
9416 goto dont_check_jobs_but_continue;
9419 last_followup = pi->followup;
9420 IF_HAS_KEYWORDS(last_rword = rword;)
9423 if (rword == RES_THEN) {
9424 /* if false; then ... fi has exitcode 0! */
9425 G.last_exitcode = rcode = EXIT_SUCCESS;
9426 /* "if <false> THEN cmd": skip cmd */
9430 if (rword == RES_ELSE || rword == RES_ELIF) {
9431 /* "if <true> then ... ELSE/ELIF cmd":
9432 * skip cmd and all following ones */
9437 #if ENABLE_HUSH_LOOPS
9438 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9440 /* first loop through for */
9442 static const char encoded_dollar_at[] ALIGN1 = {
9443 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9444 }; /* encoded representation of "$@" */
9445 static const char *const encoded_dollar_at_argv[] = {
9446 encoded_dollar_at, NULL
9447 }; /* argv list with one element: "$@" */
9450 G.last_exitcode = rcode = EXIT_SUCCESS;
9451 vals = (char**)encoded_dollar_at_argv;
9452 if (pi->next->res_word == RES_IN) {
9453 /* if no variable values after "in" we skip "for" */
9454 if (!pi->next->cmds[0].argv) {
9455 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9458 vals = pi->next->cmds[0].argv;
9459 } /* else: "for var; do..." -> assume "$@" list */
9460 /* create list of variable values */
9461 debug_print_strings("for_list made from", vals);
9462 for_list = expand_strvec_to_strvec(vals);
9463 for_lcur = for_list;
9464 debug_print_strings("for_list", for_list);
9467 /* "for" loop is over, clean up */
9473 /* Insert next value from for_lcur */
9474 /* note: *for_lcur already has quotes removed, $var expanded, etc */
9475 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
9478 if (rword == RES_IN) {
9479 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9481 if (rword == RES_DONE) {
9482 continue; /* "done" has no cmds too */
9485 #if ENABLE_HUSH_CASE
9486 if (rword == RES_CASE) {
9487 debug_printf_exec("CASE cond_code:%d\n", cond_code);
9488 case_word = expand_string_to_string(pi->cmds->argv[0],
9489 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
9490 debug_printf_exec("CASE word1:'%s'\n", case_word);
9491 //unbackslash(case_word);
9492 //debug_printf_exec("CASE word2:'%s'\n", case_word);
9495 if (rword == RES_MATCH) {
9498 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
9499 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9501 /* all prev words didn't match, does this one match? */
9502 argv = pi->cmds->argv;
9505 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9506 pattern = expand_string_to_string(*argv,
9507 EXP_FLAG_ESC_GLOB_CHARS,
9510 /* TODO: which FNM_xxx flags to use? */
9511 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
9512 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9513 pattern, case_word, cond_code);
9515 if (cond_code == 0) {
9516 /* match! we will execute this branch */
9518 case_word = NULL; /* make future "word)" stop */
9525 if (rword == RES_CASE_BODY) { /* inside of a case branch */
9526 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
9528 continue; /* not matched yet, skip this pipe */
9530 if (rword == RES_ESAC) {
9531 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9533 /* "case" did not match anything: still set $? (to 0) */
9534 G.last_exitcode = rcode = EXIT_SUCCESS;
9538 /* Just pressing <enter> in shell should check for jobs.
9539 * OTOH, in non-interactive shell this is useless
9540 * and only leads to extra job checks */
9541 if (pi->num_cmds == 0) {
9542 if (G_interactive_fd)
9543 goto check_jobs_and_continue;
9547 /* After analyzing all keywords and conditions, we decided
9548 * to execute this pipe. NB: have to do checkjobs(NULL)
9549 * after run_pipe to collect any background children,
9550 * even if list execution is to be stopped. */
9551 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
9552 #if ENABLE_HUSH_LOOPS
9553 G.flag_break_continue = 0;
9555 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9557 /* We ran a builtin, function, or group.
9558 * rcode is already known
9559 * and we don't need to wait for anything. */
9560 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9561 G.last_exitcode = rcode;
9562 check_and_run_traps();
9563 #if ENABLE_HUSH_LOOPS
9564 /* Was it "break" or "continue"? */
9565 if (G.flag_break_continue) {
9566 smallint fbc = G.flag_break_continue;
9567 /* We might fall into outer *loop*,
9568 * don't want to break it too */
9570 G.depth_break_continue--;
9571 if (G.depth_break_continue == 0)
9572 G.flag_break_continue = 0;
9573 /* else: e.g. "continue 2" should *break* once, *then* continue */
9574 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9575 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
9576 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9579 /* "continue": simulate end of loop */
9584 if (G_flag_return_in_progress == 1) {
9585 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9588 } else if (pi->followup == PIPE_BG) {
9589 /* What does bash do with attempts to background builtins? */
9590 /* even bash 3.2 doesn't do that well with nested bg:
9591 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9592 * I'm NOT treating inner &'s as jobs */
9594 if (G.run_list_level == 1)
9595 insert_job_into_table(pi);
9597 /* Last command's pid goes to $! */
9598 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
9599 G.last_bg_pid_exitcode = 0;
9600 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
9601 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
9602 rcode = EXIT_SUCCESS;
9606 if (G.run_list_level == 1 && G_interactive_fd) {
9607 /* Waits for completion, then fg's main shell */
9608 rcode = checkjobs_and_fg_shell(pi);
9609 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
9613 /* This one just waits for completion */
9614 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9615 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9617 G.last_exitcode = rcode;
9618 check_and_run_traps();
9621 /* Handle "set -e" */
9622 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9623 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9624 if (G.errexit_depth == 0)
9627 G.errexit_depth = sv_errexit_depth;
9629 /* Analyze how result affects subsequent commands */
9631 if (rword == RES_IF || rword == RES_ELIF)
9634 check_jobs_and_continue:
9635 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9636 dont_check_jobs_but_continue: ;
9637 #if ENABLE_HUSH_LOOPS
9638 /* Beware of "while false; true; do ..."! */
9640 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
9641 /* check for RES_DONE is needed for "while ...; do \n done" case */
9643 if (rword == RES_WHILE) {
9645 /* "while false; do...done" - exitcode 0 */
9646 G.last_exitcode = rcode = EXIT_SUCCESS;
9647 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
9651 if (rword == RES_UNTIL) {
9653 debug_printf_exec(": until expr is true: breaking\n");
9664 #if ENABLE_HUSH_LOOPS
9669 #if ENABLE_HUSH_CASE
9673 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9677 /* Select which version we will use */
9678 static int run_and_free_list(struct pipe *pi)
9681 debug_printf_exec("run_and_free_list entered\n");
9682 if (!G.o_opt[OPT_O_NOEXEC]) {
9683 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9684 rcode = run_list(pi);
9686 /* free_pipe_list has the side effect of clearing memory.
9687 * In the long run that function can be merged with run_list,
9688 * but doing that now would hobble the debugging effort. */
9690 debug_printf_exec("run_and_free_list return %d\n", rcode);
9695 static void install_sighandlers(unsigned mask)
9697 sighandler_t old_handler;
9699 while ((mask >>= 1) != 0) {
9703 old_handler = install_sighandler(sig, pick_sighandler(sig));
9704 /* POSIX allows shell to re-enable SIGCHLD
9705 * even if it was SIG_IGN on entry.
9706 * Therefore we skip IGN check for it:
9710 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9711 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9713 //if (sig == SIGHUP) continue; - TODO?
9714 if (old_handler == SIG_IGN) {
9715 /* oops... restore back to IGN, and record this fact */
9716 install_sighandler(sig, old_handler);
9717 #if ENABLE_HUSH_TRAP
9719 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9721 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9727 /* Called a few times only (or even once if "sh -c") */
9728 static void install_special_sighandlers(void)
9732 /* Which signals are shell-special? */
9733 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
9734 if (G_interactive_fd) {
9735 mask |= SPECIAL_INTERACTIVE_SIGS;
9736 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
9737 mask |= SPECIAL_JOBSTOP_SIGS;
9739 /* Careful, do not re-install handlers we already installed */
9740 if (G.special_sig_mask != mask) {
9741 unsigned diff = mask & ~G.special_sig_mask;
9742 G.special_sig_mask = mask;
9743 install_sighandlers(diff);
9749 /* Set handlers to restore tty pgrp and exit */
9750 static void install_fatal_sighandlers(void)
9754 /* We will restore tty pgrp on these signals */
9756 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9757 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
9758 + (1 << SIGBUS ) * HUSH_DEBUG
9759 + (1 << SIGSEGV) * HUSH_DEBUG
9760 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
9762 /* bash 3.2 seems to handle these just like 'fatal' ones */
9765 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
9766 * if we aren't interactive... but in this case
9767 * we never want to restore pgrp on exit, and this fn is not called
9769 /*+ (1 << SIGHUP )*/
9770 /*+ (1 << SIGTERM)*/
9771 /*+ (1 << SIGINT )*/
9773 G_fatal_sig_mask = mask;
9775 install_sighandlers(mask);
9779 static int set_mode(int state, char mode, const char *o_opt)
9784 G.o_opt[OPT_O_NOEXEC] = state;
9787 IF_HUSH_MODE_X(G_x_mode = state;)
9788 IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
9792 /* "set -+o" without parameter.
9793 * in bash, set -o produces this output:
9797 * We always use the second form.
9799 const char *p = o_opt_strings;
9802 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9808 idx = index_in_strings(o_opt_strings, o_opt);
9810 G.o_opt[idx] = state;
9814 G.o_opt[OPT_O_ERREXIT] = state;
9817 return EXIT_FAILURE;
9819 return EXIT_SUCCESS;
9822 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
9823 int hush_main(int argc, char **argv)
9826 OPT_login = (1 << 0),
9830 unsigned builtin_argc;
9832 struct variable *cur_var;
9833 struct variable *shell_ver;
9836 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
9837 G.last_exitcode = EXIT_SUCCESS;
9839 #if ENABLE_HUSH_FAST
9840 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9843 G.argv0_for_re_execing = argv[0];
9846 /* Deal with HUSH_VERSION */
9847 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9848 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
9849 shell_ver = xzalloc(sizeof(*shell_ver));
9850 shell_ver->flg_export = 1;
9851 shell_ver->flg_read_only = 1;
9852 /* Code which handles ${var<op>...} needs writable values for all variables,
9853 * therefore we xstrdup: */
9854 shell_ver->varstr = xstrdup(hush_version_str);
9856 /* Create shell local variables from the values
9857 * currently living in the environment */
9858 G.top_var = shell_ver;
9859 cur_var = G.top_var;
9862 char *value = strchr(*e, '=');
9863 if (value) { /* paranoia */
9864 cur_var->next = xzalloc(sizeof(*cur_var));
9865 cur_var = cur_var->next;
9866 cur_var->varstr = *e;
9867 cur_var->max_len = strlen(*e);
9868 cur_var->flg_export = 1;
9872 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
9873 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9874 putenv(shell_ver->varstr);
9877 set_pwd_var(SETFLAG_EXPORT);
9879 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9880 /* Set (but not export) PS1/2 unless already set */
9881 if (!get_local_var_value("PS1"))
9882 set_local_var_from_halves("PS1", "\\w \\$ ");
9883 if (!get_local_var_value("PS2"))
9884 set_local_var_from_halves("PS2", "> ");
9887 #if BASH_HOSTNAME_VAR
9888 /* Set (but not export) HOSTNAME unless already set */
9889 if (!get_local_var_value("HOSTNAME")) {
9892 set_local_var_from_halves("HOSTNAME", uts.nodename);
9895 /* IFS is not inherited from the parent environment */
9896 set_local_var_from_halves("IFS", defifs);
9898 /* bash also exports SHLVL and _,
9899 * and sets (but doesn't export) the following variables:
9901 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9902 * BASH_VERSION='3.2.0(1)-release'
9904 * MACHTYPE=i386-pc-linux-gnu
9906 * PPID=<NNNNN> - we also do it elsewhere
9917 * PIPESTATUS=([0]="0")
9918 * HISTFILE=/<xxx>/.bash_history
9922 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9924 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9931 #if ENABLE_HUSH_LINENO_VAR
9932 if (ENABLE_HUSH_LINENO_VAR) {
9933 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9934 set_local_var(p, /*flags*/ 0);
9935 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9939 #if ENABLE_FEATURE_EDITING
9940 G.line_input_state = new_line_input_t(FOR_SHELL);
9943 /* Initialize some more globals to non-zero values */
9944 cmdedit_update_prompt();
9946 die_func = restore_ttypgrp_and__exit;
9948 /* Shell is non-interactive at first. We need to call
9949 * install_special_sighandlers() if we are going to execute "sh <script>",
9950 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9951 * If we later decide that we are interactive, we run install_special_sighandlers()
9952 * in order to intercept (more) signals.
9956 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9957 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9961 optarg = get_script_content(-argc - 1);
9963 argc = string_array_len(argv);
9968 int opt = getopt(argc, argv, "+c:exinsl"
9971 # if ENABLE_HUSH_FUNCTIONS
9981 * sh ... -c 'script'
9982 * sh ... -c 'script' ARG0 [ARG1...]
9983 * On NOMMU, if builtin_argc != 0,
9984 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9985 * "" needs to be replaced with NULL
9986 * and BARGV vector fed to builtin function.
9987 * Note: the form without ARG0 never happens:
9988 * sh ... -c 'builtin' BARGV... ""
9994 G.root_pid = getpid();
9995 G.root_ppid = getppid();
9997 G.global_argv = argv + optind;
9998 G.global_argc = argc - optind;
10000 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10001 const struct built_in_command *x;
10003 install_special_sighandlers();
10004 x = find_builtin(optarg);
10005 if (x) { /* paranoia */
10006 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10007 G.global_argv += builtin_argc;
10008 G.global_argv[-1] = NULL; /* replace "" */
10010 G.last_exitcode = x->b_function(argv + optind - 1);
10014 if (!G.global_argv[0]) {
10015 /* -c 'script' (no params): prevent empty $0 */
10016 G.global_argv--; /* points to argv[i] of 'script' */
10017 G.global_argv[0] = argv[0];
10019 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10020 install_special_sighandlers();
10021 parse_and_run_string(optarg);
10024 /* Well, we cannot just declare interactiveness,
10025 * we have to have some stuff (ctty, etc) */
10026 /* G_interactive_fd++; */
10032 flags |= OPT_login;
10035 case '<': /* "big heredoc" support */
10036 full_write1_str(optarg);
10039 unsigned long long empty_trap_mask;
10041 G.root_pid = bb_strtou(optarg, &optarg, 16);
10043 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10045 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10047 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
10049 builtin_argc = bb_strtou(optarg, &optarg, 16);
10051 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10052 if (empty_trap_mask != 0) {
10053 IF_HUSH_TRAP(int sig;)
10054 install_special_sighandlers();
10055 # if ENABLE_HUSH_TRAP
10056 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10057 for (sig = 1; sig < NSIG; sig++) {
10058 if (empty_trap_mask & (1LL << sig)) {
10059 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
10060 install_sighandler(sig, SIG_IGN);
10065 # if ENABLE_HUSH_LOOPS
10067 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
10069 # if ENABLE_HUSH_FUNCTIONS
10070 /* nommu uses re-exec trick for "... | func | ...",
10071 * should allow "return".
10072 * This accidentally allows returns in subshells.
10074 G_flag_return_in_progress = -1;
10080 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
10082 # if ENABLE_HUSH_FUNCTIONS
10084 struct function *funcp = new_function(optarg);
10085 /* funcp->name is already set to optarg */
10086 /* funcp->body is set to NULL. It's a special case. */
10087 funcp->body_as_string = argv[optind];
10096 if (set_mode(1, opt, NULL) == 0) /* no error */
10100 fprintf(stderr, "Usage: sh [FILE]...\n"
10101 " or: sh -c command [args]...\n\n");
10102 exit(EXIT_FAILURE);
10107 } /* option parsing loop */
10109 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10110 G.global_argc = argc - (optind - 1);
10111 G.global_argv = argv + (optind - 1);
10112 G.global_argv[0] = argv[0];
10115 G.root_pid = getpid();
10116 G.root_ppid = getppid();
10119 /* If we are login shell... */
10120 if (flags & OPT_login) {
10122 debug_printf("sourcing /etc/profile\n");
10123 input = hfopen("/etc/profile");
10124 if (input != NULL) {
10125 install_special_sighandlers();
10126 parse_and_run_file(input);
10129 /* bash: after sourcing /etc/profile,
10130 * tries to source (in the given order):
10131 * ~/.bash_profile, ~/.bash_login, ~/.profile,
10132 * stopping on first found. --noprofile turns this off.
10133 * bash also sources ~/.bash_logout on exit.
10134 * If called as sh, skips .bash_XXX files.
10138 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10139 if (!(flags & OPT_s) && G.global_argv[1]) {
10142 * "bash <script>" (which is never interactive (unless -i?))
10143 * sources $BASH_ENV here (without scanning $PATH).
10144 * If called as sh, does the same but with $ENV.
10145 * Also NB, per POSIX, $ENV should undergo parameter expansion.
10149 debug_printf("running script '%s'\n", G.global_argv[0]);
10150 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
10151 input = hfopen(G.global_argv[0]);
10153 bb_simple_perror_msg_and_die(G.global_argv[0]);
10155 xfunc_error_retval = 1;
10156 install_special_sighandlers();
10157 parse_and_run_file(input);
10158 #if ENABLE_FEATURE_CLEAN_UP
10164 /* Up to here, shell was non-interactive. Now it may become one.
10165 * NB: don't forget to (re)run install_special_sighandlers() as needed.
10168 /* A shell is interactive if the '-i' flag was given,
10169 * or if all of the following conditions are met:
10171 * no arguments remaining or the -s flag given
10172 * standard input is a terminal
10173 * standard output is a terminal
10174 * Refer to Posix.2, the description of the 'sh' utility.
10176 #if ENABLE_HUSH_JOB
10177 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10178 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10179 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10180 if (G_saved_tty_pgrp < 0)
10181 G_saved_tty_pgrp = 0;
10183 /* try to dup stdin to high fd#, >= 255 */
10184 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10185 if (G_interactive_fd < 0) {
10186 /* try to dup to any fd */
10187 G_interactive_fd = dup(STDIN_FILENO);
10188 if (G_interactive_fd < 0) {
10190 G_interactive_fd = 0;
10191 G_saved_tty_pgrp = 0;
10194 // TODO: track & disallow any attempts of user
10195 // to (inadvertently) close/redirect G_interactive_fd
10197 debug_printf("interactive_fd:%d\n", G_interactive_fd);
10198 if (G_interactive_fd) {
10199 close_on_exec_on(G_interactive_fd);
10201 if (G_saved_tty_pgrp) {
10202 /* If we were run as 'hush &', sleep until we are
10203 * in the foreground (tty pgrp == our pgrp).
10204 * If we get started under a job aware app (like bash),
10205 * make sure we are now in charge so we don't fight over
10206 * who gets the foreground */
10208 pid_t shell_pgrp = getpgrp();
10209 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10210 if (G_saved_tty_pgrp == shell_pgrp)
10212 /* send TTIN to ourself (should stop us) */
10213 kill(- shell_pgrp, SIGTTIN);
10217 /* Install more signal handlers */
10218 install_special_sighandlers();
10220 if (G_saved_tty_pgrp) {
10221 /* Set other signals to restore saved_tty_pgrp */
10222 install_fatal_sighandlers();
10223 /* Put ourselves in our own process group
10224 * (bash, too, does this only if ctty is available) */
10225 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10226 /* Grab control of the terminal */
10227 tcsetpgrp(G_interactive_fd, getpid());
10229 enable_restore_tty_pgrp_on_exit();
10231 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10233 const char *hp = get_local_var_value("HISTFILE");
10235 hp = get_local_var_value("HOME");
10237 hp = concat_path_file(hp, ".hush_history");
10242 G.line_input_state->hist_file = hp;
10243 //set_local_var(xasprintf("HISTFILE=%s", ...));
10245 # if ENABLE_FEATURE_SH_HISTFILESIZE
10246 hp = get_local_var_value("HISTFILESIZE");
10247 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10252 install_special_sighandlers();
10254 #elif ENABLE_HUSH_INTERACTIVE
10255 /* No job control compiled in, only prompt/line editing */
10256 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10257 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10258 if (G_interactive_fd < 0) {
10259 /* try to dup to any fd */
10260 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
10261 if (G_interactive_fd < 0)
10263 G_interactive_fd = 0;
10266 if (G_interactive_fd) {
10267 close_on_exec_on(G_interactive_fd);
10269 install_special_sighandlers();
10271 /* We have interactiveness code disabled */
10272 install_special_sighandlers();
10275 * if interactive but not a login shell, sources ~/.bashrc
10276 * (--norc turns this off, --rcfile <file> overrides)
10279 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
10280 /* note: ash and hush share this string */
10281 printf("\n\n%s %s\n"
10282 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10285 "hush - the humble shell"
10289 parse_and_run_file(hfopen(NULL)); /* stdin */
10292 hush_exit(G.last_exitcode);
10299 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
10304 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
10305 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
10307 int argc = string_array_len(argv);
10308 return applet_main_func(argc, argv);
10311 #if ENABLE_HUSH_TEST || BASH_TEST2
10312 static int FAST_FUNC builtin_test(char **argv)
10314 return run_applet_main(argv, test_main);
10317 #if ENABLE_HUSH_ECHO
10318 static int FAST_FUNC builtin_echo(char **argv)
10320 return run_applet_main(argv, echo_main);
10323 #if ENABLE_HUSH_PRINTF
10324 static int FAST_FUNC builtin_printf(char **argv)
10326 return run_applet_main(argv, printf_main);
10330 #if ENABLE_HUSH_HELP
10331 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10333 const struct built_in_command *x;
10336 "Built-in commands:\n"
10337 "------------------\n");
10338 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10340 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10342 return EXIT_SUCCESS;
10346 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
10347 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10349 show_history(G.line_input_state);
10350 return EXIT_SUCCESS;
10354 static char **skip_dash_dash(char **argv)
10357 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10362 static int FAST_FUNC builtin_cd(char **argv)
10364 const char *newdir;
10366 argv = skip_dash_dash(argv);
10368 if (newdir == NULL) {
10369 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
10370 * bash says "bash: cd: HOME not set" and does nothing
10373 const char *home = get_local_var_value("HOME");
10374 newdir = home ? home : "/";
10376 if (chdir(newdir)) {
10377 /* Mimic bash message exactly */
10378 bb_perror_msg("cd: %s", newdir);
10379 return EXIT_FAILURE;
10381 /* Read current dir (get_cwd(1) is inside) and set PWD.
10382 * Note: do not enforce exporting. If PWD was unset or unexported,
10383 * set it again, but do not export. bash does the same.
10385 set_pwd_var(/*flag:*/ 0);
10386 return EXIT_SUCCESS;
10389 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10392 return EXIT_SUCCESS;
10395 static int FAST_FUNC builtin_eval(char **argv)
10397 argv = skip_dash_dash(argv);
10400 return EXIT_SUCCESS;
10402 IF_HUSH_MODE_X(G.x_mode_depth++;)
10403 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
10406 * eval "echo Hi; done" ("done" is syntax error):
10407 * "echo Hi" will not execute too.
10409 parse_and_run_string(argv[0]);
10411 /* "The eval utility shall construct a command by
10412 * concatenating arguments together, separating
10413 * each with a <space> character."
10419 len += strlen(*pp) + 1;
10421 str = p = xmalloc(len);
10424 p = stpcpy(p, *pp);
10430 parse_and_run_string(str);
10433 IF_HUSH_MODE_X(G.x_mode_depth--;)
10434 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
10435 return G.last_exitcode;
10438 static int FAST_FUNC builtin_exec(char **argv)
10440 argv = skip_dash_dash(argv);
10441 if (argv[0] == NULL)
10442 return EXIT_SUCCESS; /* bash does this */
10444 /* Careful: we can end up here after [v]fork. Do not restore
10445 * tty pgrp then, only top-level shell process does that */
10446 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10447 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10449 /* Saved-redirect fds, script fds and G_interactive_fd are still
10450 * open here. However, they are all CLOEXEC, and execv below
10451 * closes them. Try interactive "exec ls -l /proc/self/fd",
10452 * it should show no extra open fds in the "ls" process.
10453 * If we'd try to run builtins/NOEXECs, this would need improving.
10455 //close_saved_fds_and_FILE_fds();
10457 /* TODO: if exec fails, bash does NOT exit! We do.
10458 * We'll need to undo trap cleanup (it's inside execvp_or_die)
10459 * and tcsetpgrp, and this is inherently racy.
10461 execvp_or_die(argv);
10464 static int FAST_FUNC builtin_exit(char **argv)
10466 debug_printf_exec("%s()\n", __func__);
10468 /* interactive bash:
10469 * # trap "echo EEE" EXIT
10472 * There are stopped jobs.
10473 * (if there are _stopped_ jobs, running ones don't count)
10476 * EEE (then bash exits)
10478 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
10481 /* note: EXIT trap is run by hush_exit */
10482 argv = skip_dash_dash(argv);
10483 if (argv[0] == NULL)
10484 hush_exit(G.last_exitcode);
10485 /* mimic bash: exit 123abc == exit 255 + error msg */
10486 xfunc_error_retval = 255;
10487 /* bash: exit -2 == exit 254, no error msg */
10488 hush_exit(xatoi(argv[0]) & 0xff);
10491 #if ENABLE_HUSH_TYPE
10492 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10493 static int FAST_FUNC builtin_type(char **argv)
10495 int ret = EXIT_SUCCESS;
10501 if (0) {} /* make conditional compile easier below */
10502 /*else if (find_alias(*argv))
10503 type = "an alias";*/
10504 #if ENABLE_HUSH_FUNCTIONS
10505 else if (find_function(*argv))
10506 type = "a function";
10508 else if (find_builtin(*argv))
10509 type = "a shell builtin";
10510 else if ((path = find_in_path(*argv)) != NULL)
10513 bb_error_msg("type: %s: not found", *argv);
10514 ret = EXIT_FAILURE;
10518 printf("%s is %s\n", *argv, type);
10526 #if ENABLE_HUSH_READ
10527 /* Interruptibility of read builtin in bash
10528 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10530 * Empty trap makes read ignore corresponding signal, for any signal.
10533 * - terminates non-interactive shell;
10534 * - interrupts read in interactive shell;
10535 * if it has non-empty trap:
10536 * - executes trap and returns to command prompt in interactive shell;
10537 * - executes trap and returns to read in non-interactive shell;
10539 * - is ignored (does not interrupt) read in interactive shell;
10540 * - terminates non-interactive shell;
10541 * if it has non-empty trap:
10542 * - executes trap and returns to read;
10544 * - terminates shell (regardless of interactivity);
10545 * if it has non-empty trap:
10546 * - executes trap and returns to read;
10547 * SIGCHLD from children:
10548 * - does not interrupt read regardless of interactivity:
10549 * try: sleep 1 & read x; echo $x
10551 static int FAST_FUNC builtin_read(char **argv)
10554 struct builtin_read_params params;
10556 memset(¶ms, 0, sizeof(params));
10558 /* "!": do not abort on errors.
10559 * Option string must start with "sr" to match BUILTIN_READ_xxx
10561 params.read_flags = getopt32(argv,
10563 "!srn:p:t:u:d:", ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u, ¶ms.opt_d
10565 "!srn:p:t:u:", ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u
10568 if ((uint32_t)params.read_flags == (uint32_t)-1)
10569 return EXIT_FAILURE;
10571 params.argv = argv;
10572 params.setvar = set_local_var_from_halves;
10573 params.ifs = get_local_var_value("IFS"); /* can be NULL */
10576 r = shell_builtin_read(¶ms);
10578 if ((uintptr_t)r == 1 && errno == EINTR) {
10579 unsigned sig = check_and_run_traps();
10584 if ((uintptr_t)r > 1) {
10585 bb_error_msg("%s", r);
10586 r = (char*)(uintptr_t)1;
10589 return (uintptr_t)r;
10593 #if ENABLE_HUSH_UMASK
10594 static int FAST_FUNC builtin_umask(char **argv)
10601 argv = skip_dash_dash(argv);
10603 mode_t old_mask = mask;
10605 /* numeric umasks are taken as-is */
10606 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10607 if (!isdigit(argv[0][0]))
10609 mask = bb_parse_mode(argv[0], mask);
10610 if (!isdigit(argv[0][0]))
10612 if ((unsigned)mask > 0777) {
10615 * bash: umask: 'q': invalid symbolic mode operator
10616 * bash: umask: 999: octal number out of range
10618 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10623 printf("%04o\n", (unsigned) mask);
10624 /* fall through and restore mask which we set to 0 */
10628 return !rc; /* rc != 0 - success */
10632 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
10633 static void print_escaped(const char *s)
10638 const char *p = strchrnul(s, '\'');
10639 /* print 'xxxx', possibly just '' */
10640 printf("'%.*s'", (int)(p - s), s);
10645 /* s points to '; print "'''...'''" */
10647 do putchar('\''); while (*++s == '\'');
10653 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
10654 static int helper_export_local(char **argv, unsigned flags)
10657 char *name = *argv;
10658 char *name_end = strchrnul(name, '=');
10660 /* So far we do not check that name is valid (TODO?) */
10662 if (*name_end == '\0') {
10663 struct variable *var, **vpp;
10665 vpp = get_ptr_to_local_var(name, name_end - name);
10666 var = vpp ? *vpp : NULL;
10668 if (flags & SETFLAG_UNEXPORT) {
10669 /* export -n NAME (without =VALUE) */
10671 var->flg_export = 0;
10672 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10674 } /* else: export -n NOT_EXISTING_VAR: no-op */
10677 if (flags & SETFLAG_EXPORT) {
10678 /* export NAME (without =VALUE) */
10680 var->flg_export = 1;
10681 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10682 putenv(var->varstr);
10686 if (flags & SETFLAG_MAKE_RO) {
10687 /* readonly NAME (without =VALUE) */
10689 var->flg_read_only = 1;
10693 # if ENABLE_HUSH_LOCAL
10694 /* Is this "local" bltin? */
10695 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
10696 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10697 if (var && var->var_nest_level == lvl) {
10698 /* "local x=abc; ...; local x" - ignore second local decl */
10703 /* Exporting non-existing variable.
10704 * bash does not put it in environment,
10705 * but remembers that it is exported,
10706 * and does put it in env when it is set later.
10707 * We just set it to "" and export.
10709 /* Or, it's "local NAME" (without =VALUE).
10710 * bash sets the value to "".
10712 /* Or, it's "readonly NAME" (without =VALUE).
10713 * bash remembers NAME and disallows its creation
10716 name = xasprintf("%s=", name);
10718 /* (Un)exporting/making local NAME=VALUE */
10719 name = xstrdup(name);
10721 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
10722 if (set_local_var(name, flags))
10723 return EXIT_FAILURE;
10725 return EXIT_SUCCESS;
10729 #if ENABLE_HUSH_EXPORT
10730 static int FAST_FUNC builtin_export(char **argv)
10732 unsigned opt_unexport;
10734 #if ENABLE_HUSH_EXPORT_N
10735 /* "!": do not abort on errors */
10736 opt_unexport = getopt32(argv, "!n");
10737 if (opt_unexport == (uint32_t)-1)
10738 return EXIT_FAILURE;
10745 if (argv[0] == NULL) {
10746 char **e = environ;
10752 /* ash emits: export VAR='VAL'
10753 * bash: declare -x VAR="VAL"
10754 * we follow ash example */
10755 const char *s = *e++;
10756 const char *p = strchr(s, '=');
10758 if (!p) /* wtf? take next variable */
10761 printf("export %.*s", (int)(p - s) + 1, s);
10762 print_escaped(p + 1);
10766 /*fflush_all(); - done after each builtin anyway */
10768 return EXIT_SUCCESS;
10771 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
10775 #if ENABLE_HUSH_LOCAL
10776 static int FAST_FUNC builtin_local(char **argv)
10778 if (G.func_nest_level == 0) {
10779 bb_error_msg("%s: not in a function", argv[0]);
10780 return EXIT_FAILURE; /* bash compat */
10783 /* Since all builtins run in a nested variable level,
10784 * need to use level - 1 here. Or else the variable will be removed at once
10785 * after builtin returns.
10787 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
10791 #if ENABLE_HUSH_READONLY
10792 static int FAST_FUNC builtin_readonly(char **argv)
10795 if (*argv == NULL) {
10796 /* bash: readonly [-p]: list all readonly VARs
10797 * (-p has no effect in bash)
10799 struct variable *e;
10800 for (e = G.top_var; e; e = e->next) {
10801 if (e->flg_read_only) {
10802 //TODO: quote value: readonly VAR='VAL'
10803 printf("readonly %s\n", e->varstr);
10806 return EXIT_SUCCESS;
10808 return helper_export_local(argv, SETFLAG_MAKE_RO);
10812 #if ENABLE_HUSH_UNSET
10813 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10814 static int FAST_FUNC builtin_unset(char **argv)
10819 /* "!": do not abort on errors */
10820 /* "+": stop at 1st non-option */
10821 opts = getopt32(argv, "!+vf");
10822 if (opts == (unsigned)-1)
10823 return EXIT_FAILURE;
10825 bb_error_msg("unset: -v and -f are exclusive");
10826 return EXIT_FAILURE;
10830 ret = EXIT_SUCCESS;
10832 if (!(opts & 2)) { /* not -f */
10833 if (unset_local_var(*argv)) {
10834 /* unset <nonexistent_var> doesn't fail.
10835 * Error is when one tries to unset RO var.
10836 * Message was printed by unset_local_var. */
10837 ret = EXIT_FAILURE;
10840 # if ENABLE_HUSH_FUNCTIONS
10851 #if ENABLE_HUSH_SET
10852 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10853 * built-in 'set' handler
10855 * set [-abCefhmnuvx] [-o option] [argument...]
10856 * set [+abCefhmnuvx] [+o option] [argument...]
10857 * set -- [argument...]
10860 * Implementations shall support the options in both their hyphen and
10861 * plus-sign forms. These options can also be specified as options to sh.
10863 * Write out all variables and their values: set
10864 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10865 * Turn on the -x and -v options: set -xv
10866 * Unset all positional parameters: set --
10867 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10868 * Set the positional parameters to the expansion of x, even if x expands
10869 * with a leading '-' or '+': set -- $x
10871 * So far, we only support "set -- [argument...]" and some of the short names.
10873 static int FAST_FUNC builtin_set(char **argv)
10876 char **pp, **g_argv;
10877 char *arg = *++argv;
10880 struct variable *e;
10881 for (e = G.top_var; e; e = e->next)
10883 return EXIT_SUCCESS;
10887 if (strcmp(arg, "--") == 0) {
10891 if (arg[0] != '+' && arg[0] != '-')
10893 for (n = 1; arg[n]; ++n) {
10894 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10896 if (arg[n] == 'o' && argv[1])
10899 } while ((arg = *++argv) != NULL);
10900 /* Now argv[0] is 1st argument */
10903 return EXIT_SUCCESS;
10906 /* NB: G.global_argv[0] ($0) is never freed/changed */
10907 g_argv = G.global_argv;
10908 if (G.global_args_malloced) {
10914 G.global_args_malloced = 1;
10915 pp = xzalloc(sizeof(pp[0]) * 2);
10916 pp[0] = g_argv[0]; /* retain $0 */
10919 /* This realloc's G.global_argv */
10920 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10922 G.global_argc = 1 + string_array_len(pp + 1);
10924 return EXIT_SUCCESS;
10926 /* Nothing known, so abort */
10928 bb_error_msg("%s: %s: invalid option", "set", arg);
10929 return EXIT_FAILURE;
10933 static int FAST_FUNC builtin_shift(char **argv)
10936 argv = skip_dash_dash(argv);
10938 n = bb_strtou(argv[0], NULL, 10);
10939 if (errno || n < 0) {
10940 /* shared string with ash.c */
10941 bb_error_msg("Illegal number: %s", argv[0]);
10943 * ash aborts in this case.
10944 * bash prints error message and set $? to 1.
10945 * Interestingly, for "shift 99999" bash does not
10946 * print error message, but does set $? to 1
10947 * (and does no shifting at all).
10951 if (n >= 0 && n < G.global_argc) {
10952 if (G_global_args_malloced) {
10955 free(G.global_argv[m++]);
10957 G.global_argc -= n;
10958 memmove(&G.global_argv[1], &G.global_argv[n+1],
10959 G.global_argc * sizeof(G.global_argv[0]));
10960 return EXIT_SUCCESS;
10962 return EXIT_FAILURE;
10965 #if ENABLE_HUSH_GETOPTS
10966 static int FAST_FUNC builtin_getopts(char **argv)
10968 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10971 If a required argument is not found, and getopts is not silent,
10972 a question mark (?) is placed in VAR, OPTARG is unset, and a
10973 diagnostic message is printed. If getopts is silent, then a
10974 colon (:) is placed in VAR and OPTARG is set to the option
10977 Test that VAR is a valid variable name?
10979 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10982 const char *cp, *optstring, *var;
10983 int c, n, exitcode, my_opterr;
10986 optstring = *++argv;
10987 if (!optstring || !(var = *++argv)) {
10988 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10989 return EXIT_FAILURE;
10993 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10995 argv = G.global_argv;
10999 if (optstring[0] != ':') {
11000 cp = get_local_var_value("OPTERR");
11001 /* 0 if "OPTERR=0", 1 otherwise */
11002 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
11005 /* getopts stops on first non-option. Add "+" to force that */
11006 /*if (optstring[0] != '+')*/ {
11007 char *s = alloca(strlen(optstring) + 2);
11008 sprintf(s, "+%s", optstring);
11012 /* Naively, now we should just
11013 * cp = get_local_var_value("OPTIND");
11014 * optind = cp ? atoi(cp) : 0;
11016 * opterr = my_opterr;
11017 * c = getopt(string_array_len(argv), argv, optstring);
11018 * and be done? Not so fast...
11019 * Unlike normal getopt() usage in C programs, here
11020 * each successive call will (usually) have the same argv[] CONTENTS,
11021 * but not the ADDRESSES. Worse yet, it's possible that between
11022 * invocations of "getopts", there will be calls to shell builtins
11023 * which use getopt() internally. Example:
11024 * while getopts "abc" RES -a -bc -abc de; do
11027 * This would not work correctly: getopt() call inside "unset"
11028 * modifies internal libc state which is tracking position in
11029 * multi-option strings ("-abc"). At best, it can skip options
11030 * or return the same option infinitely. With glibc implementation
11031 * of getopt(), it would use outright invalid pointers and return
11032 * garbage even _without_ "unset" mangling internal state.
11034 * We resort to resetting getopt() state and calling it N times,
11035 * until we get Nth result (or failure).
11036 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11040 n = string_array_len(argv);
11043 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11044 c = getopt(n, argv, optstring);
11048 } while (count <= G.getopt_count);
11050 /* Set OPTIND. Prevent resetting of the magic counter! */
11051 set_local_var_from_halves("OPTIND", utoa(optind));
11052 G.getopt_count = count; /* "next time, give me N+1'th result" */
11053 GETOPT_RESET(); /* just in case */
11056 /* Always set or unset, never left as-is, even on exit/error:
11057 * "If no option was found, or if the option that was found
11058 * does not have an option-argument, OPTARG shall be unset."
11062 /* If ":optstring" and unknown option is seen,
11063 * it is stored to OPTARG.
11065 if (optstring[1] == ':') {
11071 set_local_var_from_halves("OPTARG", cp);
11073 unset_local_var("OPTARG");
11075 /* Convert -1 to "?" */
11076 exitcode = EXIT_SUCCESS;
11077 if (c < 0) { /* -1: end of options */
11078 exitcode = EXIT_FAILURE;
11084 set_local_var_from_halves(var, cbuf);
11090 static int FAST_FUNC builtin_source(char **argv)
11092 char *arg_path, *filename;
11095 char *args_need_save;
11096 #if ENABLE_HUSH_FUNCTIONS
11100 argv = skip_dash_dash(argv);
11101 filename = argv[0];
11103 /* bash says: "bash: .: filename argument required" */
11104 return 2; /* bash compat */
11107 if (!strchr(filename, '/')) {
11108 arg_path = find_in_path(filename);
11110 filename = arg_path;
11111 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
11113 bb_simple_perror_msg(filename);
11114 return EXIT_FAILURE;
11117 input = hfopen(filename);
11120 bb_perror_msg("%s", filename);
11121 /* POSIX: non-interactive shell should abort here,
11122 * not merely fail. So far no one complained :)
11124 return EXIT_FAILURE;
11127 #if ENABLE_HUSH_FUNCTIONS
11128 sv_flg = G_flag_return_in_progress;
11129 /* "we are inside sourced file, ok to use return" */
11130 G_flag_return_in_progress = -1;
11132 args_need_save = argv[1]; /* used as a boolean variable */
11133 if (args_need_save)
11134 save_and_replace_G_args(&sv, argv);
11136 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11137 G.last_exitcode = 0;
11138 parse_and_run_file(input);
11141 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11142 restore_G_args(&sv, argv);
11143 #if ENABLE_HUSH_FUNCTIONS
11144 G_flag_return_in_progress = sv_flg;
11147 return G.last_exitcode;
11150 #if ENABLE_HUSH_TRAP
11151 static int FAST_FUNC builtin_trap(char **argv)
11157 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
11162 /* No args: print all trapped */
11163 for (i = 0; i < NSIG; ++i) {
11165 printf("trap -- ");
11166 print_escaped(G_traps[i]);
11167 /* note: bash adds "SIG", but only if invoked
11168 * as "bash". If called as "sh", or if set -o posix,
11169 * then it prints short signal names.
11170 * We are printing short names: */
11171 printf(" %s\n", get_signame(i));
11174 /*fflush_all(); - done after each builtin anyway */
11175 return EXIT_SUCCESS;
11179 /* If first arg is a number: reset all specified signals */
11180 sig = bb_strtou(*argv, NULL, 10);
11184 ret = EXIT_SUCCESS;
11186 sighandler_t handler;
11188 sig = get_signum(*argv++);
11190 ret = EXIT_FAILURE;
11191 /* Mimic bash message exactly */
11192 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
11196 free(G_traps[sig]);
11197 G_traps[sig] = xstrdup(new_cmd);
11199 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
11200 get_signame(sig), sig, G_traps[sig]);
11202 /* There is no signal for 0 (EXIT) */
11207 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11209 /* We are removing trap handler */
11210 handler = pick_sighandler(sig);
11211 install_sighandler(sig, handler);
11216 if (!argv[1]) { /* no second arg */
11217 bb_error_msg("trap: invalid arguments");
11218 return EXIT_FAILURE;
11221 /* First arg is "-": reset all specified to default */
11222 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11223 /* Everything else: set arg as signal handler
11224 * (includes "" case, which ignores signal) */
11225 if (argv[0][0] == '-') {
11226 if (argv[0][1] == '\0') { /* "-" */
11227 /* new_cmd remains NULL: "reset these sigs" */
11230 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11233 /* else: "-something", no special meaning */
11238 goto process_sig_list;
11242 #if ENABLE_HUSH_JOB
11243 static struct pipe *parse_jobspec(const char *str)
11248 if (sscanf(str, "%%%u", &jobnum) != 1) {
11250 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11252 bb_error_msg("bad argument '%s'", str);
11255 /* It is "%%", "%+" or "%" - current job */
11256 jobnum = G.last_jobid;
11258 bb_error_msg("no current job");
11262 for (pi = G.job_list; pi; pi = pi->next) {
11263 if (pi->jobid == jobnum) {
11267 bb_error_msg("%u: no such job", jobnum);
11271 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11274 const char *status_string;
11276 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11277 for (job = G.job_list; job; job = job->next) {
11278 if (job->alive_cmds == job->stopped_cmds)
11279 status_string = "Stopped";
11281 status_string = "Running";
11283 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11286 clean_up_last_dead_job();
11288 return EXIT_SUCCESS;
11291 /* built-in 'fg' and 'bg' handler */
11292 static int FAST_FUNC builtin_fg_bg(char **argv)
11297 if (!G_interactive_fd)
11298 return EXIT_FAILURE;
11300 /* If they gave us no args, assume they want the last backgrounded task */
11302 for (pi = G.job_list; pi; pi = pi->next) {
11303 if (pi->jobid == G.last_jobid) {
11307 bb_error_msg("%s: no current job", argv[0]);
11308 return EXIT_FAILURE;
11311 pi = parse_jobspec(argv[1]);
11313 return EXIT_FAILURE;
11315 /* TODO: bash prints a string representation
11316 * of job being foregrounded (like "sleep 1 | cat") */
11317 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
11318 /* Put the job into the foreground. */
11319 tcsetpgrp(G_interactive_fd, pi->pgrp);
11322 /* Restart the processes in the job */
11323 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11324 for (i = 0; i < pi->num_cmds; i++) {
11325 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
11327 pi->stopped_cmds = 0;
11329 i = kill(- pi->pgrp, SIGCONT);
11331 if (errno == ESRCH) {
11332 delete_finished_job(pi);
11333 return EXIT_SUCCESS;
11335 bb_perror_msg("kill (SIGCONT)");
11338 if (argv[0][0] == 'f') {
11339 remove_job_from_table(pi); /* FG job shouldn't be in job table */
11340 return checkjobs_and_fg_shell(pi);
11342 return EXIT_SUCCESS;
11346 #if ENABLE_HUSH_KILL
11347 static int FAST_FUNC builtin_kill(char **argv)
11351 # if ENABLE_HUSH_JOB
11352 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11360 if (argv[i][0] != '%')
11363 * "kill %N" - job kill
11364 * Converting to pgrp / pid kill
11366 pi = parse_jobspec(argv[i]);
11368 /* Eat bad jobspec */
11372 argv[j - 1] = argv[j];
11379 * In jobs started under job control, we signal
11380 * entire process group by kill -PGRP_ID.
11381 * This happens, f.e., in interactive shell.
11383 * Otherwise, we signal each child via
11384 * kill PID1 PID2 PID3.
11386 * sh -c 'sleep 1|sleep 1 & kill %1'
11387 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11388 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11390 n = G_interactive_fd ? 1 : pi->num_cmds;
11391 dst = alloca(n * sizeof(int)*4);
11393 if (G_interactive_fd)
11394 dst += sprintf(dst, " -%u", (int)pi->pgrp);
11395 else for (j = 0; j < n; j++) {
11396 struct command *cmd = &pi->cmds[j];
11397 /* Skip exited members of the job */
11401 * kill_main has matching code to expect
11402 * leading space. Needed to not confuse
11403 * negative pids with "kill -SIGNAL_NO" syntax
11405 dst += sprintf(dst, " %u", (int)cmd->pid);
11408 } while (argv[++i]);
11412 if (argv[1] || ret == 0) {
11413 ret = run_applet_main(argv, kill_main);
11415 /* else: ret = 1, "kill %bad_jobspec" case */
11420 #if ENABLE_HUSH_WAIT
11421 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
11422 #if !ENABLE_HUSH_JOB
11423 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11425 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
11432 if (!sigisemptyset(&G.pending_set))
11435 /* waitpid is not interruptible by SA_RESTARTed
11436 * signals which we use. Thus, this ugly dance:
11439 /* Make sure possible SIGCHLD is stored in kernel's
11440 * pending signal mask before we call waitpid.
11441 * Or else we may race with SIGCHLD, lose it,
11442 * and get stuck in sigsuspend...
11444 sigfillset(&oldset); /* block all signals, remember old set */
11445 sigprocmask2(SIG_SETMASK, &oldset);
11447 if (!sigisemptyset(&G.pending_set)) {
11448 /* Crap! we raced with some signal! */
11452 /*errno = 0; - checkjobs does this */
11453 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
11454 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
11455 debug_printf_exec("checkjobs:%d\n", ret);
11456 #if ENABLE_HUSH_JOB
11457 if (waitfor_pipe) {
11458 int rcode = job_exited_or_stopped(waitfor_pipe);
11459 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11462 sigprocmask(SIG_SETMASK, &oldset, NULL);
11467 /* if ECHILD, there are no children (ret is -1 or 0) */
11468 /* if ret == 0, no children changed state */
11469 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
11470 if (errno == ECHILD || ret) {
11472 if (ret < 0) /* if ECHILD, may need to fix "ret" */
11474 sigprocmask(SIG_SETMASK, &oldset, NULL);
11477 /* Wait for SIGCHLD or any other signal */
11478 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11479 /* Note: sigsuspend invokes signal handler */
11480 sigsuspend(&oldset);
11482 sigprocmask(SIG_SETMASK, &oldset, NULL);
11484 /* So, did we get a signal? */
11485 sig = check_and_run_traps();
11486 if (sig /*&& sig != SIGCHLD - always true */) {
11487 /* Do this for any (non-ignored) signal, not only for ^C */
11491 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11496 static int FAST_FUNC builtin_wait(char **argv)
11501 argv = skip_dash_dash(argv);
11502 if (argv[0] == NULL) {
11503 /* Don't care about wait results */
11504 /* Note 1: must wait until there are no more children */
11505 /* Note 2: must be interruptible */
11507 * $ sleep 3 & sleep 6 & wait
11508 * [1] 30934 sleep 3
11509 * [2] 30935 sleep 6
11512 * $ sleep 3 & sleep 6 & wait
11513 * [1] 30936 sleep 3
11514 * [2] 30937 sleep 6
11516 * ^C <-- after ~4 sec from keyboard
11519 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
11523 pid_t pid = bb_strtou(*argv, NULL, 10);
11524 if (errno || pid <= 0) {
11525 #if ENABLE_HUSH_JOB
11526 if (argv[0][0] == '%') {
11527 struct pipe *wait_pipe;
11528 ret = 127; /* bash compat for bad jobspecs */
11529 wait_pipe = parse_jobspec(*argv);
11531 ret = job_exited_or_stopped(wait_pipe);
11533 ret = wait_for_child_or_signal(wait_pipe, 0);
11535 /* waiting on "last dead job" removes it */
11536 clean_up_last_dead_job();
11539 /* else: parse_jobspec() already emitted error msg */
11543 /* mimic bash message */
11544 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
11545 ret = EXIT_FAILURE;
11546 continue; /* bash checks all argv[] */
11549 /* Do we have such child? */
11550 ret = waitpid(pid, &status, WNOHANG);
11554 if (errno == ECHILD) {
11555 if (pid == G.last_bg_pid) {
11556 /* "wait $!" but last bg task has already exited. Try:
11557 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11558 * In bash it prints exitcode 0, then 3.
11559 * In dash, it is 127.
11561 ret = G.last_bg_pid_exitcode;
11563 /* Example: "wait 1". mimic bash message */
11564 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
11568 bb_perror_msg("wait %s", *argv);
11570 continue; /* bash checks all argv[] */
11573 /* Yes, and it still runs */
11574 ret = wait_for_child_or_signal(NULL, pid);
11576 /* Yes, and it just exited */
11577 process_wait_result(NULL, pid, status);
11578 ret = WEXITSTATUS(status);
11579 if (WIFSIGNALED(status))
11580 ret = 128 + WTERMSIG(status);
11588 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11589 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11592 def = bb_strtou(argv[1], NULL, 10);
11593 if (errno || def < def_min || argv[2]) {
11594 bb_error_msg("%s: bad arguments", argv[0]);
11602 #if ENABLE_HUSH_LOOPS
11603 static int FAST_FUNC builtin_break(char **argv)
11606 if (G.depth_of_loop == 0) {
11607 bb_error_msg("%s: only meaningful in a loop", argv[0]);
11608 /* if we came from builtin_continue(), need to undo "= 1" */
11609 G.flag_break_continue = 0;
11610 return EXIT_SUCCESS; /* bash compat */
11612 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
11614 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11615 if (depth == UINT_MAX)
11616 G.flag_break_continue = BC_BREAK;
11617 if (G.depth_of_loop < depth)
11618 G.depth_break_continue = G.depth_of_loop;
11620 return EXIT_SUCCESS;
11623 static int FAST_FUNC builtin_continue(char **argv)
11625 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11626 return builtin_break(argv);
11630 #if ENABLE_HUSH_FUNCTIONS
11631 static int FAST_FUNC builtin_return(char **argv)
11635 if (G_flag_return_in_progress != -1) {
11636 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11637 return EXIT_FAILURE; /* bash compat */
11640 G_flag_return_in_progress = 1;
11643 * out of range: wraps around at 256, does not error out
11644 * non-numeric param:
11645 * f() { false; return qwe; }; f; echo $?
11646 * bash: return: qwe: numeric argument required <== we do this
11647 * 255 <== we also do this
11649 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11654 #if ENABLE_HUSH_TIMES
11655 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11657 static const uint8_t times_tbl[] ALIGN1 = {
11658 ' ', offsetof(struct tms, tms_utime),
11659 '\n', offsetof(struct tms, tms_stime),
11660 ' ', offsetof(struct tms, tms_cutime),
11661 '\n', offsetof(struct tms, tms_cstime),
11668 clk_tck = bb_clk_tck();
11673 unsigned sec, frac;
11675 t = *(clock_t *)(((char *) &buf) + p[1]);
11677 frac = t % clk_tck;
11678 printf("%um%u.%03us%c",
11679 sec / 60, sec % 60,
11680 (frac * 1000) / clk_tck,
11685 return EXIT_SUCCESS;
11689 #if ENABLE_HUSH_MEMLEAK
11690 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11695 # ifdef M_TRIM_THRESHOLD
11696 /* Optional. Reduces probability of false positives */
11699 /* Crude attempt to find where "free memory" starts,
11700 * sans fragmentation. */
11702 l = (unsigned long)p;
11705 if (l < (unsigned long)p) l = (unsigned long)p;
11711 struct mallinfo mi = mallinfo();
11712 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11713 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11717 if (!G.memleak_value)
11718 G.memleak_value = l;
11720 l -= G.memleak_value;
11727 /* Exitcode is "how many kilobytes we leaked since 1st call" */