1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * make complex ${var%...} constructs support optional
45 * make here documents optional
46 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
50 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
53 * command BLTIN: disables special-ness (e.g. errors do not abort)
54 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
57 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
62 * redirection of stdout+stderr: &> and >&
63 * reserved words: function select
64 * advanced test: [[ ]]
65 * process substitution: <(list) and >(list)
68 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
72 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
74 * $[EXPR]: synonym for $((EXPR))
75 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
79 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
86 * [[ /bin/n* ]]; echo 0:$?
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
93 * add =~ regex match operator: STR =~ REGEX
96 //config: bool "hush (64 kb)"
99 //config: hush is a small shell. It handles the normal flow control
100 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101 //config: case/esac. Redirections, here documents, $((arithmetic))
102 //config: and functions are supported.
104 //config: It will compile and work on no-mmu systems.
106 //config: It does not handle select, aliases, tilde expansion,
107 //config: &>file and >&file redirection of stdout+stderr.
109 //config:config HUSH_BASH_COMPAT
110 //config: bool "bash-compatible extensions"
112 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
114 //config:config HUSH_BRACE_EXPANSION
115 //config: bool "Brace expansion"
117 //config: depends on HUSH_BASH_COMPAT
119 //config: Enable {abc,def} extension.
121 //config:config HUSH_LINENO_VAR
122 //config: bool "$LINENO variable"
124 //config: depends on HUSH_BASH_COMPAT
126 //config:config HUSH_BASH_SOURCE_CURDIR
127 //config: bool "'source' and '.' builtins search current directory after $PATH"
128 //config: default n # do not encourage non-standard behavior
129 //config: depends on HUSH_BASH_COMPAT
131 //config: This is not compliant with standards. Avoid if possible.
133 //config:config HUSH_INTERACTIVE
134 //config: bool "Interactive mode"
136 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
138 //config: Enable interactive mode (prompt and command editing).
139 //config: Without this, hush simply reads and executes commands
140 //config: from stdin just like a shell script from a file.
141 //config: No prompt, no PS1/PS2 magic shell variables.
143 //config:config HUSH_SAVEHISTORY
144 //config: bool "Save command history to .hush_history"
146 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
148 //config:config HUSH_JOB
149 //config: bool "Job control"
151 //config: depends on HUSH_INTERACTIVE
153 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154 //config: command (not entire shell), fg/bg builtins work. Without this option,
155 //config: "cmd &" still works by simply spawning a process and immediately
156 //config: prompting for next command (or executing next command in a script),
157 //config: but no separate process group is formed.
159 //config:config HUSH_TICK
160 //config: bool "Support process substitution"
162 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
164 //config: Enable `command` and $(command).
166 //config:config HUSH_IF
167 //config: bool "Support if/then/elif/else/fi"
169 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
171 //config:config HUSH_LOOPS
172 //config: bool "Support for, while and until loops"
174 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
176 //config:config HUSH_CASE
177 //config: bool "Support case ... esac statement"
179 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
181 //config: Enable case ... esac statement. +400 bytes.
183 //config:config HUSH_FUNCTIONS
184 //config: bool "Support funcname() { commands; } syntax"
186 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
188 //config: Enable support for shell functions. +800 bytes.
190 //config:config HUSH_LOCAL
191 //config: bool "local builtin"
193 //config: depends on HUSH_FUNCTIONS
195 //config: Enable support for local variables in functions.
197 //config:config HUSH_RANDOM_SUPPORT
198 //config: bool "Pseudorandom generator and $RANDOM variable"
200 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
202 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
205 //config:config HUSH_MODE_X
206 //config: bool "Support 'hush -x' option and 'set -x' command"
208 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
210 //config: This instructs hush to print commands before execution.
211 //config: Adds ~300 bytes.
213 //config:config HUSH_ECHO
214 //config: bool "echo builtin"
216 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
218 //config:config HUSH_PRINTF
219 //config: bool "printf builtin"
221 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
223 //config:config HUSH_TEST
224 //config: bool "test builtin"
226 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
228 //config:config HUSH_HELP
229 //config: bool "help builtin"
231 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
233 //config:config HUSH_EXPORT
234 //config: bool "export builtin"
236 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
238 //config:config HUSH_EXPORT_N
239 //config: bool "Support 'export -n' option"
241 //config: depends on HUSH_EXPORT
243 //config: export -n unexports variables. It is a bash extension.
245 //config:config HUSH_READONLY
246 //config: bool "readonly builtin"
248 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
250 //config: Enable support for read-only variables.
252 //config:config HUSH_KILL
253 //config: bool "kill builtin (supports kill %jobspec)"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_WAIT
258 //config: bool "wait builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_COMMAND
263 //config: bool "command builtin"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
267 //config:config HUSH_TRAP
268 //config: bool "trap builtin"
270 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272 //config:config HUSH_TYPE
273 //config: bool "type builtin"
275 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
277 //config:config HUSH_TIMES
278 //config: bool "times builtin"
280 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
282 //config:config HUSH_READ
283 //config: bool "read builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config:config HUSH_SET
288 //config: bool "set builtin"
290 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
292 //config:config HUSH_UNSET
293 //config: bool "unset builtin"
295 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
297 //config:config HUSH_ULIMIT
298 //config: bool "ulimit builtin"
300 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
302 //config:config HUSH_UMASK
303 //config: bool "umask builtin"
305 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
307 //config:config HUSH_GETOPTS
308 //config: bool "getopts builtin"
310 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
312 //config:config HUSH_MEMLEAK
313 //config: bool "memleak builtin (debugging)"
315 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
317 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
318 // APPLET_ODDNAME:name main location suid_type help
319 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
320 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
322 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
323 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
325 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
327 /* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
332 //usage:#define hush_trivial_usage
333 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
334 //usage:#define hush_full_usage "\n\n"
335 //usage: "Unix shell interpreter"
337 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
340 # include <malloc.h> /* for malloc_trim */
343 /* #include <dmalloc.h> */
345 # include <fnmatch.h>
347 #include <sys/times.h>
348 #include <sys/utsname.h> /* for setting $HOSTNAME */
350 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
352 #include "shell_common.h"
355 #if ENABLE_HUSH_RANDOM_SUPPORT
358 # define CLEAR_RANDOM_T(rnd) ((void)0)
363 #ifndef F_DUPFD_CLOEXEC
364 # define F_DUPFD_CLOEXEC F_DUPFD
367 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
371 /* So far, all bash compat is controlled by one config option */
372 /* Separate defines document which part of code implements what */
373 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
374 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
375 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
376 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
377 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
378 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
382 #define LEAK_HUNTING 0
383 #define BUILD_AS_NOMMU 0
384 /* Enable/disable sanity checks. Ok to enable in production,
385 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
386 * Keeping 1 for now even in released versions.
389 /* Slightly bigger (+200 bytes), but faster hush.
390 * So far it only enables a trick with counting SIGCHLDs and forks,
391 * which allows us to do fewer waitpid's.
392 * (we can detect a case where neither forks were done nor SIGCHLDs happened
393 * and therefore waitpid will return the same result as last time)
395 #define ENABLE_HUSH_FAST 0
396 /* TODO: implement simplified code for users which do not need ${var%...} ops
397 * So far ${var%...} ops are always enabled:
399 #define ENABLE_HUSH_DOLLAR_OPS 1
404 # undef USE_FOR_NOMMU
407 # define USE_FOR_NOMMU(...) __VA_ARGS__
408 # define USE_FOR_MMU(...)
411 #include "NUM_APPLETS.h"
413 /* STANDALONE does not make sense, and won't compile */
414 # undef CONFIG_FEATURE_SH_STANDALONE
415 # undef ENABLE_FEATURE_SH_STANDALONE
416 # undef IF_FEATURE_SH_STANDALONE
417 # undef IF_NOT_FEATURE_SH_STANDALONE
418 # define ENABLE_FEATURE_SH_STANDALONE 0
419 # define IF_FEATURE_SH_STANDALONE(...)
420 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
423 #if !ENABLE_HUSH_INTERACTIVE
424 # undef ENABLE_FEATURE_EDITING
425 # define ENABLE_FEATURE_EDITING 0
426 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
427 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
428 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
429 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
432 /* Do we support ANY keywords? */
433 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
434 # define HAS_KEYWORDS 1
435 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
436 # define IF_HAS_NO_KEYWORDS(...)
438 # define HAS_KEYWORDS 0
439 # define IF_HAS_KEYWORDS(...)
440 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
443 /* If you comment out one of these below, it will be #defined later
444 * to perform debug printfs to stderr: */
445 #define debug_printf(...) do {} while (0)
446 /* Finer-grained debug switches */
447 #define debug_printf_parse(...) do {} while (0)
448 #define debug_printf_heredoc(...) do {} while (0)
449 #define debug_print_tree(a, b) do {} while (0)
450 #define debug_printf_exec(...) do {} while (0)
451 #define debug_printf_env(...) do {} while (0)
452 #define debug_printf_jobs(...) do {} while (0)
453 #define debug_printf_expand(...) do {} while (0)
454 #define debug_printf_varexp(...) do {} while (0)
455 #define debug_printf_glob(...) do {} while (0)
456 #define debug_printf_redir(...) do {} while (0)
457 #define debug_printf_list(...) do {} while (0)
458 #define debug_printf_subst(...) do {} while (0)
459 #define debug_printf_prompt(...) do {} while (0)
460 #define debug_printf_clean(...) do {} while (0)
462 #define ERR_PTR ((void*)(long)1)
464 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
466 #define _SPECIAL_VARS_STR "_*@$!?#"
467 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
468 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
469 #if BASH_PATTERN_SUBST
470 /* Support / and // replace ops */
471 /* Note that // is stored as \ in "encoded" string representation */
472 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
473 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
474 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
476 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
477 # define VAR_SUBST_OPS "%#:-=+?"
478 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
481 #define SPECIAL_VAR_SYMBOL_STR "\3"
482 #define SPECIAL_VAR_SYMBOL 3
483 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
484 #define SPECIAL_VAR_QUOTED_SVS 1
488 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
490 /* This supports saving pointers malloced in vfork child,
491 * to be freed in the parent.
494 typedef struct nommu_save_t {
495 struct variable *old_vars;
497 char **argv_from_re_execing;
510 #if ENABLE_HUSH_LOOPS
517 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
522 /* three pseudo-keywords support contrived "case" syntax: */
523 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
524 RES_MATCH , /* "word)" */
525 RES_CASE_BODY, /* "this command is inside CASE" */
532 typedef struct o_string {
534 int length; /* position where data is appended */
537 /* At least some part of the string was inside '' or "",
538 * possibly empty one: word"", wo''rd etc. */
539 smallint has_quoted_part;
540 smallint has_empty_slot;
541 smallint ended_in_ifs;
544 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
546 /* Protect newly added chars against globbing
547 * by prepending \ to *, ?, [, \ */
548 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
550 /* Used for initialization: o_string foo = NULL_O_STRING; */
551 #define NULL_O_STRING { NULL }
553 #ifndef debug_printf_parse
554 static const char *const assignment_flag[] = {
556 "DEFINITELY_ASSIGNMENT",
562 /* We almost can use standard FILE api, but we need an ability to move
563 * its fd when redirects coincide with it. No api exists for that
564 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
565 * HFILE is our internal alternative. Only supports reading.
566 * Since we now can, we incorporate linked list of all opened HFILEs
567 * into the struct (used to be a separate mini-list).
569 typedef struct HFILE {
572 struct HFILE *next_hfile;
578 typedef struct in_str {
585 /* The descrip member of this structure is only used to make
586 * debugging output pretty */
587 static const struct {
589 signed char default_fd;
592 { O_RDONLY, 0, "<" },
593 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
594 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
595 { O_CREAT|O_RDWR, 1, "<>" },
596 { O_RDONLY, 0, "<<" },
597 /* Should not be needed. Bogus default_fd helps in debugging */
598 /* { O_RDONLY, 77, "<<" }, */
601 struct redir_struct {
602 struct redir_struct *next;
603 char *rd_filename; /* filename */
604 int rd_fd; /* fd to redirect */
605 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
607 smallint rd_type; /* (enum redir_type) */
608 /* note: for heredocs, rd_filename contains heredoc delimiter,
609 * and subsequently heredoc itself; and rd_dup is a bitmask:
610 * bit 0: do we need to trim leading tabs?
611 * bit 1: is heredoc quoted (<<'delim' syntax) ?
614 typedef enum redir_type {
616 REDIRECT_OVERWRITE = 1,
619 REDIRECT_HEREDOC = 4,
620 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
623 REDIRFD_SYNTAX_ERR = -2,
624 REDIRFD_TO_FILE = -1,
625 /* otherwise, rd_fd is redirected to rd_dup */
627 HEREDOC_SKIPTABS = 1,
633 pid_t pid; /* 0 if exited */
634 unsigned assignment_cnt; /* how many argv[i] are assignments? */
635 #if ENABLE_HUSH_LINENO_VAR
638 smallint cmd_type; /* CMD_xxx */
640 #define CMD_SUBSHELL 1
641 #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
642 /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
645 # define CMD_SINGLEWORD_NOGLOB 2
647 #if ENABLE_HUSH_FUNCTIONS
648 # define CMD_FUNCDEF 3
651 smalluint cmd_exitcode;
652 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
655 char *group_as_string;
657 #if ENABLE_HUSH_FUNCTIONS
658 struct function *child_func;
659 /* This field is used to prevent a bug here:
660 * while...do f1() {a;}; f1; f1() {b;}; f1; done
661 * When we execute "f1() {a;}" cmd, we create new function and clear
662 * cmd->group, cmd->group_as_string, cmd->argv[0].
663 * When we execute "f1() {b;}", we notice that f1 exists,
664 * and that its "parent cmd" struct is still "alive",
665 * we put those fields back into cmd->xxx
666 * (struct function has ->parent_cmd ptr to facilitate that).
667 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
668 * Without this trick, loop would execute a;b;b;b;...
669 * instead of correct sequence a;b;a;b;...
670 * When command is freed, it severs the link
671 * (sets ->child_func->parent_cmd to NULL).
674 char **argv; /* command name and arguments */
675 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
676 * and on execution these are substituted with their values.
677 * Substitution can make _several_ words out of one argv[n]!
678 * Example: argv[0]=='.^C*^C.' here: echo .$*.
679 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
681 struct redir_struct *redirects; /* I/O redirections */
683 /* Is there anything in this command at all? */
684 #define IS_NULL_CMD(cmd) \
685 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
689 int num_cmds; /* total number of commands in pipe */
690 int alive_cmds; /* number of commands running (not exited) */
691 int stopped_cmds; /* number of commands alive, but stopped */
693 unsigned jobid; /* job number */
694 pid_t pgrp; /* process group ID for the job */
695 char *cmdtext; /* name of job */
697 struct command *cmds; /* array of commands in pipe */
698 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
699 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
700 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
702 typedef enum pipe_style {
708 /* Is there anything in this pipe at all? */
709 #define IS_NULL_PIPE(pi) \
710 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
712 /* This holds pointers to the various results of parsing */
713 struct parse_context {
714 /* linked list of pipes */
715 struct pipe *list_head;
716 /* last pipe (being constructed right now) */
718 /* last command in pipe (being constructed right now) */
719 struct command *command;
720 /* last redirect in command->redirects list */
721 struct redir_struct *pending_redirect;
726 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
729 smallint ctx_inverted; /* "! cmd | cmd" */
731 smallint ctx_dsemicolon; /* ";;" seen */
733 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
735 /* group we are enclosed in:
736 * example: "if pipe1; pipe2; then pipe3; fi"
737 * when we see "if" or "then", we malloc and copy current context,
738 * and make ->stack point to it. then we parse pipeN.
739 * when closing "then" / fi" / whatever is found,
740 * we move list_head into ->stack->command->group,
741 * copy ->stack into current context, and delete ->stack.
742 * (parsing of { list } and ( list ) doesn't use this method)
744 struct parse_context *stack;
748 MAYBE_ASSIGNMENT = 0,
749 DEFINITELY_ASSIGNMENT = 1,
751 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
755 /* On program start, environ points to initial environment.
756 * putenv adds new pointers into it, unsetenv removes them.
757 * Neither of these (de)allocates the strings.
758 * setenv allocates new strings in malloc space and does putenv,
759 * and thus setenv is unusable (leaky) for shell's purposes */
760 #define setenv(...) setenv_is_leaky_dont_use()
762 struct variable *next;
763 char *varstr; /* points to "name=" portion */
764 int max_len; /* if > 0, name is part of initial env; else name is malloced */
765 uint16_t var_nest_level;
766 smallint flg_export; /* putenv should be done on this var */
767 smallint flg_read_only;
775 #if ENABLE_HUSH_FUNCTIONS
777 struct function *next;
779 struct command *parent_cmd;
782 char *body_as_string;
788 /* set -/+o OPT support. (TODO: make it optional)
789 * bash supports the following opts:
800 * interactive-comments on
818 static const char o_opt_strings[] ALIGN1 =
822 #if ENABLE_HUSH_MODE_X
830 #if ENABLE_HUSH_MODE_X
836 /* "Globals" within this file */
837 /* Sorted roughly by size (smaller offsets == smaller code) */
839 /* interactive_fd != 0 means we are an interactive shell.
840 * If we are, then saved_tty_pgrp can also be != 0, meaning
841 * that controlling tty is available. With saved_tty_pgrp == 0,
842 * job control still works, but terminal signals
843 * (^C, ^Z, ^Y, ^\) won't work at all, and background
844 * process groups can only be created with "cmd &".
845 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
846 * to give tty to the foreground process group,
847 * and will take it back when the group is stopped (^Z)
850 #if ENABLE_HUSH_INTERACTIVE
851 /* 'interactive_fd' is a fd# open to ctty, if we have one
852 * _AND_ if we decided to act interactively */
855 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
856 # define G_interactive_fd (G.interactive_fd)
858 # define G_interactive_fd 0
860 #if ENABLE_FEATURE_EDITING
861 line_input_t *line_input_state;
866 #if ENABLE_HUSH_RANDOM_SUPPORT
872 pid_t saved_tty_pgrp;
873 struct pipe *job_list;
874 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
876 # define G_saved_tty_pgrp 0
878 /* How deeply are we in context where "set -e" is ignored */
880 /* "set -e" rules (do we follow them correctly?):
881 * Exit if pipe, list, or compound command exits with a non-zero status.
882 * Shell does not exit if failed command is part of condition in
883 * if/while, part of && or || list except the last command, any command
884 * in a pipe but the last, or if the command's return value is being
885 * inverted with !. If a compound command other than a subshell returns a
886 * non-zero status because a command failed while -e was being ignored, the
887 * shell does not exit. A trap on ERR, if set, is executed before the shell
888 * exits [ERR is a bashism].
890 * If a compound command or function executes in a context where -e is
891 * ignored, none of the commands executed within are affected by the -e
892 * setting. If a compound command or function sets -e while executing in a
893 * context where -e is ignored, that setting does not have any effect until
894 * the compound command or the command containing the function call completes.
897 char o_opt[NUM_OPT_O];
898 #if ENABLE_HUSH_MODE_X
899 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
903 #if ENABLE_HUSH_INTERACTIVE
904 smallint promptmode; /* 0: PS1, 1: PS2 */
906 smallint flag_SIGINT;
907 #if ENABLE_HUSH_LOOPS
908 smallint flag_break_continue;
910 #if ENABLE_HUSH_FUNCTIONS
911 /* 0: outside of a function (or sourced file)
912 * -1: inside of a function, ok to use return builtin
913 * 1: return is invoked, skip all till end of func
915 smallint flag_return_in_progress;
916 # define G_flag_return_in_progress (G.flag_return_in_progress)
918 # define G_flag_return_in_progress 0
920 smallint exiting; /* used to prevent EXIT trap recursion */
921 /* These support $?, $#, and $1 */
922 smalluint last_exitcode;
923 smalluint expand_exitcode;
924 smalluint last_bg_pid_exitcode;
926 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
927 smalluint global_args_malloced;
928 # define G_global_args_malloced (G.global_args_malloced)
930 # define G_global_args_malloced 0
932 /* how many non-NULL argv's we have. NB: $# + 1 */
936 char *argv0_for_re_execing;
938 #if ENABLE_HUSH_LOOPS
939 unsigned depth_break_continue;
940 unsigned depth_of_loop;
942 #if ENABLE_HUSH_GETOPTS
943 unsigned getopt_count;
946 char *ifs_whitespace; /* = G.ifs or malloced */
948 struct variable *top_var;
949 char **expanded_assignments;
950 struct variable **shadowed_vars_pp;
951 unsigned var_nest_level;
952 #if ENABLE_HUSH_FUNCTIONS
953 # if ENABLE_HUSH_LOCAL
954 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
956 struct function *top_func;
958 /* Signal and trap handling */
960 unsigned count_SIGCHLD;
961 unsigned handled_SIGCHLD;
962 smallint we_have_children;
964 #if ENABLE_HUSH_LINENO_VAR
969 /* Which signals have non-DFL handler (even with no traps set)?
970 * Set at the start to:
971 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
972 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
973 * The rest is cleared right before execv syscalls.
974 * Other than these two times, never modified.
976 unsigned special_sig_mask;
978 unsigned fatal_sig_mask;
979 # define G_fatal_sig_mask (G.fatal_sig_mask)
981 # define G_fatal_sig_mask 0
984 char **traps; /* char *traps[NSIG] */
985 # define G_traps G.traps
987 # define G_traps ((char**)NULL)
989 sigset_t pending_set;
990 #if ENABLE_HUSH_MEMLEAK
991 unsigned long memleak_value;
993 #if ENABLE_HUSH_MODE_X
994 unsigned x_mode_depth;
995 /* "set -x" output should not be redirectable with subsequent 2>FILE.
996 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
997 * for all subsequent output.
1000 o_string x_mode_buf;
1005 struct sigaction sa;
1006 #if ENABLE_FEATURE_EDITING
1007 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1010 #define G (*ptr_to_globals)
1011 /* Not #defining name to G.name - this quickly gets unwieldy
1012 * (too many defines). Also, I actually prefer to see when a variable
1013 * is global, thus "G." prefix is a useful hint */
1014 #define INIT_G() do { \
1015 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
1016 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1017 sigfillset(&G.sa.sa_mask); \
1018 G.sa.sa_flags = SA_RESTART; \
1022 /* Function prototypes for builtins */
1023 static int builtin_cd(char **argv) FAST_FUNC;
1024 #if ENABLE_HUSH_ECHO
1025 static int builtin_echo(char **argv) FAST_FUNC;
1027 static int builtin_eval(char **argv) FAST_FUNC;
1028 static int builtin_exec(char **argv) FAST_FUNC;
1029 static int builtin_exit(char **argv) FAST_FUNC;
1030 #if ENABLE_HUSH_EXPORT
1031 static int builtin_export(char **argv) FAST_FUNC;
1033 #if ENABLE_HUSH_READONLY
1034 static int builtin_readonly(char **argv) FAST_FUNC;
1037 static int builtin_fg_bg(char **argv) FAST_FUNC;
1038 static int builtin_jobs(char **argv) FAST_FUNC;
1040 #if ENABLE_HUSH_GETOPTS
1041 static int builtin_getopts(char **argv) FAST_FUNC;
1043 #if ENABLE_HUSH_HELP
1044 static int builtin_help(char **argv) FAST_FUNC;
1046 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1047 static int builtin_history(char **argv) FAST_FUNC;
1049 #if ENABLE_HUSH_LOCAL
1050 static int builtin_local(char **argv) FAST_FUNC;
1052 #if ENABLE_HUSH_MEMLEAK
1053 static int builtin_memleak(char **argv) FAST_FUNC;
1055 #if ENABLE_HUSH_PRINTF
1056 static int builtin_printf(char **argv) FAST_FUNC;
1058 static int builtin_pwd(char **argv) FAST_FUNC;
1059 #if ENABLE_HUSH_READ
1060 static int builtin_read(char **argv) FAST_FUNC;
1063 static int builtin_set(char **argv) FAST_FUNC;
1065 static int builtin_shift(char **argv) FAST_FUNC;
1066 static int builtin_source(char **argv) FAST_FUNC;
1067 #if ENABLE_HUSH_TEST || BASH_TEST2
1068 static int builtin_test(char **argv) FAST_FUNC;
1070 #if ENABLE_HUSH_TRAP
1071 static int builtin_trap(char **argv) FAST_FUNC;
1073 #if ENABLE_HUSH_TYPE
1074 static int builtin_type(char **argv) FAST_FUNC;
1076 #if ENABLE_HUSH_TIMES
1077 static int builtin_times(char **argv) FAST_FUNC;
1079 static int builtin_true(char **argv) FAST_FUNC;
1080 #if ENABLE_HUSH_UMASK
1081 static int builtin_umask(char **argv) FAST_FUNC;
1083 #if ENABLE_HUSH_UNSET
1084 static int builtin_unset(char **argv) FAST_FUNC;
1086 #if ENABLE_HUSH_KILL
1087 static int builtin_kill(char **argv) FAST_FUNC;
1089 #if ENABLE_HUSH_WAIT
1090 static int builtin_wait(char **argv) FAST_FUNC;
1092 #if ENABLE_HUSH_LOOPS
1093 static int builtin_break(char **argv) FAST_FUNC;
1094 static int builtin_continue(char **argv) FAST_FUNC;
1096 #if ENABLE_HUSH_FUNCTIONS
1097 static int builtin_return(char **argv) FAST_FUNC;
1100 /* Table of built-in functions. They can be forked or not, depending on
1101 * context: within pipes, they fork. As simple commands, they do not.
1102 * When used in non-forking context, they can change global variables
1103 * in the parent shell process. If forked, of course they cannot.
1104 * For example, 'unset foo | whatever' will parse and run, but foo will
1105 * still be set at the end. */
1106 struct built_in_command {
1108 int (*b_function)(char **argv) FAST_FUNC;
1109 #if ENABLE_HUSH_HELP
1110 const char *b_descr;
1111 # define BLTIN(cmd, func, help) { cmd, func, help }
1113 # define BLTIN(cmd, func, help) { cmd, func }
1117 static const struct built_in_command bltins1[] = {
1118 BLTIN("." , builtin_source , "Run commands in file"),
1119 BLTIN(":" , builtin_true , NULL),
1121 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1123 #if ENABLE_HUSH_LOOPS
1124 BLTIN("break" , builtin_break , "Exit loop"),
1126 BLTIN("cd" , builtin_cd , "Change directory"),
1127 #if ENABLE_HUSH_LOOPS
1128 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1130 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1131 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1132 BLTIN("exit" , builtin_exit , NULL),
1133 #if ENABLE_HUSH_EXPORT
1134 BLTIN("export" , builtin_export , "Set environment variables"),
1137 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1139 #if ENABLE_HUSH_GETOPTS
1140 BLTIN("getopts" , builtin_getopts , NULL),
1142 #if ENABLE_HUSH_HELP
1143 BLTIN("help" , builtin_help , NULL),
1145 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1146 BLTIN("history" , builtin_history , "Show history"),
1149 BLTIN("jobs" , builtin_jobs , "List jobs"),
1151 #if ENABLE_HUSH_KILL
1152 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1154 #if ENABLE_HUSH_LOCAL
1155 BLTIN("local" , builtin_local , "Set local variables"),
1157 #if ENABLE_HUSH_MEMLEAK
1158 BLTIN("memleak" , builtin_memleak , NULL),
1160 #if ENABLE_HUSH_READ
1161 BLTIN("read" , builtin_read , "Input into variable"),
1163 #if ENABLE_HUSH_READONLY
1164 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1166 #if ENABLE_HUSH_FUNCTIONS
1167 BLTIN("return" , builtin_return , "Return from function"),
1170 BLTIN("set" , builtin_set , "Set positional parameters"),
1172 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1174 BLTIN("source" , builtin_source , NULL),
1176 #if ENABLE_HUSH_TIMES
1177 BLTIN("times" , builtin_times , NULL),
1179 #if ENABLE_HUSH_TRAP
1180 BLTIN("trap" , builtin_trap , "Trap signals"),
1182 BLTIN("true" , builtin_true , NULL),
1183 #if ENABLE_HUSH_TYPE
1184 BLTIN("type" , builtin_type , "Show command type"),
1186 #if ENABLE_HUSH_ULIMIT
1187 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1189 #if ENABLE_HUSH_UMASK
1190 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1192 #if ENABLE_HUSH_UNSET
1193 BLTIN("unset" , builtin_unset , "Unset variables"),
1195 #if ENABLE_HUSH_WAIT
1196 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1199 /* These builtins won't be used if we are on NOMMU and need to re-exec
1200 * (it's cheaper to run an external program in this case):
1202 static const struct built_in_command bltins2[] = {
1203 #if ENABLE_HUSH_TEST
1204 BLTIN("[" , builtin_test , NULL),
1207 BLTIN("[[" , builtin_test , NULL),
1209 #if ENABLE_HUSH_ECHO
1210 BLTIN("echo" , builtin_echo , NULL),
1212 #if ENABLE_HUSH_PRINTF
1213 BLTIN("printf" , builtin_printf , NULL),
1215 BLTIN("pwd" , builtin_pwd , NULL),
1216 #if ENABLE_HUSH_TEST
1217 BLTIN("test" , builtin_test , NULL),
1225 /* prevent disasters with G.debug_indent < 0 */
1226 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1227 # define debug_enter() (G.debug_indent++)
1228 # define debug_leave() (G.debug_indent--)
1230 # define indent() ((void)0)
1231 # define debug_enter() ((void)0)
1232 # define debug_leave() ((void)0)
1235 #ifndef debug_printf
1236 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1239 #ifndef debug_printf_parse
1240 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1243 #ifndef debug_printf_heredoc
1244 # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1247 #ifndef debug_printf_exec
1248 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1251 #ifndef debug_printf_env
1252 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1255 #ifndef debug_printf_jobs
1256 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1257 # define DEBUG_JOBS 1
1259 # define DEBUG_JOBS 0
1262 #ifndef debug_printf_expand
1263 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1264 # define DEBUG_EXPAND 1
1266 # define DEBUG_EXPAND 0
1269 #ifndef debug_printf_varexp
1270 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1273 #ifndef debug_printf_glob
1274 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1275 # define DEBUG_GLOB 1
1277 # define DEBUG_GLOB 0
1280 #ifndef debug_printf_redir
1281 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1284 #ifndef debug_printf_list
1285 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1288 #ifndef debug_printf_subst
1289 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1292 #ifndef debug_printf_prompt
1293 # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1296 #ifndef debug_printf_clean
1297 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1298 # define DEBUG_CLEAN 1
1300 # define DEBUG_CLEAN 0
1304 static void debug_print_strings(const char *prefix, char **vv)
1307 fdprintf(2, "%s:\n", prefix);
1309 fdprintf(2, " '%s'\n", *vv++);
1312 # define debug_print_strings(prefix, vv) ((void)0)
1316 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1319 static void *xxmalloc(int lineno, size_t size)
1321 void *ptr = xmalloc((size + 0xff) & ~0xff);
1322 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1325 static void *xxrealloc(int lineno, void *ptr, size_t size)
1327 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1328 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1331 static char *xxstrdup(int lineno, const char *str)
1333 char *ptr = xstrdup(str);
1334 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1337 static void xxfree(void *ptr)
1339 fdprintf(2, "free %p\n", ptr);
1342 # define xmalloc(s) xxmalloc(__LINE__, s)
1343 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1344 # define xstrdup(s) xxstrdup(__LINE__, s)
1345 # define free(p) xxfree(p)
1349 /* Syntax and runtime errors. They always abort scripts.
1350 * In interactive use they usually discard unparsed and/or unexecuted commands
1351 * and return to the prompt.
1352 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1355 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1356 # define syntax_error(lineno, msg) syntax_error(msg)
1357 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1358 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1359 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1360 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1363 static void die_if_script(void)
1365 if (!G_interactive_fd) {
1366 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1367 xfunc_error_retval = G.last_exitcode;
1372 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1377 bb_error_msg("hush.c:%u", lineno);
1380 bb_verror_msg(fmt, p, NULL);
1385 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1388 bb_error_msg("syntax error: %s", msg);
1390 bb_error_msg("syntax error");
1394 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1396 bb_error_msg("syntax error at '%s'", msg);
1400 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1402 bb_error_msg("syntax error: unterminated %s", s);
1403 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1407 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1409 char msg[2] = { ch, '\0' };
1410 syntax_error_unterm_str(lineno, msg);
1413 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1419 bb_error_msg("hush.c:%u", lineno);
1421 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1426 # undef msg_and_die_if_script
1427 # undef syntax_error
1428 # undef syntax_error_at
1429 # undef syntax_error_unterm_ch
1430 # undef syntax_error_unterm_str
1431 # undef syntax_error_unexpected_ch
1433 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1434 # define syntax_error(msg) syntax_error(__LINE__, msg)
1435 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1436 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1437 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1438 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1442 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1443 static void cmdedit_update_prompt(void);
1445 # define cmdedit_update_prompt() ((void)0)
1449 /* Utility functions
1451 /* Replace each \x with x in place, return ptr past NUL. */
1452 static char *unbackslash(char *src)
1454 char *dst = src = strchrnul(src, '\\');
1463 /* else: "\<nul>". Do not delete this backslash.
1464 * Testcase: eval 'echo ok\'
1469 if ((*dst++ = *src++) == '\0')
1475 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1496 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1497 v[count1 + count2] = NULL;
1500 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1504 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1506 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1507 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1510 #define add_strings_to_strings(strings, add, need_to_dup) \
1511 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1514 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1515 static char **add_string_to_strings(char **strings, char *add)
1520 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1523 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1525 char **ptr = add_string_to_strings(strings, add);
1526 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1529 #define add_string_to_strings(strings, add) \
1530 xx_add_string_to_strings(__LINE__, strings, add)
1533 static void free_strings(char **strings)
1547 static int dup_CLOEXEC(int fd, int avoid_fd)
1551 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1553 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1554 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1555 } else { /* newfd < 0 */
1564 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1568 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1574 /* fd was not open? */
1579 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1580 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1586 /* Manipulating HFILEs */
1587 static HFILE *hfopen(const char *name)
1594 fd = open(name, O_RDONLY | O_CLOEXEC);
1597 if (O_CLOEXEC == 0) /* ancient libc */
1598 close_on_exec_on(fd);
1601 fp = xmalloc(sizeof(*fp));
1602 fp->is_stdin = (name == NULL);
1604 fp->cur = fp->end = fp->buf;
1605 fp->next_hfile = G.HFILE_list;
1609 static void hfclose(HFILE *fp)
1611 HFILE **pp = &G.HFILE_list;
1615 *pp = cur->next_hfile;
1618 pp = &cur->next_hfile;
1624 static int refill_HFILE_and_getc(HFILE *fp)
1629 /* Already saw EOF */
1632 /* Try to buffer more input */
1634 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1636 bb_perror_msg("read error");
1639 fp->end = fp->buf + n;
1646 return (unsigned char)(*fp->cur++);
1648 /* Inlined for common case of non-empty buffer.
1650 static ALWAYS_INLINE int hfgetc(HFILE *fp)
1652 if (fp->cur < fp->end)
1653 return (unsigned char)(*fp->cur++);
1655 return refill_HFILE_and_getc(fp);
1657 static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1659 HFILE *fl = G.HFILE_list;
1662 /* We use it only on script files, they are all CLOEXEC */
1663 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1664 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1665 return 1; /* "found and moved" */
1667 fl = fl->next_hfile;
1669 #if ENABLE_HUSH_MODE_X
1670 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1671 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1672 return 1; /* "found and moved" */
1675 return 0; /* "not in the list" */
1677 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1678 static void close_all_HFILE_list(void)
1680 HFILE *fl = G.HFILE_list;
1682 /* hfclose would also free HFILE object.
1683 * It is disastrous if we share memory with a vforked parent.
1684 * I'm not sure we never come here after vfork.
1685 * Therefore just close fd, nothing more.
1687 * ">" instead of ">=": we don't close fd#0,
1688 * interactive shell uses hfopen(NULL) as stdin input
1689 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1690 * If we'd close it here, then e.g. interactive "set | sort"
1691 * with NOFORKed sort, would have sort's input fd closed.
1694 /*hfclose(fl); - unsafe */
1696 fl = fl->next_hfile;
1700 static int fd_in_HFILEs(int fd)
1702 HFILE *fl = G.HFILE_list;
1706 fl = fl->next_hfile;
1712 /* Helpers for setting new $n and restoring them back
1714 typedef struct save_arg_t {
1718 IF_HUSH_SET(smallint sv_g_malloced;)
1721 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1723 sv->sv_argv0 = argv[0];
1724 sv->sv_g_argv = G.global_argv;
1725 sv->sv_g_argc = G.global_argc;
1726 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1728 argv[0] = G.global_argv[0]; /* retain $0 */
1729 G.global_argv = argv;
1730 IF_HUSH_SET(G.global_args_malloced = 0;)
1732 G.global_argc = 1 + string_array_len(argv + 1);
1735 static void restore_G_args(save_arg_t *sv, char **argv)
1738 if (G.global_args_malloced) {
1739 /* someone ran "set -- arg1 arg2 ...", undo */
1740 char **pp = G.global_argv;
1741 while (*++pp) /* note: does not free $0 */
1743 free(G.global_argv);
1746 argv[0] = sv->sv_argv0;
1747 G.global_argv = sv->sv_g_argv;
1748 G.global_argc = sv->sv_g_argc;
1749 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1753 /* Basic theory of signal handling in shell
1754 * ========================================
1755 * This does not describe what hush does, rather, it is current understanding
1756 * what it _should_ do. If it doesn't, it's a bug.
1757 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1759 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1760 * is finished or backgrounded. It is the same in interactive and
1761 * non-interactive shells, and is the same regardless of whether
1762 * a user trap handler is installed or a shell special one is in effect.
1763 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1764 * backgrounds (i.e. stops) or kills all members of currently running
1767 * Wait builtin is interruptible by signals for which user trap is set
1768 * or by SIGINT in interactive shell.
1770 * Trap handlers will execute even within trap handlers. (right?)
1772 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1773 * except for handlers set to '' (empty string).
1775 * If job control is off, backgrounded commands ("cmd &")
1776 * have SIGINT, SIGQUIT set to SIG_IGN.
1778 * Commands which are run in command substitution ("`cmd`")
1779 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1781 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1782 * by the shell from its parent.
1784 * Signals which differ from SIG_DFL action
1785 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1788 * SIGTERM (interactive): ignore
1789 * SIGHUP (interactive):
1790 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1791 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1792 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1793 * that all pipe members are stopped. Try this in bash:
1794 * while :; do :; done - ^Z does not background it
1795 * (while :; do :; done) - ^Z backgrounds it
1796 * SIGINT (interactive): wait for last pipe, ignore the rest
1797 * of the command line, show prompt. NB: ^C does not send SIGINT
1798 * to interactive shell while shell is waiting for a pipe,
1799 * since shell is bg'ed (is not in foreground process group).
1800 * Example 1: this waits 5 sec, but does not execute ls:
1801 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1802 * Example 2: this does not wait and does not execute ls:
1803 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1804 * Example 3: this does not wait 5 sec, but executes ls:
1805 * "sleep 5; ls -l" + press ^C
1806 * Example 4: this does not wait and does not execute ls:
1807 * "sleep 5 & wait; ls -l" + press ^C
1809 * (What happens to signals which are IGN on shell start?)
1810 * (What happens with signal mask on shell start?)
1812 * Old implementation
1813 * ==================
1814 * We use in-kernel pending signal mask to determine which signals were sent.
1815 * We block all signals which we don't want to take action immediately,
1816 * i.e. we block all signals which need to have special handling as described
1817 * above, and all signals which have traps set.
1818 * After each pipe execution, we extract any pending signals via sigtimedwait()
1821 * unsigned special_sig_mask: a mask of such "special" signals
1822 * sigset_t blocked_set: current blocked signal set
1825 * clear bit in blocked_set unless it is also in special_sig_mask
1826 * "trap 'cmd' SIGxxx":
1827 * set bit in blocked_set (even if 'cmd' is '')
1828 * after [v]fork, if we plan to be a shell:
1829 * unblock signals with special interactive handling
1830 * (child shell is not interactive),
1831 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1832 * after [v]fork, if we plan to exec:
1833 * POSIX says fork clears pending signal mask in child - no need to clear it.
1834 * Restore blocked signal set to one inherited by shell just prior to exec.
1836 * Note: as a result, we do not use signal handlers much. The only uses
1837 * are to count SIGCHLDs
1838 * and to restore tty pgrp on signal-induced exit.
1841 * Standard says "When a subshell is entered, traps that are not being ignored
1842 * are set to the default actions". bash interprets it so that traps which
1843 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1845 * Problem: the above approach makes it unwieldy to catch signals while
1846 * we are in read builtin, or while we read commands from stdin:
1847 * masked signals are not visible!
1849 * New implementation
1850 * ==================
1851 * We record each signal we are interested in by installing signal handler
1852 * for them - a bit like emulating kernel pending signal mask in userspace.
1853 * We are interested in: signals which need to have special handling
1854 * as described above, and all signals which have traps set.
1855 * Signals are recorded in pending_set.
1856 * After each pipe execution, we extract any pending signals
1859 * unsigned special_sig_mask: a mask of shell-special signals.
1860 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1861 * char *traps[sig] if trap for sig is set (even if it's '').
1862 * sigset_t pending_set: set of sigs we received.
1865 * if sig is in special_sig_mask, set handler back to:
1866 * record_pending_signo, or to IGN if it's a tty stop signal
1867 * if sig is in fatal_sig_mask, set handler back to sigexit.
1868 * else: set handler back to SIG_DFL
1869 * "trap 'cmd' SIGxxx":
1870 * set handler to record_pending_signo.
1872 * set handler to SIG_IGN.
1873 * after [v]fork, if we plan to be a shell:
1874 * set signals with special interactive handling to SIG_DFL
1875 * (because child shell is not interactive),
1876 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1877 * after [v]fork, if we plan to exec:
1878 * POSIX says fork clears pending signal mask in child - no need to clear it.
1880 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1881 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1884 * Standard says "When a subshell is entered, traps that are not being ignored
1885 * are set to the default actions". bash interprets it so that traps which
1886 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1889 SPECIAL_INTERACTIVE_SIGS = 0
1894 SPECIAL_JOBSTOP_SIGS = 0
1903 static void record_pending_signo(int sig)
1905 sigaddset(&G.pending_set, sig);
1906 #if ENABLE_HUSH_FAST
1907 if (sig == SIGCHLD) {
1909 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1914 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1916 struct sigaction old_sa;
1918 /* We could use signal() to install handlers... almost:
1919 * except that we need to mask ALL signals while handlers run.
1920 * I saw signal nesting in strace, race window isn't small.
1921 * SA_RESTART is also needed, but in Linux, signal()
1922 * sets SA_RESTART too.
1924 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1925 /* sigfillset(&G.sa.sa_mask); - already done */
1926 /* G.sa.sa_flags = SA_RESTART; - already done */
1927 G.sa.sa_handler = handler;
1928 sigaction(sig, &G.sa, &old_sa);
1929 return old_sa.sa_handler;
1932 static void hush_exit(int exitcode) NORETURN;
1934 static void restore_ttypgrp_and__exit(void) NORETURN;
1935 static void restore_ttypgrp_and__exit(void)
1937 /* xfunc has failed! die die die */
1938 /* no EXIT traps, this is an escape hatch! */
1940 hush_exit(xfunc_error_retval);
1945 /* Needed only on some libc:
1946 * It was observed that on exit(), fgetc'ed buffered data
1947 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1948 * With the net effect that even after fork(), not vfork(),
1949 * exit() in NOEXECed applet in "sh SCRIPT":
1950 * noexec_applet_here
1951 * echo END_OF_SCRIPT
1952 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1953 * This makes "echo END_OF_SCRIPT" executed twice.
1954 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1955 * and in `cmd` handling.
1956 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1958 static void fflush_and__exit(void) NORETURN;
1959 static void fflush_and__exit(void)
1962 _exit(xfunc_error_retval);
1965 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1966 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1967 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1968 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1970 /* Restores tty foreground process group, and exits.
1971 * May be called as signal handler for fatal signal
1972 * (will resend signal to itself, producing correct exit state)
1973 * or called directly with -EXITCODE.
1974 * We also call it if xfunc is exiting.
1976 static void sigexit(int sig) NORETURN;
1977 static void sigexit(int sig)
1979 /* Careful: we can end up here after [v]fork. Do not restore
1980 * tty pgrp then, only top-level shell process does that */
1981 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1982 /* Disable all signals: job control, SIGPIPE, etc.
1983 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1985 sigprocmask_allsigs(SIG_BLOCK);
1986 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1989 /* Not a signal, just exit */
1993 kill_myself_with_sig(sig); /* does not return */
1997 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1998 # define enable_restore_tty_pgrp_on_exit() ((void)0)
2002 static sighandler_t pick_sighandler(unsigned sig)
2004 sighandler_t handler = SIG_DFL;
2005 if (sig < sizeof(unsigned)*8) {
2006 unsigned sigmask = (1 << sig);
2010 if (G_fatal_sig_mask & sigmask)
2014 /* sig has special handling? */
2015 if (G.special_sig_mask & sigmask) {
2016 handler = record_pending_signo;
2017 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
2018 * in order to ignore them: they will be raised
2019 * in an endless loop when we try to do some
2020 * terminal ioctls! We do have to _ignore_ these.
2022 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2029 /* Restores tty foreground process group, and exits. */
2030 static void hush_exit(int exitcode)
2032 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2033 save_history(G.line_input_state);
2037 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
2039 /* argv[0] is unused */
2040 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
2042 G.exiting = 1; /* prevent EXIT trap recursion */
2043 /* Note: G_traps[0] is not cleared!
2044 * "trap" will still show it, if executed
2049 #if ENABLE_FEATURE_CLEAN_UP
2051 struct variable *cur_var;
2052 if (G.cwd != bb_msg_unknown)
2054 cur_var = G.top_var;
2056 struct variable *tmp = cur_var;
2057 if (!cur_var->max_len)
2058 free(cur_var->varstr);
2059 cur_var = cur_var->next;
2067 sigexit(- (exitcode & 0xff));
2074 //TODO: return a mask of ALL handled sigs?
2075 static int check_and_run_traps(void)
2082 if (sigisemptyset(&G.pending_set))
2087 if (sigismember(&G.pending_set, sig)) {
2088 sigdelset(&G.pending_set, sig);
2091 } while (sig < NSIG);
2094 if (G_traps && G_traps[sig]) {
2095 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
2096 if (G_traps[sig][0]) {
2097 /* We have user-defined handler */
2098 smalluint save_rcode;
2100 /* argv[0] is unused */
2101 argv[1] = xstrdup(G_traps[sig]);
2102 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
2104 save_rcode = G.last_exitcode;
2107 //FIXME: shouldn't it be set to 128 + sig instead?
2108 G.last_exitcode = save_rcode;
2110 } /* else: "" trap, ignoring signal */
2113 /* not a trap: special action */
2116 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2122 //TODO: why are we doing this? ash and dash don't do this,
2123 //they have no handler for SIGHUP at all,
2124 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2126 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2127 /* bash is observed to signal whole process groups,
2128 * not individual processes */
2129 for (job = G.job_list; job; job = job->next) {
2132 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2133 if (kill(- job->pgrp, SIGHUP) == 0)
2134 kill(- job->pgrp, SIGCONT);
2139 #if ENABLE_HUSH_FAST
2141 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2143 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2145 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2146 * This simplifies wait builtin a bit.
2150 default: /* ignored: */
2151 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2152 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2154 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2155 * Example: wait is not interrupted by TERM
2156 * in interactive shell, because TERM is ignored.
2165 static const char *get_cwd(int force)
2167 if (force || G.cwd == NULL) {
2168 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2169 * we must not try to free(bb_msg_unknown) */
2170 if (G.cwd == bb_msg_unknown)
2172 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2174 G.cwd = bb_msg_unknown;
2181 * Shell and environment variable support
2183 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2185 struct variable **pp;
2186 struct variable *cur;
2189 while ((cur = *pp) != NULL) {
2190 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2197 static const char* FAST_FUNC get_local_var_value(const char *name)
2199 struct variable **vpp;
2200 unsigned len = strlen(name);
2202 if (G.expanded_assignments) {
2203 char **cpp = G.expanded_assignments;
2206 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2207 return cp + len + 1;
2212 vpp = get_ptr_to_local_var(name, len);
2214 return (*vpp)->varstr + len + 1;
2216 if (strcmp(name, "PPID") == 0)
2217 return utoa(G.root_ppid);
2218 // bash compat: UID? EUID?
2219 #if ENABLE_HUSH_RANDOM_SUPPORT
2220 if (strcmp(name, "RANDOM") == 0)
2221 return utoa(next_random(&G.random_gen));
2226 static void handle_changed_special_names(const char *name, unsigned name_len)
2228 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2229 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2231 cmdedit_update_prompt();
2235 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2238 #if ENABLE_HUSH_LINENO_VAR
2239 if (strncmp(name, "LINENO", 6) == 0) {
2240 G.lineno_var = NULL;
2244 #if ENABLE_HUSH_GETOPTS
2245 if (strncmp(name, "OPTIND", 6) == 0) {
2253 /* str holds "NAME=VAL" and is expected to be malloced.
2254 * We take ownership of it.
2256 #define SETFLAG_EXPORT (1 << 0)
2257 #define SETFLAG_UNEXPORT (1 << 1)
2258 #define SETFLAG_MAKE_RO (1 << 2)
2259 #define SETFLAG_VARLVL_SHIFT 3
2260 static int set_local_var(char *str, unsigned flags)
2262 struct variable **cur_pp;
2263 struct variable *cur;
2264 char *free_me = NULL;
2267 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
2269 eq_sign = strchr(str, '=');
2270 if (HUSH_DEBUG && !eq_sign)
2271 bb_error_msg_and_die("BUG in setvar");
2273 name_len = eq_sign - str + 1; /* including '=' */
2274 cur_pp = &G.top_var;
2275 while ((cur = *cur_pp) != NULL) {
2276 if (strncmp(cur->varstr, str, name_len) != 0) {
2277 cur_pp = &cur->next;
2281 /* We found an existing var with this name */
2282 if (cur->flg_read_only) {
2283 bb_error_msg("%s: readonly variable", str);
2285 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2286 //but export per se succeeds (does put the var in env). We don't mimic that.
2289 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2290 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2295 if (cur->var_nest_level < local_lvl) {
2296 /* bash 3.2.33(1) and exported vars:
2298 * # f() { local z=a; env | grep ^z; }
2304 if (cur->flg_export)
2305 flags |= SETFLAG_EXPORT;
2306 /* New variable is local ("local VAR=VAL" or
2308 * and existing one is global, or local
2309 * on a lower level that new one.
2310 * Remove it from global variable list:
2312 *cur_pp = cur->next;
2313 if (G.shadowed_vars_pp) {
2314 /* Save in "shadowed" list */
2315 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2316 cur->flg_export ? "exported " : "",
2317 cur->varstr, cur->var_nest_level, str, local_lvl
2319 cur->next = *G.shadowed_vars_pp;
2320 *G.shadowed_vars_pp = cur;
2322 /* Came from pseudo_exec_argv(), no need to save: delete it */
2323 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2324 cur->flg_export ? "exported " : "",
2325 cur->varstr, cur->var_nest_level, str, local_lvl
2327 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2328 free_me = cur->varstr; /* then free it later */
2334 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2335 debug_printf_env("assignement '%s' does not change anything\n", str);
2341 /* Replace the value in the found "struct variable" */
2342 if (cur->max_len != 0) {
2343 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
2344 /* This one is from startup env, reuse space */
2345 debug_printf_env("reusing startup env for '%s'\n", str);
2346 strcpy(cur->varstr, str);
2351 goto set_str_and_exp;
2353 /* max_len == 0 signifies "malloced" var, which we can
2354 * (and have to) free. But we can't free(cur->varstr) here:
2355 * if cur->flg_export is 1, it is in the environment.
2356 * We should either unsetenv+free, or wait until putenv,
2357 * then putenv(new)+free(old).
2359 free_me = cur->varstr;
2360 goto set_str_and_exp;
2363 /* Not found or shadowed - create new variable struct */
2364 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
2365 cur = xzalloc(sizeof(*cur));
2366 cur->var_nest_level = local_lvl;
2367 cur->next = *cur_pp;
2373 #if !BB_MMU || ENABLE_HUSH_READONLY
2374 if (flags & SETFLAG_MAKE_RO) {
2375 cur->flg_read_only = 1;
2378 if (flags & SETFLAG_EXPORT)
2379 cur->flg_export = 1;
2380 if (cur->flg_export) {
2381 if (flags & SETFLAG_UNEXPORT) {
2382 cur->flg_export = 0;
2383 /* unsetenv was already done */
2386 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
2387 i = putenv(cur->varstr);
2388 /* only now we can free old exported malloced string */
2395 handle_changed_special_names(cur->varstr, name_len - 1);
2400 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2402 char *var = xasprintf("%s=%s", name, val);
2403 set_local_var(var, /*flag:*/ 0);
2406 /* Used at startup and after each cd */
2407 static void set_pwd_var(unsigned flag)
2409 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2412 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2413 static int unset_local_var_len(const char *name, int name_len)
2415 struct variable *cur;
2416 struct variable **cur_pp;
2418 cur_pp = &G.top_var;
2419 while ((cur = *cur_pp) != NULL) {
2420 if (strncmp(cur->varstr, name, name_len) == 0
2421 && cur->varstr[name_len] == '='
2423 if (cur->flg_read_only) {
2424 bb_error_msg("%s: readonly variable", name);
2425 return EXIT_FAILURE;
2428 *cur_pp = cur->next;
2429 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2430 bb_unsetenv(cur->varstr);
2437 cur_pp = &cur->next;
2440 /* Handle "unset PS1" et al even if did not find the variable to unset */
2441 handle_changed_special_names(name, name_len);
2443 return EXIT_SUCCESS;
2446 static int unset_local_var(const char *name)
2448 return unset_local_var_len(name, strlen(name));
2454 * Helpers for "var1=val1 var2=val2 cmd" feature
2456 static void add_vars(struct variable *var)
2458 struct variable *next;
2462 var->next = G.top_var;
2464 if (var->flg_export) {
2465 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2466 putenv(var->varstr);
2468 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2474 /* We put strings[i] into variable table and possibly putenv them.
2475 * If variable is read only, we can free the strings[i]
2476 * which attempts to overwrite it.
2477 * The strings[] vector itself is freed.
2479 static void set_vars_and_save_old(char **strings)
2488 struct variable *var_p;
2489 struct variable **var_pp;
2492 eq = strchr(*s, '=');
2493 if (HUSH_DEBUG && !eq)
2494 bb_error_msg_and_die("BUG in varexp4");
2495 var_pp = get_ptr_to_local_var(*s, eq - *s);
2498 if (var_p->flg_read_only) {
2500 bb_error_msg("%s: readonly variable", *s);
2502 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2503 * If VAR is readonly, leaving it in the list
2504 * after asssignment error (msg above)
2505 * causes doubled error message later, on unset.
2507 debug_printf_env("removing/freeing '%s' element\n", *s);
2510 do { *p = p[1]; p++; } while (*p);
2513 /* below, set_local_var() with nest level will
2514 * "shadow" (remove) this variable from
2515 * global linked list.
2518 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2519 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2530 static void reinit_unicode_for_hush(void)
2532 /* Unicode support should be activated even if LANG is set
2533 * _during_ shell execution, not only if it was set when
2534 * shell was started. Therefore, re-check LANG every time:
2536 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2537 || ENABLE_UNICODE_USING_LOCALE
2539 const char *s = get_local_var_value("LC_ALL");
2540 if (!s) s = get_local_var_value("LC_CTYPE");
2541 if (!s) s = get_local_var_value("LANG");
2547 * in_str support (strings, and "strings" read from files).
2550 #if ENABLE_HUSH_INTERACTIVE
2551 /* To test correct lineedit/interactive behavior, type from command line:
2557 * It exercises a lot of corner cases.
2559 # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2560 static void cmdedit_update_prompt(void)
2562 G.PS1 = get_local_var_value("PS1");
2565 G.PS2 = get_local_var_value("PS2");
2570 static const char *setup_prompt_string(void)
2572 const char *prompt_str;
2574 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
2576 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2577 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
2578 if (G.promptmode == 0) { /* PS1 */
2579 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2580 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2582 /* bash uses $PWD value, even if it is set by user.
2583 * It uses current dir only if PWD is unset.
2584 * We always use current dir. */
2585 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2589 debug_printf("prompt_str '%s'\n", prompt_str);
2592 static int get_user_input(struct in_str *i)
2595 const char *prompt_str;
2597 prompt_str = setup_prompt_string();
2598 # if ENABLE_FEATURE_EDITING
2600 reinit_unicode_for_hush();
2601 if (G.flag_SIGINT) {
2602 /* There was ^C'ed, make it look prettier: */
2606 /* buglet: SIGINT will not make new prompt to appear _at once_,
2607 * only after <Enter>. (^C works immediately) */
2608 r = read_line_input(G.line_input_state, prompt_str,
2609 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2611 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2614 check_and_run_traps();
2615 if (r != 0 && !G.flag_SIGINT)
2617 /* ^C or SIGINT: repeat */
2618 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2619 write(STDOUT_FILENO, "^C", 2);
2620 G.last_exitcode = 128 + SIGINT;
2623 /* EOF/error detected */
2625 i->peek_buf[0] = r = EOF;
2628 i->p = G.user_input_buf;
2629 return (unsigned char)*i->p++;
2633 if (i->last_char == '\0' || i->last_char == '\n') {
2634 /* Why check_and_run_traps here? Try this interactively:
2635 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2636 * $ <[enter], repeatedly...>
2637 * Without check_and_run_traps, handler never runs.
2639 check_and_run_traps();
2640 fputs(prompt_str, stdout);
2643 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2644 r = hfgetc(i->file);
2645 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2646 * no ^C masking happens during fgetc, no special code for ^C:
2647 * it generates SIGINT as usual.
2649 check_and_run_traps();
2651 G.last_exitcode = 128 + SIGINT;
2658 /* This is the magic location that prints prompts
2659 * and gets data back from the user */
2660 static int fgetc_interactive(struct in_str *i)
2663 /* If it's interactive stdin, get new line. */
2664 if (G_interactive_fd && i->file->is_stdin) {
2665 /* Returns first char (or EOF), the rest is in i->p[] */
2666 ch = get_user_input(i);
2667 G.promptmode = 1; /* PS2 */
2668 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
2670 /* Not stdin: script file, sourced file, etc */
2671 do ch = hfgetc(i->file); while (ch == '\0');
2676 static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
2679 do ch = hfgetc(i->file); while (ch == '\0');
2682 #endif /* INTERACTIVE */
2684 static int i_getch(struct in_str *i)
2689 /* string-based in_str */
2690 ch = (unsigned char)*i->p;
2699 /* FILE-based in_str */
2701 #if ENABLE_FEATURE_EDITING
2702 /* This can be stdin, check line editing char[] buffer */
2703 if (i->p && *i->p != '\0') {
2704 ch = (unsigned char)*i->p++;
2708 /* peek_buf[] is an int array, not char. Can contain EOF. */
2709 ch = i->peek_buf[0];
2711 int ch2 = i->peek_buf[1];
2712 i->peek_buf[0] = ch2;
2713 if (ch2 == 0) /* very likely, avoid redundant write */
2719 ch = fgetc_interactive(i);
2721 debug_printf("file_get: got '%c' %d\n", ch, ch);
2723 #if ENABLE_HUSH_LINENO_VAR
2726 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2732 static int i_peek(struct in_str *i)
2737 /* string-based in_str */
2738 /* Doesn't report EOF on NUL. None of the callers care. */
2739 return (unsigned char)*i->p;
2742 /* FILE-based in_str */
2744 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2745 /* This can be stdin, check line editing char[] buffer */
2746 if (i->p && *i->p != '\0')
2747 return (unsigned char)*i->p;
2749 /* peek_buf[] is an int array, not char. Can contain EOF. */
2750 ch = i->peek_buf[0];
2754 /* Need to get a new char */
2755 ch = fgetc_interactive(i);
2756 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2758 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2759 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2765 i->peek_buf[0] = ch;
2766 /*i->peek_buf[1] = 0; - already is */
2770 /* Only ever called if i_peek() was called, and did not return EOF.
2771 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2772 * not end-of-line. Therefore we never need to read a new editing line here.
2774 static int i_peek2(struct in_str *i)
2778 /* There are two cases when i->p[] buffer exists.
2779 * (1) it's a string in_str.
2780 * (2) It's a file, and we have a saved line editing buffer.
2781 * In both cases, we know that i->p[0] exists and not NUL, and
2782 * the peek2 result is in i->p[1].
2785 return (unsigned char)i->p[1];
2787 /* Now we know it is a file-based in_str. */
2789 /* peek_buf[] is an int array, not char. Can contain EOF. */
2790 /* Is there 2nd char? */
2791 ch = i->peek_buf[1];
2793 /* We did not read it yet, get it now */
2794 do ch = hfgetc(i->file); while (ch == '\0');
2795 i->peek_buf[1] = ch;
2798 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2802 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2807 ch = i_getch(input);
2810 ch2 = i_peek(input);
2813 /* backslash+newline, skip it */
2818 /* Note: this function _eats_ \<newline> pairs, safe to use plain
2819 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2821 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2829 ch2 = i_peek2(input);
2832 /* backslash+newline, skip it */
2838 static void setup_file_in_str(struct in_str *i, HFILE *fp)
2840 memset(i, 0, sizeof(*i));
2845 static void setup_string_in_str(struct in_str *i, const char *s)
2847 memset(i, 0, sizeof(*i));
2848 /*i->file = NULL */;
2856 #define B_CHUNK (32 * sizeof(char*))
2858 static void o_reset_to_empty_unquoted(o_string *o)
2861 o->has_quoted_part = 0;
2866 static void o_free_and_set_NULL(o_string *o)
2869 memset(o, 0, sizeof(*o));
2872 static ALWAYS_INLINE void o_free(o_string *o)
2877 static void o_grow_by(o_string *o, int len)
2879 if (o->length + len > o->maxlen) {
2880 o->maxlen += (2 * len) | (B_CHUNK-1);
2881 o->data = xrealloc(o->data, 1 + o->maxlen);
2885 static void o_addchr(o_string *o, int ch)
2887 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2888 if (o->length < o->maxlen) {
2889 /* likely. avoid o_grow_by() call */
2891 o->data[o->length] = ch;
2893 o->data[o->length] = '\0';
2901 /* Valid only if we know o_string is not empty */
2902 static void o_delchr(o_string *o)
2905 o->data[o->length] = '\0';
2909 static void o_addblock(o_string *o, const char *str, int len)
2912 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2916 static void o_addstr(o_string *o, const char *str)
2918 o_addblock(o, str, strlen(str));
2921 static void o_addstr_with_NUL(o_string *o, const char *str)
2923 o_addblock(o, str, strlen(str) + 1);
2927 static void nommu_addchr(o_string *o, int ch)
2933 # define nommu_addchr(o, str) ((void)0)
2936 #if ENABLE_HUSH_MODE_X
2937 static void x_mode_addchr(int ch)
2939 o_addchr(&G.x_mode_buf, ch);
2941 static void x_mode_addstr(const char *str)
2943 o_addstr(&G.x_mode_buf, str);
2945 static void x_mode_addblock(const char *str, int len)
2947 o_addblock(&G.x_mode_buf, str, len);
2949 static void x_mode_prefix(void)
2951 int n = G.x_mode_depth;
2952 do x_mode_addchr('+'); while (--n >= 0);
2954 static void x_mode_flush(void)
2956 int len = G.x_mode_buf.length;
2959 if (G.x_mode_fd > 0) {
2960 G.x_mode_buf.data[len] = '\n';
2961 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2963 G.x_mode_buf.length = 0;
2968 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2969 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2970 * Apparently, on unquoted $v bash still does globbing
2971 * ("v='*.txt'; echo $v" prints all .txt files),
2972 * but NOT brace expansion! Thus, there should be TWO independent
2973 * quoting mechanisms on $v expansion side: one protects
2974 * $v from brace expansion, and other additionally protects "$v" against globbing.
2975 * We have only second one.
2978 #if ENABLE_HUSH_BRACE_EXPANSION
2979 # define MAYBE_BRACES "{}"
2981 # define MAYBE_BRACES ""
2984 /* My analysis of quoting semantics tells me that state information
2985 * is associated with a destination, not a source.
2987 static void o_addqchr(o_string *o, int ch)
2990 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2995 o->data[o->length] = '\\';
2998 o->data[o->length] = ch;
3000 o->data[o->length] = '\0';
3003 static void o_addQchr(o_string *o, int ch)
3006 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3007 && strchr("*?[\\" MAYBE_BRACES, ch)
3010 o->data[o->length] = '\\';
3014 o->data[o->length] = ch;
3016 o->data[o->length] = '\0';
3019 static void o_addqblock(o_string *o, const char *str, int len)
3024 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
3025 if (ordinary_cnt > len) /* paranoia */
3027 o_addblock(o, str, ordinary_cnt);
3028 if (ordinary_cnt == len)
3029 return; /* NUL is already added by o_addblock */
3030 str += ordinary_cnt;
3031 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
3035 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
3037 o->data[o->length] = '\\';
3041 o->data[o->length] = ch;
3044 o->data[o->length] = '\0';
3047 static void o_addQblock(o_string *o, const char *str, int len)
3049 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
3050 o_addblock(o, str, len);
3053 o_addqblock(o, str, len);
3056 static void o_addQstr(o_string *o, const char *str)
3058 o_addQblock(o, str, strlen(str));
3061 /* A special kind of o_string for $VAR and `cmd` expansion.
3062 * It contains char* list[] at the beginning, which is grown in 16 element
3063 * increments. Actual string data starts at the next multiple of 16 * (char*).
3064 * list[i] contains an INDEX (int!) into this string data.
3065 * It means that if list[] needs to grow, data needs to be moved higher up
3066 * but list[i]'s need not be modified.
3067 * NB: remembering how many list[i]'s you have there is crucial.
3068 * o_finalize_list() operation post-processes this structure - calculates
3069 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3071 #if DEBUG_EXPAND || DEBUG_GLOB
3072 static void debug_print_list(const char *prefix, o_string *o, int n)
3074 char **list = (char**)o->data;
3075 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3079 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
3080 prefix, list, n, string_start, o->length, o->maxlen,
3081 !!(o->o_expflags & EXP_FLAG_GLOB),
3083 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3086 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3087 o->data + (int)(uintptr_t)list[i] + string_start,
3088 o->data + (int)(uintptr_t)list[i] + string_start);
3092 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
3094 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
3098 # define debug_print_list(prefix, o, n) ((void)0)
3101 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3102 * in list[n] so that it points past last stored byte so far.
3103 * It returns n+1. */
3104 static int o_save_ptr_helper(o_string *o, int n)
3106 char **list = (char**)o->data;
3110 if (!o->has_empty_slot) {
3111 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3112 string_len = o->length - string_start;
3113 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
3114 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
3115 /* list[n] points to string_start, make space for 16 more pointers */
3116 o->maxlen += 0x10 * sizeof(list[0]);
3117 o->data = xrealloc(o->data, o->maxlen + 1);
3118 list = (char**)o->data;
3119 memmove(list + n + 0x10, list + n, string_len);
3121 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3122 * check. (grep for -prev-ifs-check-).
3123 * Ensure that argv[-1][last] is not garbage
3124 * but zero bytes, to save index check there.
3126 list[n + 0x10 - 1] = 0;
3127 o->length += 0x10 * sizeof(list[0]);
3129 debug_printf_list("list[%d]=%d string_start=%d\n",
3130 n, string_len, string_start);
3133 /* We have empty slot at list[n], reuse without growth */
3134 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3135 string_len = o->length - string_start;
3136 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3137 n, string_len, string_start);
3138 o->has_empty_slot = 0;
3140 o->has_quoted_part = 0;
3141 list[n] = (char*)(uintptr_t)string_len;
3145 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
3146 static int o_get_last_ptr(o_string *o, int n)
3148 char **list = (char**)o->data;
3149 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3151 return ((int)(uintptr_t)list[n-1]) + string_start;
3155 * Globbing routines.
3157 * Most words in commands need to be globbed, even ones which are
3158 * (single or double) quoted. This stems from the possiblity of
3159 * constructs like "abc"* and 'abc'* - these should be globbed.
3160 * Having a different code path for fully-quoted strings ("abc",
3161 * 'abc') would only help performance-wise, but we still need
3162 * code for partially-quoted strings.
3164 * Unfortunately, if we want to match bash and ash behavior in all cases,
3165 * the logic can't be "shell-syntax argument is first transformed
3166 * to a string, then globbed, and if globbing does not match anything,
3167 * it is used verbatim". Here are two examples where it fails:
3171 * The globbing can't be avoided (because of '?' at the end).
3172 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3173 * and are glob-escaped. If this does not match, bash/ash print b\*?
3174 * - IOW: they "unbackslash" the glob pattern.
3175 * Now, look at this:
3177 * v='\\\*'; echo b$v?
3179 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
3180 * should be used as glob pattern with no changes. However, if glob
3181 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
3183 * ash implements this by having an encoded representation of the word
3184 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3185 * Glob pattern is derived from it. If glob fails, the decision what result
3186 * should be is made using that encoded representation. Not glob pattern.
3189 #if ENABLE_HUSH_BRACE_EXPANSION
3190 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
3191 * first, it processes even {a} (no commas), second,
3192 * I didn't manage to make it return strings when they don't match
3193 * existing files. Need to re-implement it.
3197 static int glob_needed(const char *s)
3206 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3212 /* Return pointer to next closing brace or to comma */
3213 static const char *next_brace_sub(const char *cp)
3217 while (*cp != '\0') {
3224 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3230 return *cp != '\0' ? cp : NULL;
3232 /* Recursive brace globber. Note: may garble pattern[]. */
3233 static int glob_brace(char *pattern, o_string *o, int n)
3235 char *new_pattern_buf;
3242 debug_printf_glob("glob_brace('%s')\n", pattern);
3248 if (*begin == '{') {
3249 /* Find the first sub-pattern and at the same time
3250 * find the rest after the closing brace */
3251 next = next_brace_sub(begin);
3253 /* An illegal expression */
3257 /* "{abc}" with no commas - illegal
3258 * brace expr, disregard and skip it */
3264 if (*begin == '\\' && begin[1] != '\0')
3268 debug_printf_glob("begin:%s\n", begin);
3269 debug_printf_glob("next:%s\n", next);
3271 /* Now find the end of the whole brace expression */
3273 while (*rest != '}') {
3274 rest = next_brace_sub(rest);
3276 /* An illegal expression */
3279 debug_printf_glob("rest:%s\n", rest);
3281 rest_len = strlen(++rest) + 1;
3283 /* We are sure the brace expression is well-formed */
3285 /* Allocate working buffer large enough for our work */
3286 new_pattern_buf = xmalloc(strlen(pattern));
3288 /* We have a brace expression. BEGIN points to the opening {,
3289 * NEXT points past the terminator of the first element, and REST
3290 * points past the final }. We will accumulate result names from
3291 * recursive runs for each brace alternative in the buffer using
3296 /* Construct the new glob expression */
3299 mempcpy(new_pattern_buf,
3300 /* We know the prefix for all sub-patterns */
3301 pattern, begin - pattern),
3305 /* Note: glob_brace() may garble new_pattern_buf[].
3306 * That's why we re-copy prefix every time (1st memcpy above).
3308 n = glob_brace(new_pattern_buf, o, n);
3310 /* We saw the last entry */
3314 next = next_brace_sub(next);
3316 free(new_pattern_buf);
3324 memset(&globdata, 0, sizeof(globdata));
3325 gr = glob(pattern, 0, NULL, &globdata);
3326 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3328 if (gr == GLOB_NOMATCH) {
3329 globfree(&globdata);
3330 /* NB: garbles parameter */
3331 unbackslash(pattern);
3332 o_addstr_with_NUL(o, pattern);
3333 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3334 return o_save_ptr_helper(o, n);
3336 if (gr == GLOB_NOSPACE)
3337 bb_die_memory_exhausted();
3338 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3339 * but we didn't specify it. Paranoia again. */
3340 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3342 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3343 char **argv = globdata.gl_pathv;
3345 o_addstr_with_NUL(o, *argv);
3346 n = o_save_ptr_helper(o, n);
3352 globfree(&globdata);
3356 /* Performs globbing on last list[],
3357 * saving each result as a new list[].
3359 static int perform_glob(o_string *o, int n)
3361 char *pattern, *copy;
3363 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3365 return o_save_ptr_helper(o, n);
3366 pattern = o->data + o_get_last_ptr(o, n);
3367 debug_printf_glob("glob pattern '%s'\n", pattern);
3368 if (!glob_needed(pattern)) {
3369 /* unbackslash last string in o in place, fix length */
3370 o->length = unbackslash(pattern) - o->data;
3371 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3372 return o_save_ptr_helper(o, n);
3375 copy = xstrdup(pattern);
3376 /* "forget" pattern in o */
3377 o->length = pattern - o->data;
3378 n = glob_brace(copy, o, n);
3381 debug_print_list("perform_glob returning", o, n);
3385 #else /* !HUSH_BRACE_EXPANSION */
3388 static int glob_needed(const char *s)
3397 if (*s == '*' || *s == '[' || *s == '?')
3403 /* Performs globbing on last list[],
3404 * saving each result as a new list[].
3406 static int perform_glob(o_string *o, int n)
3412 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3414 return o_save_ptr_helper(o, n);
3415 pattern = o->data + o_get_last_ptr(o, n);
3416 debug_printf_glob("glob pattern '%s'\n", pattern);
3417 if (!glob_needed(pattern)) {
3419 /* unbackslash last string in o in place, fix length */
3420 o->length = unbackslash(pattern) - o->data;
3421 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3422 return o_save_ptr_helper(o, n);
3425 memset(&globdata, 0, sizeof(globdata));
3426 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3427 * If we glob "*.\*" and don't find anything, we need
3428 * to fall back to using literal "*.*", but GLOB_NOCHECK
3429 * will return "*.\*"!
3431 gr = glob(pattern, 0, NULL, &globdata);
3432 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3434 if (gr == GLOB_NOMATCH) {
3435 globfree(&globdata);
3438 if (gr == GLOB_NOSPACE)
3439 bb_die_memory_exhausted();
3440 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3441 * but we didn't specify it. Paranoia again. */
3442 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3444 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3445 char **argv = globdata.gl_pathv;
3446 /* "forget" pattern in o */
3447 o->length = pattern - o->data;
3449 o_addstr_with_NUL(o, *argv);
3450 n = o_save_ptr_helper(o, n);
3456 globfree(&globdata);
3458 debug_print_list("perform_glob returning", o, n);
3462 #endif /* !HUSH_BRACE_EXPANSION */
3464 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3465 * Otherwise, just finish current list[] and start new */
3466 static int o_save_ptr(o_string *o, int n)
3468 if (o->o_expflags & EXP_FLAG_GLOB) {
3469 /* If o->has_empty_slot, list[n] was already globbed
3470 * (if it was requested back then when it was filled)
3471 * so don't do that again! */
3472 if (!o->has_empty_slot)
3473 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3475 return o_save_ptr_helper(o, n);
3478 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3479 static char **o_finalize_list(o_string *o, int n)
3485 debug_print_list("finalized", o, n);
3486 debug_printf_expand("finalized n:%d\n", n);
3487 list = (char**)o->data;
3488 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3492 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3497 static void free_pipe_list(struct pipe *pi);
3499 /* Returns pi->next - next pipe in the list */
3500 static struct pipe *free_pipe(struct pipe *pi)
3505 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3506 for (i = 0; i < pi->num_cmds; i++) {
3507 struct command *command;
3508 struct redir_struct *r, *rnext;
3510 command = &pi->cmds[i];
3511 debug_printf_clean(" command %d:\n", i);
3512 if (command->argv) {
3516 for (a = 0, p = command->argv; *p; a++, p++) {
3517 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3520 free_strings(command->argv);
3521 //command->argv = NULL;
3523 /* not "else if": on syntax error, we may have both! */
3524 if (command->group) {
3525 debug_printf_clean(" begin group (cmd_type:%d)\n",
3527 free_pipe_list(command->group);
3528 debug_printf_clean(" end group\n");
3529 //command->group = NULL;
3531 /* else is crucial here.
3532 * If group != NULL, child_func is meaningless */
3533 #if ENABLE_HUSH_FUNCTIONS
3534 else if (command->child_func) {
3535 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3536 command->child_func->parent_cmd = NULL;
3540 free(command->group_as_string);
3541 //command->group_as_string = NULL;
3543 for (r = command->redirects; r; r = rnext) {
3544 debug_printf_clean(" redirect %d%s",
3545 r->rd_fd, redir_table[r->rd_type].descrip);
3546 /* guard against the case >$FOO, where foo is unset or blank */
3547 if (r->rd_filename) {
3548 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3549 free(r->rd_filename);
3550 //r->rd_filename = NULL;
3552 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3556 //command->redirects = NULL;
3558 free(pi->cmds); /* children are an array, they get freed all at once */
3562 //pi->cmdtext = NULL;
3570 static void free_pipe_list(struct pipe *pi)
3574 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3576 debug_printf_clean("pipe followup code %d\n", pi->followup);
3582 /*** Parsing routines ***/
3584 #ifndef debug_print_tree
3585 static void debug_print_tree(struct pipe *pi, int lvl)
3587 static const char *const PIPE[] = {
3593 static const char *RES[] = {
3594 [RES_NONE ] = "NONE" ,
3597 [RES_THEN ] = "THEN" ,
3598 [RES_ELIF ] = "ELIF" ,
3599 [RES_ELSE ] = "ELSE" ,
3602 # if ENABLE_HUSH_LOOPS
3603 [RES_FOR ] = "FOR" ,
3604 [RES_WHILE] = "WHILE",
3605 [RES_UNTIL] = "UNTIL",
3607 [RES_DONE ] = "DONE" ,
3609 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3612 # if ENABLE_HUSH_CASE
3613 [RES_CASE ] = "CASE" ,
3614 [RES_CASE_IN ] = "CASE_IN" ,
3615 [RES_MATCH] = "MATCH",
3616 [RES_CASE_BODY] = "CASE_BODY",
3617 [RES_ESAC ] = "ESAC" ,
3619 [RES_XXXX ] = "XXXX" ,
3620 [RES_SNTX ] = "SNTX" ,
3622 static const char *const CMDTYPE[] = {
3626 # if ENABLE_HUSH_FUNCTIONS
3635 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3638 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3640 pi->followup, PIPE[pi->followup]
3643 while (prn < pi->num_cmds) {
3644 struct command *command = &pi->cmds[prn];
3645 char **argv = command->argv;
3647 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3649 command->assignment_cnt);
3650 #if ENABLE_HUSH_LINENO_VAR
3651 fdprintf(2, " LINENO:%u", command->lineno);
3653 if (command->group) {
3654 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3655 CMDTYPE[command->cmd_type],
3658 , " group_as_string:", command->group_as_string
3663 debug_print_tree(command->group, lvl+1);
3667 if (argv) while (*argv) {
3668 fdprintf(2, " '%s'", *argv);
3671 if (command->redirects)
3672 fdprintf(2, " {redir}");
3680 #endif /* debug_print_tree */
3682 static struct pipe *new_pipe(void)
3685 pi = xzalloc(sizeof(struct pipe));
3686 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3690 /* Command (member of a pipe) is complete, or we start a new pipe
3691 * if ctx->command is NULL.
3692 * No errors possible here.
3694 static int done_command(struct parse_context *ctx)
3696 /* The command is really already in the pipe structure, so
3697 * advance the pipe counter and make a new, null command. */
3698 struct pipe *pi = ctx->pipe;
3699 struct command *command = ctx->command;
3701 #if 0 /* Instead we emit error message at run time */
3702 if (ctx->pending_redirect) {
3703 /* For example, "cmd >" (no filename to redirect to) */
3704 syntax_error("invalid redirect");
3705 ctx->pending_redirect = NULL;
3710 if (IS_NULL_CMD(command)) {
3711 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3715 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3716 //debug_print_tree(ctx->list_head, 20);
3718 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3721 /* Only real trickiness here is that the uncommitted
3722 * command structure is not counted in pi->num_cmds. */
3723 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3724 ctx->command = command = &pi->cmds[pi->num_cmds];
3726 memset(command, 0, sizeof(*command));
3727 #if ENABLE_HUSH_LINENO_VAR
3728 command->lineno = G.lineno;
3729 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
3731 return pi->num_cmds; /* used only for 0/nonzero check */
3734 static void done_pipe(struct parse_context *ctx, pipe_style type)
3738 debug_printf_parse("done_pipe entered, followup %d\n", type);
3739 /* Close previous command */
3740 not_null = done_command(ctx);
3742 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3743 ctx->ctx_inverted = 0;
3744 ctx->pipe->res_word = ctx->ctx_res_w;
3746 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3747 /* Necessary since && and || have precedence over &:
3748 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3749 * in a backgrounded subshell.
3752 struct command *command;
3754 /* Is this actually this construct, all pipes end with && or ||? */
3755 pi = ctx->list_head;
3756 while (pi != ctx->pipe) {
3757 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3762 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3763 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3764 pi = xzalloc(sizeof(*pi));
3765 pi->followup = PIPE_BG;
3767 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3768 command = &pi->cmds[0];
3769 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3770 command->cmd_type = CMD_NORMAL;
3771 command->group = ctx->list_head;
3773 command->group_as_string = xstrndup(
3774 ctx->as_string.data,
3775 ctx->as_string.length - 1 /* do not copy last char, "&" */
3778 /* Replace all pipes in ctx with one newly created */
3779 ctx->list_head = ctx->pipe = pi;
3782 ctx->pipe->followup = type;
3785 /* Without this check, even just <enter> on command line generates
3786 * tree of three NOPs (!). Which is harmless but annoying.
3787 * IOW: it is safe to do it unconditionally. */
3790 || ctx->ctx_res_w == RES_FI
3792 #if ENABLE_HUSH_LOOPS
3793 || ctx->ctx_res_w == RES_DONE
3794 || ctx->ctx_res_w == RES_FOR
3795 || ctx->ctx_res_w == RES_IN
3797 #if ENABLE_HUSH_CASE
3798 || ctx->ctx_res_w == RES_ESAC
3802 debug_printf_parse("done_pipe: adding new pipe: "
3803 "not_null:%d ctx->ctx_res_w:%d\n",
3804 not_null, ctx->ctx_res_w);
3806 ctx->pipe->next = new_p;
3808 /* RES_THEN, RES_DO etc are "sticky" -
3809 * they remain set for pipes inside if/while.
3810 * This is used to control execution.
3811 * RES_FOR and RES_IN are NOT sticky (needed to support
3812 * cases where variable or value happens to match a keyword):
3814 #if ENABLE_HUSH_LOOPS
3815 if (ctx->ctx_res_w == RES_FOR
3816 || ctx->ctx_res_w == RES_IN)
3817 ctx->ctx_res_w = RES_NONE;
3819 #if ENABLE_HUSH_CASE
3820 if (ctx->ctx_res_w == RES_MATCH)
3821 ctx->ctx_res_w = RES_CASE_BODY;
3822 if (ctx->ctx_res_w == RES_CASE)
3823 ctx->ctx_res_w = RES_CASE_IN;
3825 ctx->command = NULL; /* trick done_command below */
3826 /* Create the memory for command, roughly:
3827 * ctx->pipe->cmds = new struct command;
3828 * ctx->command = &ctx->pipe->cmds[0];
3831 //debug_print_tree(ctx->list_head, 10);
3833 debug_printf_parse("done_pipe return\n");
3836 static void initialize_context(struct parse_context *ctx)
3838 memset(ctx, 0, sizeof(*ctx));
3839 if (MAYBE_ASSIGNMENT != 0)
3840 ctx->is_assignment = MAYBE_ASSIGNMENT;
3841 ctx->pipe = ctx->list_head = new_pipe();
3842 /* Create the memory for command, roughly:
3843 * ctx->pipe->cmds = new struct command;
3844 * ctx->command = &ctx->pipe->cmds[0];
3849 /* If a reserved word is found and processed, parse context is modified
3850 * and 1 is returned.
3853 struct reserved_combo {
3856 unsigned char assignment_flag;
3860 FLAG_END = (1 << RES_NONE ),
3862 FLAG_IF = (1 << RES_IF ),
3863 FLAG_THEN = (1 << RES_THEN ),
3864 FLAG_ELIF = (1 << RES_ELIF ),
3865 FLAG_ELSE = (1 << RES_ELSE ),
3866 FLAG_FI = (1 << RES_FI ),
3868 # if ENABLE_HUSH_LOOPS
3869 FLAG_FOR = (1 << RES_FOR ),
3870 FLAG_WHILE = (1 << RES_WHILE),
3871 FLAG_UNTIL = (1 << RES_UNTIL),
3872 FLAG_DO = (1 << RES_DO ),
3873 FLAG_DONE = (1 << RES_DONE ),
3874 FLAG_IN = (1 << RES_IN ),
3876 # if ENABLE_HUSH_CASE
3877 FLAG_MATCH = (1 << RES_MATCH),
3878 FLAG_ESAC = (1 << RES_ESAC ),
3880 FLAG_START = (1 << RES_XXXX ),
3883 static const struct reserved_combo* match_reserved_word(o_string *word)
3885 /* Mostly a list of accepted follow-up reserved words.
3886 * FLAG_END means we are done with the sequence, and are ready
3887 * to turn the compound list into a command.
3888 * FLAG_START means the word must start a new compound list.
3890 static const struct reserved_combo reserved_list[] = {
3892 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3893 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3894 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3895 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3896 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3897 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3899 # if ENABLE_HUSH_LOOPS
3900 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3901 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3902 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3903 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3904 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3905 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3907 # if ENABLE_HUSH_CASE
3908 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3909 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3912 const struct reserved_combo *r;
3914 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3915 if (strcmp(word->data, r->literal) == 0)
3920 /* Return NULL: not a keyword, else: keyword
3922 static const struct reserved_combo* reserved_word(struct parse_context *ctx)
3924 # if ENABLE_HUSH_CASE
3925 static const struct reserved_combo reserved_match = {
3926 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3929 const struct reserved_combo *r;
3931 if (ctx->word.has_quoted_part)
3933 r = match_reserved_word(&ctx->word);
3935 return r; /* NULL */
3937 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3938 # if ENABLE_HUSH_CASE
3939 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3940 /* "case word IN ..." - IN part starts first MATCH part */
3941 r = &reserved_match;
3944 if (r->flag == 0) { /* '!' */
3945 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3946 syntax_error("! ! command");
3947 ctx->ctx_res_w = RES_SNTX;
3949 ctx->ctx_inverted = 1;
3952 if (r->flag & FLAG_START) {
3953 struct parse_context *old;
3955 old = xmemdup(ctx, sizeof(*ctx));
3956 debug_printf_parse("push stack %p\n", old);
3957 initialize_context(ctx);
3959 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3960 syntax_error_at(ctx->word.data);
3961 ctx->ctx_res_w = RES_SNTX;
3964 /* "{...} fi" is ok. "{...} if" is not
3966 * if { echo foo; } then { echo bar; } fi */
3967 if (ctx->command->group)
3968 done_pipe(ctx, PIPE_SEQ);
3971 ctx->ctx_res_w = r->res;
3972 ctx->old_flag = r->flag;
3973 ctx->is_assignment = r->assignment_flag;
3974 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
3976 if (ctx->old_flag & FLAG_END) {
3977 struct parse_context *old;
3979 done_pipe(ctx, PIPE_SEQ);
3980 debug_printf_parse("pop stack %p\n", ctx->stack);
3982 old->command->group = ctx->list_head;
3983 old->command->cmd_type = CMD_NORMAL;
3985 /* At this point, the compound command's string is in
3986 * ctx->as_string... except for the leading keyword!
3987 * Consider this example: "echo a | if true; then echo a; fi"
3988 * ctx->as_string will contain "true; then echo a; fi",
3989 * with "if " remaining in old->as_string!
3993 int len = old->as_string.length;
3994 /* Concatenate halves */
3995 o_addstr(&old->as_string, ctx->as_string.data);
3996 o_free(&ctx->as_string);
3997 /* Find where leading keyword starts in first half */
3998 str = old->as_string.data + len;
3999 if (str > old->as_string.data)
4000 str--; /* skip whitespace after keyword */
4001 while (str > old->as_string.data && isalpha(str[-1]))
4003 /* Ugh, we're done with this horrid hack */
4004 old->command->group_as_string = xstrdup(str);
4005 debug_printf_parse("pop, remembering as:'%s'\n",
4006 old->command->group_as_string);
4009 *ctx = *old; /* physical copy */
4014 #endif /* HAS_KEYWORDS */
4016 /* Word is complete, look at it and update parsing context.
4017 * Normal return is 0. Syntax errors return 1.
4018 * Note: on return, word is reset, but not o_free'd!
4020 static int done_word(struct parse_context *ctx)
4022 struct command *command = ctx->command;
4024 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4025 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
4026 debug_printf_parse("done_word return 0: true null, ignored\n");
4030 if (ctx->pending_redirect) {
4031 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4032 * only if run as "bash", not "sh" */
4033 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
4035 * If the redirection operator is "<<" or "<<-", the word
4036 * that follows the redirection operator shall be
4037 * subjected to quote removal; it is unspecified whether
4038 * any of the other expansions occur. For the other
4039 * redirection operators, the word that follows the
4040 * redirection operator shall be subjected to tilde
4041 * expansion, parameter expansion, command substitution,
4042 * arithmetic expansion, and quote removal.
4043 * Pathname expansion shall not be performed
4044 * on the word by a non-interactive shell; an interactive
4045 * shell may perform it, but shall do so only when
4046 * the expansion would result in one word."
4048 //bash does not do parameter/command substitution or arithmetic expansion
4049 //for _heredoc_ redirection word: these constructs look for exact eof marker
4053 // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4055 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
4056 /* Cater for >\file case:
4057 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4058 * Same with heredocs:
4059 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4061 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4062 unbackslash(ctx->pending_redirect->rd_filename);
4063 /* Is it <<"HEREDOC"? */
4064 if (ctx->word.has_quoted_part) {
4065 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4068 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
4069 ctx->pending_redirect = NULL;
4072 # if ENABLE_HUSH_CASE
4073 if (ctx->ctx_dsemicolon
4074 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4076 /* already done when ctx_dsemicolon was set to 1: */
4077 /* ctx->ctx_res_w = RES_MATCH; */
4078 ctx->ctx_dsemicolon = 0;
4081 if (!command->argv /* if it's the first word... */
4082 # if ENABLE_HUSH_LOOPS
4083 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4084 && ctx->ctx_res_w != RES_IN
4086 # if ENABLE_HUSH_CASE
4087 && ctx->ctx_res_w != RES_CASE
4090 const struct reserved_combo *reserved;
4091 reserved = reserved_word(ctx);
4092 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
4094 # if ENABLE_HUSH_LINENO_VAR
4098 * If we don't close the pipe _now_, immediately after "do", lineno logic
4099 * sees "cmd" as starting at "do" - i.e., at the previous line.
4102 IF_HUSH_IF(|| reserved->res == RES_THEN)
4103 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4104 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4105 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4107 done_pipe(ctx, PIPE_SEQ);
4110 o_reset_to_empty_unquoted(&ctx->word);
4111 debug_printf_parse("done_word return %d\n",
4112 (ctx->ctx_res_w == RES_SNTX));
4113 return (ctx->ctx_res_w == RES_SNTX);
4115 # if defined(CMD_SINGLEWORD_NOGLOB)
4118 || strcmp(ctx->word.data, "[[") == 0
4120 /* In bash, local/export/readonly are special, args
4121 * are assignments and therefore expansion of them
4122 * should be "one-word" expansion:
4123 * $ export i=`echo 'a b'` # one arg: "i=a b"
4125 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4126 * ls: cannot access i=a: No such file or directory
4127 * ls: cannot access b: No such file or directory
4128 * Note: bash 3.2.33(1) does this only if export word
4129 * itself is not quoted:
4130 * $ export i=`echo 'aaa bbb'`; echo "$i"
4132 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4135 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4136 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4137 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
4139 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4144 #endif /* HAS_KEYWORDS */
4146 if (command->group) {
4147 /* "{ echo foo; } echo bar" - bad */
4148 syntax_error_at(ctx->word.data);
4149 debug_printf_parse("done_word return 1: syntax error, "
4150 "groups and arglists don't mix\n");
4154 /* If this word wasn't an assignment, next ones definitely
4155 * can't be assignments. Even if they look like ones. */
4156 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4157 && ctx->is_assignment != WORD_IS_KEYWORD
4159 ctx->is_assignment = NOT_ASSIGNMENT;
4161 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
4162 command->assignment_cnt++;
4163 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4165 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4166 ctx->is_assignment = MAYBE_ASSIGNMENT;
4168 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4169 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
4170 debug_print_strings("word appended to argv", command->argv);
4173 #if ENABLE_HUSH_LOOPS
4174 if (ctx->ctx_res_w == RES_FOR) {
4175 if (ctx->word.has_quoted_part
4176 || !is_well_formed_var_name(command->argv[0], '\0')
4178 /* bash says just "not a valid identifier" */
4179 syntax_error("not a valid identifier in for");
4182 /* Force FOR to have just one word (variable name) */
4183 /* NB: basically, this makes hush see "for v in ..."
4184 * syntax as if it is "for v; in ...". FOR and IN become
4185 * two pipe structs in parse tree. */
4186 done_pipe(ctx, PIPE_SEQ);
4189 #if ENABLE_HUSH_CASE
4190 /* Force CASE to have just one word */
4191 if (ctx->ctx_res_w == RES_CASE) {
4192 done_pipe(ctx, PIPE_SEQ);
4196 o_reset_to_empty_unquoted(&ctx->word);
4198 debug_printf_parse("done_word return 0\n");
4203 /* Peek ahead in the input to find out if we have a "&n" construct,
4204 * as in "2>&1", that represents duplicating a file descriptor.
4206 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4207 * REDIRFD_SYNTAX_ERR if syntax error,
4208 * REDIRFD_TO_FILE if no & was seen,
4209 * or the number found.
4212 #define parse_redir_right_fd(as_string, input) \
4213 parse_redir_right_fd(input)
4215 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4221 return REDIRFD_TO_FILE;
4223 ch = i_getch(input); /* get the & */
4224 nommu_addchr(as_string, ch);
4227 ch = i_getch(input);
4228 nommu_addchr(as_string, ch);
4229 return REDIRFD_CLOSE;
4233 while (ch != EOF && isdigit(ch)) {
4234 d = d*10 + (ch-'0');
4236 ch = i_getch(input);
4237 nommu_addchr(as_string, ch);
4242 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4244 bb_error_msg("ambiguous redirect");
4245 return REDIRFD_SYNTAX_ERR;
4248 /* Return code is 0 normal, 1 if a syntax error is detected
4250 static int parse_redirect(struct parse_context *ctx,
4253 struct in_str *input)
4255 struct command *command = ctx->command;
4256 struct redir_struct *redir;
4257 struct redir_struct **redirp;
4260 dup_num = REDIRFD_TO_FILE;
4261 if (style != REDIRECT_HEREDOC) {
4262 /* Check for a '>&1' type redirect */
4263 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4264 if (dup_num == REDIRFD_SYNTAX_ERR)
4267 int ch = i_peek_and_eat_bkslash_nl(input);
4268 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4269 if (dup_num) { /* <<-... */
4270 ch = i_getch(input);
4271 nommu_addchr(&ctx->as_string, ch);
4276 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4277 int ch = i_peek_and_eat_bkslash_nl(input);
4279 /* >|FILE redirect ("clobbering" >).
4280 * Since we do not support "set -o noclobber" yet,
4281 * >| and > are the same for now. Just eat |.
4283 ch = i_getch(input);
4284 nommu_addchr(&ctx->as_string, ch);
4288 /* Create a new redir_struct and append it to the linked list */
4289 redirp = &command->redirects;
4290 while ((redir = *redirp) != NULL) {
4291 redirp = &(redir->next);
4293 *redirp = redir = xzalloc(sizeof(*redir));
4294 /* redir->next = NULL; */
4295 /* redir->rd_filename = NULL; */
4296 redir->rd_type = style;
4297 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4299 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4300 redir_table[style].descrip);
4302 redir->rd_dup = dup_num;
4303 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4304 /* Erik had a check here that the file descriptor in question
4305 * is legit; I postpone that to "run time"
4306 * A "-" representation of "close me" shows up as a -3 here */
4307 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4308 redir->rd_fd, redir->rd_dup);
4310 #if 0 /* Instead we emit error message at run time */
4311 if (ctx->pending_redirect) {
4312 /* For example, "cmd > <file" */
4313 syntax_error("invalid redirect");
4316 /* Set ctx->pending_redirect, so we know what to do at the
4317 * end of the next parsed word. */
4318 ctx->pending_redirect = redir;
4323 /* If a redirect is immediately preceded by a number, that number is
4324 * supposed to tell which file descriptor to redirect. This routine
4325 * looks for such preceding numbers. In an ideal world this routine
4326 * needs to handle all the following classes of redirects...
4327 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4328 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4329 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4330 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4332 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4334 * ... If n is quoted, the number shall not be recognized as part of
4335 * the redirection expression. For example:
4337 * writes the character 2 into file a"
4338 * We are getting it right by setting ->has_quoted_part on any \<char>
4340 * A -1 return means no valid number was found,
4341 * the caller should use the appropriate default for this redirection.
4343 static int redirect_opt_num(o_string *o)
4347 if (o->data == NULL)
4349 num = bb_strtou(o->data, NULL, 10);
4350 if (errno || num < 0)
4352 o_reset_to_empty_unquoted(o);
4357 #define fetch_till_str(as_string, input, word, skip_tabs) \
4358 fetch_till_str(input, word, skip_tabs)
4360 static char *fetch_till_str(o_string *as_string,
4361 struct in_str *input,
4365 o_string heredoc = NULL_O_STRING;
4367 int prev = 0; /* not \ */
4370 /* Starting with "" is necessary for this case:
4376 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4381 ch = i_getch(input);
4383 nommu_addchr(as_string, ch);
4384 if (ch == '\n' || ch == EOF) {
4386 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4387 /* End-of-line, and not a line continuation */
4388 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4389 heredoc.data[past_EOL] = '\0';
4390 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
4391 return heredoc.data;
4394 /* This is a new line.
4395 * Remember position and backslash-escaping status.
4397 o_addchr(&heredoc, ch);
4400 past_EOL = heredoc.length;
4401 /* Get 1st char of next line, possibly skipping leading tabs */
4403 ch = i_getch(input);
4405 nommu_addchr(as_string, ch);
4406 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4407 /* If this immediately ended the line,
4408 * go back to end-of-line checks.
4411 goto check_heredoc_end;
4414 /* Backslash-line continuation in an unquoted
4415 * heredoc. This does not need special handling
4416 * for heredoc body (unquoted heredocs are
4417 * expanded on "execution" and that would take
4418 * care of this case too), but not the case
4419 * of line continuation *in terminator*:
4425 heredoc.data[--heredoc.length] = '\0';
4426 prev = 0; /* not '\' */
4432 return NULL; /* error */
4434 o_addchr(&heredoc, ch);
4435 nommu_addchr(as_string, ch);
4436 if (prev == '\\' && ch == '\\')
4437 /* Correctly handle foo\\<eol> (not a line cont.) */
4438 prev = 0; /* not '\' */
4444 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4445 * and load them all. There should be exactly heredoc_cnt of them.
4448 #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4449 fetch_heredocs(pi, heredoc_cnt, input)
4451 static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
4453 while (pi && heredoc_cnt) {
4455 struct command *cmd = pi->cmds;
4457 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4459 cmd->argv ? cmd->argv[0] : "NONE"
4461 for (i = 0; i < pi->num_cmds; i++) {
4462 struct redir_struct *redir = cmd->redirects;
4464 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
4465 i, cmd->argv ? cmd->argv[0] : "NONE");
4467 if (redir->rd_type == REDIRECT_HEREDOC) {
4470 redir->rd_type = REDIRECT_HEREDOC2;
4471 /* redir->rd_dup is (ab)used to indicate <<- */
4472 p = fetch_till_str(as_string, input,
4473 redir->rd_filename, redir->rd_dup);
4475 syntax_error("unexpected EOF in here document");
4478 free(redir->rd_filename);
4479 redir->rd_filename = p;
4482 redir = redir->next;
4485 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4486 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4487 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4488 if (heredoc_cnt < 0)
4489 return heredoc_cnt; /* error */
4499 static int run_list(struct pipe *pi);
4501 #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4502 parse_stream(heredoc_cnt_ptr, input, end_trigger)
4504 static struct pipe *parse_stream(char **pstring,
4505 int *heredoc_cnt_ptr,
4506 struct in_str *input,
4509 /* Returns number of heredocs not yet consumed,
4512 static int parse_group(struct parse_context *ctx,
4513 struct in_str *input, int ch)
4515 /* ctx->word contains characters seen prior to ( or {.
4516 * Typically it's empty, but for function defs,
4517 * it contains function name (without '()'). */
4519 # define as_string NULL
4521 char *as_string = NULL;
4523 struct pipe *pipe_list;
4524 int heredoc_cnt = 0;
4526 struct command *command = ctx->command;
4528 debug_printf_parse("parse_group entered\n");
4529 #if ENABLE_HUSH_FUNCTIONS
4530 if (ch == '(' && !ctx->word.has_quoted_part) {
4531 if (ctx->word.length)
4535 goto skip; /* (... */
4536 if (command->argv[1]) { /* word word ... (... */
4537 syntax_error_unexpected_ch('(');
4540 /* it is "word(..." or "word (..." */
4542 ch = i_getch(input);
4543 while (ch == ' ' || ch == '\t');
4545 syntax_error_unexpected_ch(ch);
4548 nommu_addchr(&ctx->as_string, ch);
4550 ch = i_getch(input);
4551 while (ch == ' ' || ch == '\t' || ch == '\n');
4552 if (ch != '{' && ch != '(') {
4553 syntax_error_unexpected_ch(ch);
4556 nommu_addchr(&ctx->as_string, ch);
4557 command->cmd_type = CMD_FUNCDEF;
4562 #if 0 /* Prevented by caller */
4563 if (command->argv /* word [word]{... */
4564 || ctx->word.length /* word{... */
4565 || ctx->word.has_quoted_part /* ""{... */
4568 debug_printf_parse("parse_group return -1: "
4569 "syntax error, groups and arglists don't mix\n");
4574 IF_HUSH_FUNCTIONS(skip:)
4579 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4580 command->cmd_type = CMD_SUBSHELL;
4582 /* bash does not allow "{echo...", requires whitespace */
4584 if (ch != ' ' && ch != '\t' && ch != '\n'
4585 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4587 syntax_error_unexpected_ch(ch);
4591 ch = i_getch(input);
4592 nommu_addchr(&ctx->as_string, ch);
4596 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4597 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4598 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
4601 o_addstr(&ctx->as_string, as_string);
4604 /* empty ()/{} or parse error? */
4605 if (!pipe_list || pipe_list == ERR_PTR) {
4606 /* parse_stream already emitted error msg */
4609 debug_printf_parse("parse_group return -1: "
4610 "parse_stream returned %p\n", pipe_list);
4614 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4615 command->group_as_string = as_string;
4616 debug_printf_parse("end of group, remembering as:'%s'\n",
4617 command->group_as_string);
4620 #if ENABLE_HUSH_FUNCTIONS
4621 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4622 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4623 struct command *cmd2;
4625 cmd2 = xzalloc(sizeof(*cmd2));
4626 cmd2->cmd_type = CMD_SUBSHELL;
4627 cmd2->group = pipe_list;
4630 cmd2->group_as_string = command->group_as_string;
4631 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4634 pipe_list = new_pipe();
4635 pipe_list->cmds = cmd2;
4636 pipe_list->num_cmds = 1;
4640 command->group = pipe_list;
4642 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4644 /* command remains "open", available for possible redirects */
4648 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4649 /* Subroutines for copying $(...) and `...` things */
4651 static int add_till_single_quote(o_string *dest, struct in_str *input)
4654 int ch = i_getch(input);
4656 syntax_error_unterm_ch('\'');
4664 static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4667 int ch = i_getch(input);
4669 syntax_error_unterm_ch('\'');
4674 o_addqchr(dest, ch);
4677 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4678 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4679 static int add_till_double_quote(o_string *dest, struct in_str *input)
4682 int ch = i_getch(input);
4684 syntax_error_unterm_ch('"');
4689 if (ch == '\\') { /* \x. Copy both chars. */
4691 ch = i_getch(input);
4695 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4700 //if (ch == '$') ...
4703 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4705 * "Within the backquoted style of command substitution, backslash
4706 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4707 * The search for the matching backquote shall be satisfied by the first
4708 * backquote found without a preceding backslash; during this search,
4709 * if a non-escaped backquote is encountered within a shell comment,
4710 * a here-document, an embedded command substitution of the $(command)
4711 * form, or a quoted string, undefined results occur. A single-quoted
4712 * or double-quoted string that begins, but does not end, within the
4713 * "`...`" sequence produces undefined results."
4715 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4717 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4720 int ch = i_getch(input);
4724 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4725 ch = i_getch(input);
4729 && (!in_dquote || ch != '"')
4731 o_addchr(dest, '\\');
4735 syntax_error_unterm_ch('`');
4741 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4742 * quoting and nested ()s.
4743 * "With the $(command) style of command substitution, all characters
4744 * following the open parenthesis to the matching closing parenthesis
4745 * constitute the command. Any valid shell script can be used for command,
4746 * except a script consisting solely of redirections which produces
4747 * unspecified results."
4749 * echo $(echo '(TEST)' BEST) (TEST) BEST
4750 * echo $(echo 'TEST)' BEST) TEST) BEST
4751 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4753 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4754 * can contain arbitrary constructs, just like $(cmd).
4755 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4756 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4758 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4759 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4762 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4763 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4764 char end_char2 = end_ch >> 8;
4766 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4768 #if ENABLE_HUSH_INTERACTIVE
4769 G.promptmode = 1; /* PS2 */
4771 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4774 ch = i_getch(input);
4776 syntax_error_unterm_ch(end_ch);
4780 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4786 /* we look for closing )) of $((EXPR)) */
4787 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4788 i_getch(input); /* eat second ')' */
4793 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
4794 if (ch == '(' || ch == '{') {
4795 ch = (ch == '(' ? ')' : '}');
4796 if (!add_till_closing_bracket(dest, input, ch))
4802 if (!add_till_single_quote(dest, input))
4808 if (!add_till_double_quote(dest, input))
4814 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4820 /* \x. Copy verbatim. Important for \(, \) */
4821 ch = i_getch(input);
4823 syntax_error_unterm_ch(end_ch);
4828 /* "backslash+newline", ignore both */
4829 o_delchr(dest); /* undo insertion of '\' */
4834 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
4838 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
4841 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4843 /* Return code: 0 for OK, 1 for syntax error */
4845 #define parse_dollar(as_string, dest, input, quote_mask) \
4846 parse_dollar(dest, input, quote_mask)
4847 #define as_string NULL
4849 static int parse_dollar(o_string *as_string,
4851 struct in_str *input, unsigned char quote_mask)
4853 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4855 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4858 ch = i_getch(input);
4859 nommu_addchr(as_string, ch);
4861 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4863 debug_printf_parse(": '%c'\n", ch);
4864 o_addchr(dest, ch | quote_mask);
4866 ch = i_peek_and_eat_bkslash_nl(input);
4867 if (!isalnum(ch) && ch != '_') {
4868 /* End of variable name reached */
4871 ch = i_getch(input);
4872 nommu_addchr(as_string, ch);
4874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4875 } else if (isdigit(ch)) {
4877 ch = i_getch(input);
4878 nommu_addchr(as_string, ch);
4879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4880 debug_printf_parse(": '%c'\n", ch);
4881 o_addchr(dest, ch | quote_mask);
4882 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4883 } else switch (ch) {
4885 case '!': /* last bg pid */
4886 case '?': /* last exit code */
4887 case '#': /* number of args */
4888 case '*': /* args */
4889 case '@': /* args */
4890 goto make_one_char_var;
4894 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4896 ch = i_getch(input); /* eat '{' */
4897 nommu_addchr(as_string, ch);
4899 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4900 /* It should be ${?}, or ${#var},
4901 * or even ${?+subst} - operator acting on a special variable,
4902 * or the beginning of variable name.
4905 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4908 syntax_error_unterm_str("${name}");
4909 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4912 nommu_addchr(as_string, ch);
4916 /* It's possible to just call add_till_closing_bracket() at this point.
4917 * However, this regresses some of our testsuite cases
4918 * which check invalid constructs like ${%}.
4919 * Oh well... let's check that the var name part is fine... */
4925 debug_printf_parse(": '%c'\n", ch);
4927 ch = i_getch(input);
4928 nommu_addchr(as_string, ch);
4932 if (!isalnum(ch) && ch != '_') {
4934 unsigned char last_ch;
4935 /* handle parameter expansions
4936 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4938 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4939 if (len_single_ch != '#'
4940 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4941 || i_peek(input) != '}'
4943 goto bad_dollar_syntax;
4945 /* else: it's "length of C" ${#C} op,
4946 * where C is a single char
4947 * special var name, e.g. ${#!}.
4950 /* Eat everything until closing '}' (or ':') */
4954 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4956 /* It's ${var:N[:M]} thing */
4957 end_ch = '}' * 0x100 + ':';
4959 if (BASH_PATTERN_SUBST
4962 /* It's ${var/[/]pattern[/repl]} thing */
4963 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4965 nommu_addchr(as_string, '/');
4968 end_ch = '}' * 0x100 + '/';
4971 /* The pattern can't be empty.
4972 * IOW: if the first char after "${v//" is a slash,
4973 * it does not terminate the pattern - it's the first char of the pattern:
4974 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4975 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4977 if (i_peek(input) == '/') {
4978 o_addchr(dest, i_getch(input));
4983 #if ENABLE_HUSH_DOLLAR_OPS
4984 last_ch = add_till_closing_bracket(dest, input, end_ch);
4985 if (last_ch == 0) /* error? */
4988 #error Simple code to only allow ${var} is not implemented
4991 o_addstr(as_string, dest->data + pos);
4992 o_addchr(as_string, last_ch);
4995 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4996 && (end_ch & 0xff00)
4998 /* close the first block: */
4999 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5000 /* while parsing N from ${var:N[:M]}
5001 * or pattern from ${var/[/]pattern[/repl]} */
5002 if ((end_ch & 0xff) == last_ch) {
5003 /* got ':' or '/'- parse the rest */
5008 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
5009 /* it's ${var:N} - emulate :999999999 */
5010 o_addstr(dest, "999999999");
5011 } /* else: it's ${var/[/]pattern} */
5015 len_single_ch = 0; /* it can't be ${#C} op */
5017 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5020 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
5024 ch = i_getch(input);
5025 nommu_addchr(as_string, ch);
5026 # if ENABLE_FEATURE_SH_MATH
5027 if (i_peek_and_eat_bkslash_nl(input) == '(') {
5028 ch = i_getch(input);
5029 nommu_addchr(as_string, ch);
5030 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5031 o_addchr(dest, /*quote_mask |*/ '+');
5034 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5035 return 0; /* error */
5037 o_addstr(as_string, dest->data + pos);
5038 o_addchr(as_string, ')');
5039 o_addchr(as_string, ')');
5041 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5045 # if ENABLE_HUSH_TICK
5046 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5047 o_addchr(dest, quote_mask | '`');
5050 if (!add_till_closing_bracket(dest, input, ')'))
5051 return 0; /* error */
5053 o_addstr(as_string, dest->data + pos);
5054 o_addchr(as_string, ')');
5056 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5064 /* TODO: $_ and $-: */
5065 /* $_ Shell or shell script name; or last argument of last command
5066 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5067 * but in command's env, set to full pathname used to invoke it */
5068 /* $- Option flags set by set builtin or shell options (-i etc) */
5069 ch = i_getch(input);
5070 nommu_addchr(as_string, ch);
5071 ch = i_peek_and_eat_bkslash_nl(input);
5072 if (isalnum(ch)) { /* it's $_name or $_123 */
5079 o_addQchr(dest, '$');
5081 debug_printf_parse("parse_dollar return 1 (ok)\n");
5087 #define encode_string(as_string, dest, input, dquote_end) \
5088 encode_string(dest, input, dquote_end)
5089 #define as_string NULL
5091 static int encode_string(o_string *as_string,
5093 struct in_str *input,
5100 ch = i_getch(input);
5102 nommu_addchr(as_string, ch);
5103 if (ch == dquote_end) { /* may be only '"' or EOF */
5104 debug_printf_parse("encode_string return 1 (ok)\n");
5107 /* note: can't move it above ch == dquote_end check! */
5109 syntax_error_unterm_ch('"');
5110 return 0; /* error */
5114 next = i_peek(input);
5116 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
5117 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5120 /* Testcase: in interactive shell a file with
5121 * echo "unterminated string\<eof>
5124 syntax_error_unterm_ch('"');
5125 return 0; /* error */
5128 * "The backslash retains its special meaning [in "..."]
5129 * only when followed by one of the following characters:
5130 * $, `, ", \, or <newline>. A double quote may be quoted
5131 * within double quotes by preceding it with a backslash."
5132 * NB: in (unquoted) heredoc, above does not apply to ",
5133 * therefore we check for it by "next == dquote_end" cond.
5135 if (next == dquote_end || strchr("$`\\\n", next)) {
5136 ch = i_getch(input); /* eat next */
5138 goto again; /* skip \<newline> */
5139 } /* else: ch remains == '\\', and we double it below: */
5140 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
5141 nommu_addchr(as_string, ch);
5145 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5146 debug_printf_parse("encode_string return 0: "
5147 "parse_dollar returned 0 (error)\n");
5152 #if ENABLE_HUSH_TICK
5154 //unsigned pos = dest->length;
5155 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5156 o_addchr(dest, 0x80 | '`');
5157 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5158 return 0; /* error */
5159 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5160 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5164 o_addQchr(dest, ch);
5170 * Scan input until EOF or end_trigger char.
5171 * Return a list of pipes to execute, or NULL on EOF
5172 * or if end_trigger character is met.
5173 * On syntax error, exit if shell is not interactive,
5174 * reset parsing machinery and start parsing anew,
5175 * or return ERR_PTR.
5177 static struct pipe *parse_stream(char **pstring,
5178 int *heredoc_cnt_ptr,
5179 struct in_str *input,
5182 struct parse_context ctx;
5185 /* Single-quote triggers a bypass of the main loop until its mate is
5186 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
5188 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5189 end_trigger ? end_trigger : 'X');
5192 initialize_context(&ctx);
5194 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5197 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
5199 /* We used to separate words on $IFS here. This was wrong.
5200 * $IFS is used only for word splitting when $var is expanded,
5201 * here we should use blank chars as separators, not $IFS
5206 const char *is_blank;
5207 const char *is_special;
5211 redir_type redir_style;
5213 ch = i_getch(input);
5214 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5215 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5220 syntax_error_unterm_str("here document");
5223 if (end_trigger == ')') {
5224 syntax_error_unterm_ch('(');
5227 if (end_trigger == '}') {
5228 syntax_error_unterm_ch('{');
5232 if (done_word(&ctx)) {
5235 o_free_and_set_NULL(&ctx.word);
5236 done_pipe(&ctx, PIPE_SEQ);
5238 /* If we got nothing... */
5239 /* (this makes bare "&" cmd a no-op.
5240 * bash says: "syntax error near unexpected token '&'") */
5241 if (pi->num_cmds == 0
5242 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
5248 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
5250 *pstring = ctx.as_string.data;
5252 o_free(&ctx.as_string);
5254 // heredoc_cnt must be 0 here anyway
5255 //if (heredoc_cnt_ptr)
5256 // *heredoc_cnt_ptr = heredoc_cnt;
5258 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5259 debug_printf_parse("parse_stream return %p\n", pi);
5263 /* Handle "'" and "\" first, as they won't play nice with
5264 * i_peek_and_eat_bkslash_nl() anyway:
5272 ch = i_getch(input);
5274 continue; /* drop \<newline>, get next char */
5275 nommu_addchr(&ctx.as_string, '\\');
5276 o_addchr(&ctx.word, '\\');
5278 /* Testcase: eval 'echo Ok\' */
5279 /* bash-4.3.43 was removing backslash,
5280 * but 4.4.19 retains it, most other shells too
5282 continue; /* get next char */
5284 /* Example: echo Hello \2>file
5285 * we need to know that word 2 is quoted
5287 ctx.word.has_quoted_part = 1;
5288 nommu_addchr(&ctx.as_string, ch);
5289 o_addchr(&ctx.word, ch);
5290 continue; /* get next char */
5292 nommu_addchr(&ctx.as_string, ch);
5294 ctx.word.has_quoted_part = 1;
5295 next = i_getch(input);
5296 if (next == '\'' && !ctx.pending_redirect)
5297 goto insert_empty_quoted_str_marker;
5302 syntax_error_unterm_ch('\'');
5305 nommu_addchr(&ctx.as_string, ch);
5308 if (ch == SPECIAL_VAR_SYMBOL) {
5309 /* Convert raw ^C to corresponding special variable reference */
5310 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5311 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5313 o_addqchr(&ctx.word, ch);
5314 ch = i_getch(input);
5316 continue; /* get next char */
5321 next = i_peek_and_eat_bkslash_nl(input);
5323 is_special = "{}<>;&|()#" /* special outside of "str" */
5324 "$\"" IF_HUSH_TICK("`") /* always special */
5325 SPECIAL_VAR_SYMBOL_STR;
5326 /* Are { and } special here? */
5327 if (ctx.command->argv /* word [word]{... - non-special */
5328 || ctx.word.length /* word{... - non-special */
5329 || ctx.word.has_quoted_part /* ""{... - non-special */
5330 || (next != ';' /* }; - special */
5331 && next != ')' /* }) - special */
5332 && next != '(' /* {( - special */
5333 && next != '&' /* }& and }&& ... - special */
5334 && next != '|' /* }|| ... - special */
5335 && !strchr(defifs, next) /* {word - non-special */
5338 /* They are not special, skip "{}" */
5341 is_special = strchr(is_special, ch);
5342 is_blank = strchr(defifs, ch);
5344 if (!is_special && !is_blank) { /* ordinary char */
5346 o_addQchr(&ctx.word, ch);
5347 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5348 || ctx.is_assignment == WORD_IS_KEYWORD)
5350 && is_well_formed_var_name(ctx.word.data, '=')
5352 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5353 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5359 #if ENABLE_HUSH_LINENO_VAR
5361 * "while ...; do<whitespace><newline>
5363 * would think that "cmd" starts in <whitespace> -
5364 * i.e., at the previous line.
5365 * We need to skip all whitespace before newlines.
5367 while (ch != '\n') {
5368 next = i_peek(input);
5369 if (next != ' ' && next != '\t' && next != '\n')
5370 break; /* next char is not ws */
5371 ch = i_getch(input);
5373 /* ch == last eaten whitespace char */
5375 if (done_word(&ctx)) {
5379 /* Is this a case when newline is simply ignored?
5381 * "cmd | <newline> cmd ..."
5382 * "case ... in <newline> word) ..."
5384 if (IS_NULL_CMD(ctx.command)
5385 && ctx.word.length == 0
5386 && !ctx.word.has_quoted_part
5389 /* This newline can be ignored. But...
5390 * Without check #1, interactive shell
5391 * ignores even bare <newline>,
5392 * and shows the continuation prompt:
5393 * ps1_prompt$ <enter>
5394 * ps2> _ <=== wrong, should be ps1
5395 * Without check #2, "cmd & <newline>"
5396 * is similarly mistreated.
5397 * (BTW, this makes "cmd & cmd"
5398 * and "cmd && cmd" non-orthogonal.
5399 * Really, ask yourself, why
5400 * "cmd && <newline>" doesn't start
5401 * cmd but waits for more input?
5402 * The only reason is that it might be
5403 * a "cmd1 && <nl> cmd2 &" construct,
5404 * cmd1 may need to run in BG).
5406 struct pipe *pi = ctx.list_head;
5407 if (pi->num_cmds != 0 /* check #1 */
5408 && pi->followup != PIPE_BG /* check #2 */
5413 /* Treat newline as a command separator. */
5414 done_pipe(&ctx, PIPE_SEQ);
5415 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
5417 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5418 if (heredoc_cnt != 0)
5421 ctx.is_assignment = MAYBE_ASSIGNMENT;
5422 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5424 /* note: if (is_blank) continue;
5425 * will still trigger for us */
5429 /* "cmd}" or "cmd }..." without semicolon or &:
5430 * } is an ordinary char in this case, even inside { cmd; }
5431 * Pathological example: { ""}; } should exec "}" cmd
5434 if (ctx.word.length != 0 /* word} */
5435 || ctx.word.has_quoted_part /* ""} */
5439 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5440 /* Generally, there should be semicolon: "cmd; }"
5441 * However, bash allows to omit it if "cmd" is
5442 * a group. Examples:
5445 * { echo 0 >&2 | { echo 1; } }
5446 * { while false; do :; done }
5447 * { case a in b) ;; esac }
5449 if (ctx.command->group)
5453 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5454 /* Can't be an end of {cmd}, skip the check */
5455 goto skip_end_trigger;
5456 /* else: } does terminate a group */
5459 if (end_trigger && end_trigger == ch
5460 && (ch != ';' || heredoc_cnt == 0)
5461 #if ENABLE_HUSH_CASE
5463 || ctx.ctx_res_w != RES_MATCH
5464 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
5468 if (done_word(&ctx)) {
5471 done_pipe(&ctx, PIPE_SEQ);
5472 ctx.is_assignment = MAYBE_ASSIGNMENT;
5473 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5474 /* Do we sit outside of any if's, loops or case's? */
5476 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5478 o_free_and_set_NULL(&ctx.word);
5480 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5482 *pstring = ctx.as_string.data;
5484 o_free(&ctx.as_string);
5486 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5487 /* Example: bare "{ }", "()" */
5488 G.last_exitcode = 2; /* bash compat */
5489 syntax_error_unexpected_ch(ch);
5492 if (heredoc_cnt_ptr)
5493 *heredoc_cnt_ptr = heredoc_cnt;
5494 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5495 debug_printf_parse("parse_stream return %p: "
5496 "end_trigger char found\n",
5499 return ctx.list_head;
5506 /* Catch <, > before deciding whether this word is
5507 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5510 redir_fd = redirect_opt_num(&ctx.word);
5511 if (done_word(&ctx)) {
5514 redir_style = REDIRECT_OVERWRITE;
5516 redir_style = REDIRECT_APPEND;
5517 ch = i_getch(input);
5518 nommu_addchr(&ctx.as_string, ch);
5521 else if (next == '(') {
5522 syntax_error(">(process) not supported");
5526 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5528 continue; /* get next char */
5530 redir_fd = redirect_opt_num(&ctx.word);
5531 if (done_word(&ctx)) {
5534 redir_style = REDIRECT_INPUT;
5536 redir_style = REDIRECT_HEREDOC;
5538 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
5539 ch = i_getch(input);
5540 nommu_addchr(&ctx.as_string, ch);
5541 } else if (next == '>') {
5542 redir_style = REDIRECT_IO;
5543 ch = i_getch(input);
5544 nommu_addchr(&ctx.as_string, ch);
5547 else if (next == '(') {
5548 syntax_error("<(process) not supported");
5552 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5554 continue; /* get next char */
5556 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
5557 /* skip "#comment" */
5558 /* note: we do not add it to &ctx.as_string */
5560 * comment inside $() goes to the next \n, even inside quoted string (!):
5561 * cmd "$(cmd2 #comment)" - syntax error
5562 * cmd "`cmd2 #comment`" - ok
5563 * We accept both (comment ends where command subst ends, in both cases).
5568 nommu_addchr(&ctx.as_string, '\n');
5571 ch = i_getch(input);
5575 continue; /* get next char */
5581 if (ctx.is_assignment == MAYBE_ASSIGNMENT
5582 /* check that we are not in word in "a=1 2>word b=1": */
5583 && !ctx.pending_redirect
5585 /* ch is a special char and thus this word
5586 * cannot be an assignment */
5587 ctx.is_assignment = NOT_ASSIGNMENT;
5588 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5591 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5594 case SPECIAL_VAR_SYMBOL:
5595 /* Convert raw ^C to corresponding special variable reference */
5596 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5597 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5600 /* non-comment #: "echo a#b" etc */
5601 o_addchr(&ctx.word, ch);
5602 continue; /* get next char */
5604 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
5605 debug_printf_parse("parse_stream parse error: "
5606 "parse_dollar returned 0 (error)\n");
5609 continue; /* get next char */
5611 ctx.word.has_quoted_part = 1;
5612 if (next == '"' && !ctx.pending_redirect) {
5613 i_getch(input); /* eat second " */
5614 insert_empty_quoted_str_marker:
5615 nommu_addchr(&ctx.as_string, next);
5616 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5617 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5618 continue; /* get next char */
5620 if (ctx.is_assignment == NOT_ASSIGNMENT)
5621 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5622 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
5624 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5625 continue; /* get next char */
5626 #if ENABLE_HUSH_TICK
5628 USE_FOR_NOMMU(unsigned pos;)
5630 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5631 o_addchr(&ctx.word, '`');
5632 USE_FOR_NOMMU(pos = ctx.word.length;)
5633 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
5636 o_addstr(&ctx.as_string, ctx.word.data + pos);
5637 o_addchr(&ctx.as_string, '`');
5639 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5640 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
5641 continue; /* get next char */
5645 #if ENABLE_HUSH_CASE
5648 if (done_word(&ctx)) {
5651 done_pipe(&ctx, PIPE_SEQ);
5652 #if ENABLE_HUSH_CASE
5653 /* Eat multiple semicolons, detect
5654 * whether it means something special */
5656 ch = i_peek_and_eat_bkslash_nl(input);
5659 ch = i_getch(input);
5660 nommu_addchr(&ctx.as_string, ch);
5661 if (ctx.ctx_res_w == RES_CASE_BODY) {
5662 ctx.ctx_dsemicolon = 1;
5663 ctx.ctx_res_w = RES_MATCH;
5669 /* We just finished a cmd. New one may start
5670 * with an assignment */
5671 ctx.is_assignment = MAYBE_ASSIGNMENT;
5672 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5673 continue; /* get next char */
5675 if (done_word(&ctx)) {
5679 ch = i_getch(input);
5680 nommu_addchr(&ctx.as_string, ch);
5681 done_pipe(&ctx, PIPE_AND);
5683 done_pipe(&ctx, PIPE_BG);
5687 if (done_word(&ctx)) {
5690 #if ENABLE_HUSH_CASE
5691 if (ctx.ctx_res_w == RES_MATCH)
5692 break; /* we are in case's "word | word)" */
5694 if (next == '|') { /* || */
5695 ch = i_getch(input);
5696 nommu_addchr(&ctx.as_string, ch);
5697 done_pipe(&ctx, PIPE_OR);
5699 /* we could pick up a file descriptor choice here
5700 * with redirect_opt_num(), but bash doesn't do it.
5701 * "echo foo 2| cat" yields "foo 2". */
5706 #if ENABLE_HUSH_CASE
5707 /* "case... in [(]word)..." - skip '(' */
5708 if (ctx.ctx_res_w == RES_MATCH
5709 && ctx.command->argv == NULL /* not (word|(... */
5710 && ctx.word.length == 0 /* not word(... */
5711 && ctx.word.has_quoted_part == 0 /* not ""(... */
5713 continue; /* get next char */
5718 int n = parse_group(&ctx, input, ch);
5722 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5727 #if ENABLE_HUSH_CASE
5728 if (ctx.ctx_res_w == RES_MATCH)
5733 /* proper use of this character is caught by end_trigger:
5734 * if we see {, we call parse_group(..., end_trigger='}')
5735 * and it will match } earlier (not here). */
5736 G.last_exitcode = 2;
5737 syntax_error_unexpected_ch(ch);
5741 bb_error_msg_and_die("BUG: unexpected %c", ch);
5746 G.last_exitcode = 1;
5749 struct parse_context *pctx;
5750 IF_HAS_KEYWORDS(struct parse_context *p2;)
5752 /* Clean up allocated tree.
5753 * Sample for finding leaks on syntax error recovery path.
5754 * Run it from interactive shell, watch pmap `pidof hush`.
5755 * while if false; then false; fi; do break; fi
5756 * Samples to catch leaks at execution:
5757 * while if (true | { true;}); then echo ok; fi; do break; done
5758 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5762 /* Update pipe/command counts,
5763 * otherwise freeing may miss some */
5764 done_pipe(pctx, PIPE_SEQ);
5765 debug_printf_clean("freeing list %p from ctx %p\n",
5766 pctx->list_head, pctx);
5767 debug_print_tree(pctx->list_head, 0);
5768 free_pipe_list(pctx->list_head);
5769 debug_printf_clean("freed list %p\n", pctx->list_head);
5771 o_free(&pctx->as_string);
5773 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5777 IF_HAS_KEYWORDS(pctx = p2;)
5778 } while (HAS_KEYWORDS && pctx);
5791 /*** Execution routines ***/
5793 /* Expansion can recurse, need forward decls: */
5794 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5795 #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
5796 expand_string_to_string(str)
5798 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
5799 #if ENABLE_HUSH_TICK
5800 static int process_command_subs(o_string *dest, const char *s);
5802 static int expand_vars_to_list(o_string *output, int n, char *arg);
5804 /* expand_strvec_to_strvec() takes a list of strings, expands
5805 * all variable references within and returns a pointer to
5806 * a list of expanded strings, possibly with larger number
5807 * of strings. (Think VAR="a b"; echo $VAR).
5808 * This new list is allocated as a single malloc block.
5809 * NULL-terminated list of char* pointers is at the beginning of it,
5810 * followed by strings themselves.
5811 * Caller can deallocate entire list by single free(list). */
5813 /* A horde of its helpers come first: */
5815 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5817 while (--len >= 0) {
5820 #if ENABLE_HUSH_BRACE_EXPANSION
5821 if (c == '{' || c == '}') {
5822 /* { -> \{, } -> \} */
5824 /* And now we want to add { or } and continue:
5827 * luckily, just falling through achieves this.
5833 /* \z -> \\\z; \<eol> -> \\<eol> */
5838 o_addchr(o, *str++);
5844 /* Store given string, finalizing the word and starting new one whenever
5845 * we encounter IFS char(s). This is used for expanding variable values.
5846 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5847 * Return in output->ended_in_ifs:
5848 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5850 static int expand_on_ifs(o_string *output, int n, const char *str)
5852 int last_is_ifs = 0;
5857 if (!*str) /* EOL - do not finalize word */
5859 word_len = strcspn(str, G.ifs);
5861 /* We have WORD_LEN leading non-IFS chars */
5862 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5863 o_addblock(output, str, word_len);
5865 /* Protect backslashes against globbing up :)
5866 * Example: "v='\*'; echo b$v" prints "b\*"
5867 * (and does not try to glob on "*")
5869 o_addblock_duplicate_backslash(output, str, word_len);
5870 /*/ Why can't we do it easier? */
5871 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5872 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5876 if (!*str) /* EOL - do not finalize word */
5880 /* We know str here points to at least one IFS char */
5882 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
5883 if (!*str) /* EOL - do not finalize word */
5886 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5887 && strchr(G.ifs, *str) /* the second check would fail */
5889 /* This is a non-whitespace $IFS char */
5890 /* Skip it and IFS whitespace chars, start new word */
5892 str += strspn(str, G.ifs_whitespace);
5896 /* Start new word... but not always! */
5897 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5898 if (output->has_quoted_part
5900 * Case "v=' a'; echo $v":
5901 * here nothing precedes the space in $v expansion,
5902 * therefore we should not finish the word
5903 * (IOW: if there *is* word to finalize, only then do it):
5904 * It's okay if this accesses the byte before first argv[]:
5905 * past call to o_save_ptr() cleared it to zero byte
5906 * (grep for -prev-ifs-check-).
5908 || output->data[output->length - 1]
5911 o_addchr(output, '\0');
5912 debug_print_list("expand_on_ifs", output, n);
5913 n = o_save_ptr(output, n);
5917 output->ended_in_ifs = last_is_ifs;
5918 debug_print_list("expand_on_ifs[1]", output, n);
5922 /* Helper to expand $((...)) and heredoc body. These act as if
5923 * they are in double quotes, with the exception that they are not :).
5924 * Just the rules are similar: "expand only $var and `cmd`"
5926 * Returns malloced string.
5927 * As an optimization, we return NULL if expansion is not needed.
5929 static char *encode_then_expand_string(const char *str)
5932 struct in_str input;
5933 o_string dest = NULL_O_STRING;
5938 if (!*cp) return NULL; /* string has no special chars */
5939 if (*cp == '$') break;
5940 if (*cp == '\\') break;
5941 #if ENABLE_HUSH_TICK
5942 if (*cp == '`') break;
5947 /* We need to expand. Example:
5948 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5950 setup_string_in_str(&input, str);
5951 encode_string(NULL, &dest, &input, EOF);
5952 //TODO: error check (encode_string returns 0 on error)?
5953 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5954 exp_str = expand_string_to_string(dest.data,
5955 EXP_FLAG_ESC_GLOB_CHARS,
5958 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5963 static const char *first_special_char_in_vararg(const char *cp)
5966 if (!*cp) return NULL; /* string has no special chars */
5967 if (*cp == '$') return cp;
5968 if (*cp == '\\') return cp;
5969 if (*cp == '\'') return cp;
5970 if (*cp == '"') return cp;
5971 #if ENABLE_HUSH_TICK
5972 if (*cp == '`') return cp;
5974 /* dquoted "${x:+ARG}" should not glob, therefore
5975 * '*' et al require some non-literal processing: */
5976 if (*cp == '*') return cp;
5977 if (*cp == '?') return cp;
5978 if (*cp == '[') return cp;
5983 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5984 * These can contain single- and double-quoted strings,
5985 * and treated as if the ARG string is initially unquoted. IOW:
5986 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5987 * a dquoted string: "${var#"zz"}"), the difference only comes later
5988 * (word splitting and globbing of the ${var...} result).
5990 #if !BASH_PATTERN_SUBST
5991 #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5992 encode_then_expand_vararg(str, handle_squotes)
5994 static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5996 #if !BASH_PATTERN_SUBST
5997 const int do_unbackslash = 0;
6000 struct in_str input;
6001 o_string dest = NULL_O_STRING;
6003 if (!first_special_char_in_vararg(str)) {
6004 /* string has no special chars */
6008 setup_string_in_str(&input, str);
6009 dest.data = xzalloc(1); /* start as "", not as NULL */
6015 ch = i_getch(&input);
6016 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6017 __func__, ch, ch, !!dest.o_expflags);
6019 if (!dest.o_expflags) {
6022 if (handle_squotes && ch == '\'') {
6023 if (!add_till_single_quote_dquoted(&dest, &input))
6024 goto ret; /* error */
6029 syntax_error_unterm_ch('"');
6030 goto ret; /* error */
6033 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6037 ch = i_getch(&input);
6039 //example? error message? syntax_error_unterm_ch('"');
6040 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6043 o_addqchr(&dest, ch);
6047 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6048 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6053 #if ENABLE_HUSH_TICK
6055 //unsigned pos = dest->length;
6056 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6057 o_addchr(&dest, 0x80 | '`');
6058 if (!add_till_backquote(&dest, &input,
6059 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6062 goto ret; /* error */
6064 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6065 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6069 o_addQchr(&dest, ch);
6072 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6073 exp_str = expand_string_to_string(dest.data,
6074 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6078 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
6083 /* Expanding ARG in ${var+ARG}, ${var-ARG}
6085 static int encode_then_append_var_plusminus(o_string *output, int n,
6086 char *str, int dquoted)
6088 struct in_str input;
6089 o_string dest = NULL_O_STRING;
6091 if (!first_special_char_in_vararg(str)
6092 && '\0' == str[strcspn(str, G.ifs)]
6094 /* string has no special chars
6095 * && string has no $IFS chars
6097 return expand_vars_to_list(output, n, str);
6100 setup_string_in_str(&input, str);
6105 ch = i_getch(&input);
6106 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6107 __func__, ch, ch, dest.o_expflags);
6109 if (!dest.o_expflags) {
6112 if (!dquoted && strchr(G.ifs, ch)) {
6113 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6114 * do not assume we are at the start of the word (PREFIX above).
6117 n = expand_vars_to_list(output, n, dest.data);
6118 o_free_and_set_NULL(&dest);
6119 o_addchr(output, '\0');
6120 n = o_save_ptr(output, n); /* create next word */
6122 if (output->length != o_get_last_ptr(output, n)
6123 || output->has_quoted_part
6126 * f() { for i; do echo "|$i|"; done; }; x=x
6127 * f a${x:+ }b # 1st condition
6130 * f ""${x:+ }b # 2nd condition
6134 o_addchr(output, '\0');
6135 n = o_save_ptr(output, n); /* create next word */
6139 if (!dquoted && ch == '\'') {
6140 if (!add_till_single_quote_dquoted(&dest, &input))
6141 goto ret; /* error */
6142 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6143 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6148 syntax_error_unterm_ch('"');
6149 goto ret; /* error */
6152 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6153 if (dest.o_expflags) {
6154 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6155 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6160 ch = i_getch(&input);
6162 //example? error message? syntax_error_unterm_ch('"');
6163 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6166 o_addqchr(&dest, ch);
6170 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6171 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6176 #if ENABLE_HUSH_TICK
6178 //unsigned pos = dest->length;
6179 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6180 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6181 if (!add_till_backquote(&dest, &input,
6182 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6185 goto ret; /* error */
6187 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6188 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6193 /* Always glob-protect if in dquotes:
6194 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6195 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6197 o_addqchr(&dest, ch);
6199 /* Glob-protect only if char is quoted:
6200 * x=x; echo ${x:+/bin/c*} - prints many filenames
6201 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6203 o_addQchr(&dest, ch);
6208 n = expand_vars_to_list(output, n, dest.data);
6215 #if ENABLE_FEATURE_SH_MATH
6216 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
6218 arith_state_t math_state;
6222 math_state.lookupvar = get_local_var_value;
6223 math_state.setvar = set_local_var_from_halves;
6224 //math_state.endofname = endofname;
6225 exp_str = encode_then_expand_string(arg);
6226 res = arith(&math_state, exp_str ? exp_str : arg);
6229 *errmsg_p = math_state.errmsg;
6230 if (math_state.errmsg)
6231 msg_and_die_if_script(math_state.errmsg);
6236 #if BASH_PATTERN_SUBST
6237 /* ${var/[/]pattern[/repl]} helpers */
6238 static char *strstr_pattern(char *val, const char *pattern, int *size)
6241 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6242 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6249 /* Optimization: if "*pat" did not match the start of "string",
6250 * we know that "tring", "ring" etc will not match too:
6252 if (pattern[0] == '*')
6257 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6259 char *result = NULL;
6260 unsigned res_len = 0;
6261 unsigned repl_len = strlen(repl);
6263 /* Null pattern never matches, including if "var" is empty */
6265 return result; /* NULL, no replaces happened */
6269 char *s = strstr_pattern(val, pattern, &size);
6273 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
6274 strcpy(mempcpy(result + res_len, val, s - val), repl);
6275 res_len += (s - val) + repl_len;
6276 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6282 if (*val && result) {
6283 result = xrealloc(result, res_len + strlen(val) + 1);
6284 strcpy(result + res_len, val);
6285 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6287 debug_printf_varexp("result:'%s'\n", result);
6290 #endif /* BASH_PATTERN_SUBST */
6292 static int append_str_maybe_ifs_split(o_string *output, int n,
6293 int first_ch, const char *val)
6295 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6296 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6297 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6299 n = expand_on_ifs(output, n, val);
6300 } else { /* quoted "$VAR" */
6301 output->has_quoted_part = 1;
6302 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6303 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6305 o_addQstr(output, val);
6310 /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6312 static NOINLINE int expand_one_var(o_string *output, int n,
6313 int first_ch, char *arg, char **pp)
6320 char exp_save = exp_save; /* for compiler */
6321 char *exp_saveptr; /* points to expansion operator */
6322 char *exp_word = exp_word; /* for compiler */
6328 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
6330 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
6332 arg[0] = (arg0 & 0x7f);
6335 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
6336 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6337 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6338 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
6340 /* It must be length operator: ${#var} */
6344 /* Maybe handle parameter expansion */
6345 if (exp_saveptr /* if 2nd char is one of expansion operators */
6346 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
6348 /* ${?:0}, ${#[:]%0} etc */
6349 exp_saveptr = var + 1;
6351 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6352 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6354 exp_op = exp_save = *exp_saveptr;
6356 exp_word = exp_saveptr + 1;
6357 if (exp_op == ':') {
6358 exp_op = *exp_word++;
6359 //TODO: try ${var:} and ${var:bogus} in non-bash config
6361 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
6363 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6368 *exp_saveptr = '\0';
6369 } /* else: it's not an expansion op, but bare ${var} */
6372 /* Look up the variable in question */
6373 if (isdigit(var[0])) {
6374 /* parse_dollar should have vetted var for us */
6375 int nn = xatoi_positive(var);
6376 if (nn < G.global_argc)
6377 val = G.global_argv[nn];
6378 /* else val remains NULL: $N with too big N */
6382 val = utoa(G.root_pid);
6384 case '!': /* bg pid */
6385 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6387 case '?': /* exitcode */
6388 val = utoa(G.last_exitcode);
6390 case '#': /* argc */
6391 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6394 val = get_local_var_value(var);
6398 /* Handle any expansions */
6399 if (exp_op == 'L') {
6400 reinit_unicode_for_hush();
6401 debug_printf_expand("expand: length(%s)=", val);
6402 val = utoa(val ? unicode_strlen(val) : 0);
6403 debug_printf_expand("%s\n", val);
6404 } else if (exp_op) {
6405 if (exp_op == '%' || exp_op == '#') {
6406 /* Standard-mandated substring removal ops:
6407 * ${parameter%word} - remove smallest suffix pattern
6408 * ${parameter%%word} - remove largest suffix pattern
6409 * ${parameter#word} - remove smallest prefix pattern
6410 * ${parameter##word} - remove largest prefix pattern
6412 * Word is expanded to produce a glob pattern.
6413 * Then var's value is matched to it and matching part removed.
6415 //FIXME: ${x#...${...}...}
6416 //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6417 //inner ${...} may have side effects!
6418 if (val && val[0]) {
6422 unsigned scan_flags = pick_scan(exp_op, *exp_word);
6423 if (exp_op == *exp_word) /* ## or %% */
6425 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6426 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6428 exp_word = exp_exp_word;
6429 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6431 * HACK ALERT. We depend here on the fact that
6432 * G.global_argv and results of utoa and get_local_var_value
6433 * are actually in writable memory:
6434 * scan_and_match momentarily stores NULs there.
6437 loc = scan_and_match(t, exp_word, scan_flags);
6438 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
6440 if (loc) { /* match was found */
6441 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
6442 val = loc; /* take right part */
6444 val = to_be_freed = xstrndup(val, loc - val); /* left */
6448 #if BASH_PATTERN_SUBST
6449 else if (exp_op == '/' || exp_op == '\\') {
6450 /* It's ${var/[/]pattern[/repl]} thing.
6451 * Note that in encoded form it has TWO parts:
6452 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6453 * and if // is used, it is encoded as \:
6454 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6456 if (val && val[0]) {
6457 /* pattern uses non-standard expansion.
6458 * repl should be unbackslashed and globbed
6459 * by the usual expansion rules:
6461 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6462 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6463 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6464 * v='a bz'; echo ${v/a*z/\z} #prints "z"
6465 * (note that a*z _pattern_ is never globbed!)
6467 char *pattern, *repl, *t;
6468 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6470 pattern = xstrdup(exp_word);
6471 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6472 *p++ = SPECIAL_VAR_SYMBOL;
6474 p = strchr(p, SPECIAL_VAR_SYMBOL);
6476 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
6477 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6478 /* HACK ALERT. We depend here on the fact that
6479 * G.global_argv and results of utoa and get_local_var_value
6480 * are actually in writable memory:
6481 * replace_pattern momentarily stores NULs there. */
6483 to_be_freed = replace_pattern(t,
6485 (repl ? repl : exp_word),
6487 if (to_be_freed) /* at least one replace happened */
6492 /* Empty variable always gives nothing */
6493 // "v=''; echo ${v/*/w}" prints "", not "w"
6494 /* Just skip "replace" part */
6495 *p++ = SPECIAL_VAR_SYMBOL;
6496 p = strchr(p, SPECIAL_VAR_SYMBOL);
6500 #endif /* BASH_PATTERN_SUBST */
6501 else if (exp_op == ':') {
6502 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
6503 /* It's ${var:N[:M]} bashism.
6504 * Note that in encoded form it has TWO parts:
6505 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6510 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6513 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6514 *p++ = SPECIAL_VAR_SYMBOL;
6516 p = strchr(p, SPECIAL_VAR_SYMBOL);
6518 len = expand_and_evaluate_arith(exp_word, &errmsg);
6521 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
6523 /* negative beg counts from the end */
6524 beg = (arith_t)strlen(val) + beg;
6525 if (beg < 0) /* ${v: -999999} is "" */
6528 debug_printf_varexp("from val:'%s'\n", val);
6530 /* in bash, len=-n means strlen()-n */
6531 len = (arith_t)strlen(val) - beg + len;
6532 if (len < 0) /* bash compat */
6533 msg_and_die_if_script("%s: substring expression < 0", var);
6535 if (len <= 0 || !val || beg >= strlen(val)) {
6539 /* Paranoia. What if user entered 9999999999999
6540 * which fits in arith_t but not int? */
6543 val = to_be_freed = xstrndup(val + beg, len);
6545 debug_printf_varexp("val:'%s'\n", val);
6546 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
6547 msg_and_die_if_script("malformed ${%s:...}", var);
6550 } else { /* one of "-=+?" */
6551 /* Standard-mandated substitution ops:
6552 * ${var?word} - indicate error if unset
6553 * If var is unset, word (or a message indicating it is unset
6554 * if word is null) is written to standard error
6555 * and the shell exits with a non-zero exit status.
6556 * Otherwise, the value of var is substituted.
6557 * ${var-word} - use default value
6558 * If var is unset, word is substituted.
6559 * ${var=word} - assign and use default value
6560 * If var is unset, word is assigned to var.
6561 * In all cases, final value of var is substituted.
6562 * ${var+word} - use alternative value
6563 * If var is unset, null is substituted.
6564 * Otherwise, word is substituted.
6566 * Word is subjected to tilde expansion, parameter expansion,
6567 * command substitution, and arithmetic expansion.
6568 * If word is not needed, it is not expanded.
6570 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6571 * but also treat null var as if it is unset.
6573 * Word-splitting and single quote behavior:
6575 * $ f() { for i; do echo "|$i|"; done; };
6577 * $ x=; f ${x:?'x y' z}
6578 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6579 * $ x=; f "${x:?'x y' z}"
6580 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6582 * $ x=; f ${x:='x y' z}
6586 * $ x=; f "${x:='x y' z}"
6589 * $ x=x; f ${x:+'x y' z}
6592 * $ x=x; f "${x:+'x y' z}"
6595 * $ x=; f ${x:-'x y' z}
6598 * $ x=; f "${x:-'x y' z}"
6601 int use_word = (!val || ((exp_save == ':') && !val[0]));
6603 use_word = !use_word;
6604 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6605 (exp_save == ':') ? "true" : "false", use_word);
6607 if (exp_op == '+' || exp_op == '-') {
6608 /* ${var+word} - use alternative value */
6609 /* ${var-word} - use default value */
6610 n = encode_then_append_var_plusminus(output, n, exp_word,
6611 /*dquoted:*/ (arg0 & 0x80)
6615 /* ${var?word} - indicate error if unset */
6616 /* ${var=word} - assign and use default value */
6617 to_be_freed = encode_then_expand_vararg(exp_word,
6618 /*handle_squotes:*/ !(arg0 & 0x80),
6622 exp_word = to_be_freed;
6623 if (exp_op == '?') {
6624 /* mimic bash message */
6625 msg_and_die_if_script("%s: %s",
6629 : "parameter null or not set"
6630 /* ash has more specific messages, a-la: */
6631 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6633 //TODO: how interactive bash aborts expansion mid-command?
6634 //It aborts the entire line, returns to prompt:
6635 // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6638 // ("echo YO" is not executed, neither the f function call)
6642 if (exp_op == '=') {
6643 /* ${var=[word]} or ${var:=[word]} */
6644 if (isdigit(var[0]) || var[0] == '#') {
6645 /* mimic bash message */
6646 msg_and_die_if_script("$%s: cannot assign in this way", var);
6649 char *new_var = xasprintf("%s=%s", var, val);
6650 set_local_var(new_var, /*flag:*/ 0);
6655 } /* one of "-=+?" */
6657 *exp_saveptr = exp_save;
6663 n = append_str_maybe_ifs_split(output, n, first_ch, val);
6669 /* Expand all variable references in given string, adding words to list[]
6670 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6671 * to be filled). This routine is extremely tricky: has to deal with
6672 * variables/parameters with whitespace, $* and $@, and constructs like
6673 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
6674 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
6676 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
6677 * expansion of right-hand side of assignment == 1-element expand.
6679 char cant_be_null = 0; /* only bit 0x80 matters */
6682 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6683 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
6684 debug_print_list("expand_vars_to_list[0]", output, n);
6686 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6688 #if ENABLE_FEATURE_SH_MATH
6689 char arith_buf[sizeof(arith_t)*3 + 2];
6692 if (output->ended_in_ifs) {
6693 o_addchr(output, '\0');
6694 n = o_save_ptr(output, n);
6695 output->ended_in_ifs = 0;
6698 o_addblock(output, arg, p - arg);
6699 debug_print_list("expand_vars_to_list[1]", output, n);
6701 p = strchr(p, SPECIAL_VAR_SYMBOL);
6703 /* Fetch special var name (if it is indeed one of them)
6704 * and quote bit, force the bit on if singleword expansion -
6705 * important for not getting v=$@ expand to many words. */
6706 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6708 /* Is this variable quoted and thus expansion can't be null?
6709 * "$@" is special. Even if quoted, it can still
6710 * expand to nothing (not even an empty string),
6711 * thus it is excluded. */
6712 if ((first_ch & 0x7f) != '@')
6713 cant_be_null |= first_ch;
6715 switch (first_ch & 0x7f) {
6716 /* Highest bit in first_ch indicates that var is double-quoted */
6720 if (!G.global_argv[1])
6723 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6724 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6725 while (G.global_argv[i]) {
6726 n = expand_on_ifs(output, n, G.global_argv[i]);
6727 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6728 if (G.global_argv[i++][0] && G.global_argv[i]) {
6729 /* this argv[] is not empty and not last:
6730 * put terminating NUL, start new word */
6731 o_addchr(output, '\0');
6732 debug_print_list("expand_vars_to_list[2]", output, n);
6733 n = o_save_ptr(output, n);
6734 debug_print_list("expand_vars_to_list[3]", output, n);
6738 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6739 * and in this case should treat it like '$*' - see 'else...' below */
6740 if (first_ch == (char)('@'|0x80) /* quoted $@ */
6741 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6744 o_addQstr(output, G.global_argv[i]);
6745 if (++i >= G.global_argc)
6747 o_addchr(output, '\0');
6748 debug_print_list("expand_vars_to_list[4]", output, n);
6749 n = o_save_ptr(output, n);
6751 } else { /* quoted $* (or v="$@" case): add as one word */
6753 o_addQstr(output, G.global_argv[i]);
6754 if (!G.global_argv[++i])
6757 o_addchr(output, G.ifs[0]);
6759 output->has_quoted_part = 1;
6763 case SPECIAL_VAR_SYMBOL: {
6764 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6765 /* "Empty variable", used to make "" etc to not disappear */
6766 output->has_quoted_part = 1;
6767 cant_be_null = 0x80;
6771 case SPECIAL_VAR_QUOTED_SVS:
6772 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6773 /* "^C variable", represents literal ^C char (possible in scripts) */
6774 o_addchr(output, SPECIAL_VAR_SYMBOL);
6777 #if ENABLE_HUSH_TICK
6779 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6780 o_string subst_result = NULL_O_STRING;
6782 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6784 /* Can't just stuff it into output o_string,
6785 * expanded result may need to be globbed
6787 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6788 G.last_exitcode = process_command_subs(&subst_result, arg);
6789 G.expand_exitcode = G.last_exitcode;
6790 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6791 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
6792 o_free(&subst_result);
6796 #if ENABLE_FEATURE_SH_MATH
6798 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
6801 arg++; /* skip '+' */
6802 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6803 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6804 res = expand_and_evaluate_arith(arg, NULL);
6805 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6806 sprintf(arith_buf, ARITH_FMT, res);
6807 o_addstr(output, arith_buf);
6812 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
6813 n = expand_one_var(output, n, first_ch, arg, &p);
6815 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6817 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6818 * Do the check to avoid writing to a const string. */
6819 if (*p != SPECIAL_VAR_SYMBOL)
6820 *p = SPECIAL_VAR_SYMBOL;
6822 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6825 /* handle trailing string */
6826 if (output->ended_in_ifs) {
6827 o_addchr(output, '\0');
6828 n = o_save_ptr(output, n);
6830 debug_print_list("expand_vars_to_list[a]", output, n);
6831 /* this part is literal, and it was already pre-quoted
6832 * if needed (much earlier), do not use o_addQstr here!
6834 o_addstr(output, arg);
6835 debug_print_list("expand_vars_to_list[b]", output, n);
6837 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6838 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6839 && !output->has_quoted_part
6842 /* allow to reuse list[n] later without re-growth */
6843 output->has_empty_slot = 1;
6849 static char **expand_variables(char **argv, unsigned expflags)
6853 o_string output = NULL_O_STRING;
6855 output.o_expflags = expflags;
6859 /* go to next list[n] */
6860 output.ended_in_ifs = 0;
6861 n = o_save_ptr(&output, n);
6866 /* expand argv[i] */
6867 n = expand_vars_to_list(&output, n, *argv++);
6868 /* if (!output->has_empty_slot) -- need this?? */
6869 o_addchr(&output, '\0');
6871 debug_print_list("expand_variables", &output, n);
6873 /* output.data (malloced in one block) gets returned in "list" */
6874 list = o_finalize_list(&output, n);
6875 debug_print_strings("expand_variables[1]", list);
6879 static char **expand_strvec_to_strvec(char **argv)
6881 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6884 #if defined(CMD_SINGLEWORD_NOGLOB)
6885 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6887 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6891 /* Used for expansion of right hand of assignments,
6892 * $((...)), heredocs, variable expansion parts.
6894 * NB: should NOT do globbing!
6895 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6897 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
6899 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6900 const int do_unbackslash = 1;
6901 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
6903 char *argv[2], **list;
6905 debug_printf_expand("string_to_string<='%s'\n", str);
6906 /* This is generally an optimization, but it also
6907 * handles "", which otherwise trips over !list[0] check below.
6908 * (is this ever happens that we actually get str="" here?)
6910 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6911 //TODO: Can use on strings with \ too, just unbackslash() them?
6912 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6913 return xstrdup(str);
6916 argv[0] = (char*)str;
6918 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
6920 /* Example where it happens:
6921 * x=; echo ${x:-"$@"}
6923 ((char*)list)[0] = '\0';
6927 bb_error_msg_and_die("BUG in varexp2");
6928 /* actually, just move string 2*sizeof(char*) bytes back */
6929 overlapping_strcpy((char*)list, list[0]);
6931 unbackslash((char*)list);
6933 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6938 static char* expand_strvec_to_string(char **argv)
6942 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6943 /* Convert all NULs to spaces */
6948 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6949 bb_error_msg_and_die("BUG in varexp3");
6950 /* bash uses ' ' regardless of $IFS contents */
6955 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6956 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6961 static char **expand_assignments(char **argv, int count)
6966 G.expanded_assignments = p = NULL;
6967 /* Expand assignments into one string each */
6968 for (i = 0; i < count; i++) {
6969 p = add_string_to_strings(p,
6970 expand_string_to_string(argv[i],
6971 EXP_FLAG_ESC_GLOB_CHARS,
6975 G.expanded_assignments = p;
6977 G.expanded_assignments = NULL;
6982 static void switch_off_special_sigs(unsigned mask)
6985 while ((mask >>= 1) != 0) {
6989 #if ENABLE_HUSH_TRAP
6991 if (G_traps[sig] && !G_traps[sig][0])
6992 /* trap is '', has to remain SIG_IGN */
6995 G_traps[sig] = NULL;
6998 /* We are here only if no trap or trap was not '' */
6999 install_sighandler(sig, SIG_DFL);
7005 void re_execute_shell(char ***to_free, const char *s,
7006 char *g_argv0, char **g_argv,
7007 char **builtin_argv) NORETURN;
7009 static void reset_traps_to_defaults(void)
7011 /* This function is always called in a child shell
7012 * after fork (not vfork, NOMMU doesn't use this function).
7014 IF_HUSH_TRAP(unsigned sig;)
7017 /* Child shells are not interactive.
7018 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7019 * Testcase: (while :; do :; done) + ^Z should background.
7020 * Same goes for SIGTERM, SIGHUP, SIGINT.
7022 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
7023 if (!G_traps && !mask)
7024 return; /* already no traps and no special sigs */
7026 /* Switch off special sigs */
7027 switch_off_special_sigs(mask);
7028 # if ENABLE_HUSH_JOB
7029 G_fatal_sig_mask = 0;
7031 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
7032 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7033 * remain set in G.special_sig_mask */
7035 # if ENABLE_HUSH_TRAP
7039 /* Reset all sigs to default except ones with empty traps */
7040 for (sig = 0; sig < NSIG; sig++) {
7042 continue; /* no trap: nothing to do */
7043 if (!G_traps[sig][0])
7044 continue; /* empty trap: has to remain SIG_IGN */
7045 /* sig has non-empty trap, reset it: */
7047 G_traps[sig] = NULL;
7048 /* There is no signal for trap 0 (EXIT) */
7051 install_sighandler(sig, pick_sighandler(sig));
7058 static void re_execute_shell(char ***to_free, const char *s,
7059 char *g_argv0, char **g_argv,
7060 char **builtin_argv) NORETURN;
7061 static void re_execute_shell(char ***to_free, const char *s,
7062 char *g_argv0, char **g_argv,
7063 char **builtin_argv)
7065 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7066 /* delims + 2 * (number of bytes in printed hex numbers) */
7067 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7068 char *heredoc_argv[4];
7069 struct variable *cur;
7070 # if ENABLE_HUSH_FUNCTIONS
7071 struct function *funcp;
7075 unsigned long long empty_trap_mask;
7077 if (!g_argv0) { /* heredoc */
7078 argv = heredoc_argv;
7079 argv[0] = (char *) G.argv0_for_re_execing;
7080 argv[1] = (char *) "-<";
7081 argv[2] = (char *) s;
7083 pp = &argv[3]; /* used as pointer to empty environment */
7089 if (pp) while (*pp++)
7092 empty_trap_mask = 0;
7095 for (sig = 1; sig < NSIG; sig++) {
7096 if (G_traps[sig] && !G_traps[sig][0])
7097 empty_trap_mask |= 1LL << sig;
7101 sprintf(param_buf, NOMMU_HACK_FMT
7102 , (unsigned) G.root_pid
7103 , (unsigned) G.root_ppid
7104 , (unsigned) G.last_bg_pid
7105 , (unsigned) G.last_exitcode
7108 IF_HUSH_LOOPS(, G.depth_of_loop)
7110 # undef NOMMU_HACK_FMT
7111 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7112 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7115 for (cur = G.top_var; cur; cur = cur->next) {
7116 if (!cur->flg_export || cur->flg_read_only)
7119 # if ENABLE_HUSH_FUNCTIONS
7120 for (funcp = G.top_func; funcp; funcp = funcp->next)
7126 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7127 *pp++ = (char *) G.argv0_for_re_execing;
7129 for (cur = G.top_var; cur; cur = cur->next) {
7130 if (strcmp(cur->varstr, hush_version_str) == 0)
7132 if (cur->flg_read_only) {
7133 *pp++ = (char *) "-R";
7134 *pp++ = cur->varstr;
7135 } else if (!cur->flg_export) {
7136 *pp++ = (char *) "-V";
7137 *pp++ = cur->varstr;
7140 # if ENABLE_HUSH_FUNCTIONS
7141 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7142 *pp++ = (char *) "-F";
7143 *pp++ = funcp->name;
7144 *pp++ = funcp->body_as_string;
7147 /* We can pass activated traps here. Say, -Tnn:trap_string
7149 * However, POSIX says that subshells reset signals with traps
7151 * I tested bash-3.2 and it not only does that with true subshells
7152 * of the form ( list ), but with any forked children shells.
7153 * I set trap "echo W" WINCH; and then tried:
7155 * { echo 1; sleep 20; echo 2; } &
7156 * while true; do echo 1; sleep 20; echo 2; break; done &
7157 * true | { echo 1; sleep 20; echo 2; } | cat
7159 * In all these cases sending SIGWINCH to the child shell
7160 * did not run the trap. If I add trap "echo V" WINCH;
7161 * _inside_ group (just before echo 1), it works.
7163 * I conclude it means we don't need to pass active traps here.
7165 *pp++ = (char *) "-c";
7168 while (*++builtin_argv)
7169 *pp++ = *builtin_argv;
7170 *pp++ = (char *) "";
7175 /* *pp = NULL; - is already there */
7179 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
7180 /* Don't propagate SIG_IGN to the child */
7181 if (SPECIAL_JOBSTOP_SIGS != 0)
7182 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7183 execve(bb_busybox_exec_path, argv, pp);
7184 /* Fallback. Useful for init=/bin/hush usage etc */
7185 if (argv[0][0] == '/')
7186 execve(argv[0], argv, pp);
7187 xfunc_error_retval = 127;
7188 bb_error_msg_and_die("can't re-execute the shell");
7190 #endif /* !BB_MMU */
7193 static int run_and_free_list(struct pipe *pi);
7195 /* Executing from string: eval, sh -c '...'
7196 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7197 * end_trigger controls how often we stop parsing
7198 * NUL: parse all, execute, return
7199 * ';': parse till ';' or newline, execute, repeat till EOF
7201 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7203 /* Why we need empty flag?
7204 * An obscure corner case "false; ``; echo $?":
7205 * empty command in `` should still set $? to 0.
7206 * But we can't just set $? to 0 at the start,
7207 * this breaks "false; echo `echo $?`" case.
7211 struct pipe *pipe_list;
7213 #if ENABLE_HUSH_INTERACTIVE
7214 if (end_trigger == ';') {
7215 G.promptmode = 0; /* PS1 */
7216 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7219 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
7220 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7221 /* If we are in "big" script
7222 * (not in `cmd` or something similar)...
7224 if (pipe_list == ERR_PTR && end_trigger == ';') {
7225 /* Discard cached input (rest of line) */
7226 int ch = inp->last_char;
7227 while (ch != EOF && ch != '\n') {
7228 //bb_error_msg("Discarded:'%c'", ch);
7233 /* This stream isn't empty */
7237 if (!pipe_list && empty)
7238 G.last_exitcode = 0;
7241 debug_print_tree(pipe_list, 0);
7242 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7243 run_and_free_list(pipe_list);
7245 if (G_flag_return_in_progress == 1)
7250 static void parse_and_run_string(const char *s)
7252 struct in_str input;
7253 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7255 setup_string_in_str(&input, s);
7256 parse_and_run_stream(&input, '\0');
7257 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
7260 static void parse_and_run_file(HFILE *fp)
7262 struct in_str input;
7263 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7265 IF_HUSH_LINENO_VAR(G.lineno = 1;)
7266 setup_file_in_str(&input, fp);
7267 parse_and_run_stream(&input, ';');
7268 IF_HUSH_LINENO_VAR(G.lineno = sv;)
7271 #if ENABLE_HUSH_TICK
7272 static int generate_stream_from_string(const char *s, pid_t *pid_p)
7277 char **to_free = NULL;
7281 pid = BB_MMU ? xfork() : xvfork();
7282 if (pid == 0) { /* child */
7283 disable_restore_tty_pgrp_on_exit();
7284 /* Process substitution is not considered to be usual
7285 * 'command execution'.
7286 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7293 close(channel[0]); /* NB: close _first_, then move fd! */
7294 xmove_fd(channel[1], 1);
7295 # if ENABLE_HUSH_TRAP
7296 /* Awful hack for `trap` or $(trap).
7298 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7299 * contains an example where "trap" is executed in a subshell:
7301 * save_traps=$(trap)
7303 * eval "$save_traps"
7305 * Standard does not say that "trap" in subshell shall print
7306 * parent shell's traps. It only says that its output
7307 * must have suitable form, but then, in the above example
7308 * (which is not supposed to be normative), it implies that.
7310 * bash (and probably other shell) does implement it
7311 * (traps are reset to defaults, but "trap" still shows them),
7312 * but as a result, "trap" logic is hopelessly messed up:
7315 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7316 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7317 * # true | trap <--- trap is in subshell - no output (ditto)
7318 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7319 * trap -- 'echo Ho' SIGWINCH
7320 * # echo `(trap)` <--- in subshell in subshell - output
7321 * trap -- 'echo Ho' SIGWINCH
7322 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7323 * trap -- 'echo Ho' SIGWINCH
7325 * The rules when to forget and when to not forget traps
7326 * get really complex and nonsensical.
7328 * Our solution: ONLY bare $(trap) or `trap` is special.
7330 s = skip_whitespace(s);
7331 if (is_prefixed_with(s, "trap")
7332 && skip_whitespace(s + 4)[0] == '\0'
7334 static const char *const argv[] = { NULL, NULL };
7335 builtin_trap((char**)argv);
7336 fflush_all(); /* important */
7341 /* Prevent it from trying to handle ctrl-z etc */
7342 IF_HUSH_JOB(G.run_list_level = 1;)
7343 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7344 reset_traps_to_defaults();
7345 IF_HUSH_MODE_X(G.x_mode_depth++;)
7346 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
7347 parse_and_run_string(s);
7348 _exit(G.last_exitcode);
7350 /* We re-execute after vfork on NOMMU. This makes this script safe:
7351 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7352 * huge=`cat BIG` # was blocking here forever
7355 re_execute_shell(&to_free,
7365 # if ENABLE_HUSH_FAST
7367 //bb_error_msg("[%d] fork in generate_stream_from_string:"
7368 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7369 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7371 enable_restore_tty_pgrp_on_exit();
7379 /* Return code is exit status of the process that is run. */
7380 static int process_command_subs(o_string *dest, const char *s)
7384 int status, ch, eol_cnt;
7386 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
7388 /* Now send results of command back into original context */
7390 while ((ch = getc(fp)) != EOF) {
7398 o_addchr(dest, '\n');
7401 o_addQchr(dest, ch);
7404 debug_printf("done reading from `cmd` pipe, closing it\n");
7406 /* We need to extract exitcode. Test case
7407 * "true; echo `sleep 1; false` $?"
7409 safe_waitpid(pid, &status, 0);
7410 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7411 return WEXITSTATUS(status);
7413 #endif /* ENABLE_HUSH_TICK */
7416 static void setup_heredoc(struct redir_struct *redir)
7418 struct fd_pair pair;
7421 /* the _body_ of heredoc (misleading field name) */
7422 const char *heredoc = redir->rd_filename;
7429 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
7430 expanded = encode_then_expand_string(heredoc);
7434 len = strlen(heredoc);
7436 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7438 xmove_fd(pair.rd, redir->rd_fd);
7440 /* Try writing without forking. Newer kernels have
7441 * dynamically growing pipes. Must use non-blocking write! */
7444 written = write(pair.wr, heredoc, len);
7455 ndelay_off(pair.wr);
7457 /* Okay, pipe buffer was not big enough */
7458 /* Note: we must not create a stray child (bastard? :)
7459 * for the unsuspecting parent process. Child creates a grandchild
7460 * and exits before parent execs the process which consumes heredoc
7461 * (that exec happens after we return from this function) */
7468 disable_restore_tty_pgrp_on_exit();
7469 pid = BB_MMU ? xfork() : xvfork();
7473 close(redir->rd_fd); /* read side of the pipe */
7475 full_write(pair.wr, heredoc, len); /* may loop or block */
7478 /* Delegate blocking writes to another process */
7479 xmove_fd(pair.wr, STDOUT_FILENO);
7480 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7484 #if ENABLE_HUSH_FAST
7486 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7488 enable_restore_tty_pgrp_on_exit();
7494 wait(NULL); /* wait till child has died */
7500 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7501 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7504 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7506 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7507 sq[i].orig_fd = orig;
7508 sq[i].moved_to = moved;
7509 sq[i+1].orig_fd = -1; /* end marker */
7513 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7519 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7520 /* If we collide with an already moved fd... */
7521 if (fd == sq[i].moved_to) {
7522 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
7523 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7524 if (sq[i].moved_to < 0) /* what? */
7528 if (fd == sq[i].orig_fd) {
7529 /* Example: echo Hello >/dev/null 1>&2 */
7530 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7535 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
7536 moved_to = dup_CLOEXEC(fd, avoid_fd);
7537 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7538 if (moved_to < 0 && errno != EBADF)
7540 return append_squirrel(sq, i, fd, moved_to);
7543 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7548 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7549 /* If we collide with an already moved fd... */
7550 if (fd == sq[i].orig_fd) {
7552 * "echo 3>FILE 3>&- 3>FILE"
7553 * "echo 3>&- 3>FILE"
7554 * No need for last redirect to insert
7555 * another "need to close 3" indicator.
7557 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7562 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7563 return append_squirrel(sq, i, fd, -1);
7566 /* fd: redirect wants this fd to be used (e.g. 3>file).
7567 * Move all conflicting internally used fds,
7568 * and remember them so that we can restore them later.
7570 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
7572 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7575 #if ENABLE_HUSH_INTERACTIVE
7576 if (fd == G.interactive_fd) {
7577 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
7578 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
7579 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7580 return 1; /* "we closed fd" */
7583 /* Are we called from setup_redirects(squirrel==NULL)
7584 * in redirect in a [v]forked child?
7587 /* No need to move script fds.
7588 * For NOMMU case, it's actively wrong: we'd change ->fd
7589 * fields in memory for the parent, but parent's fds
7590 * aren't be moved, it would use wrong fd!
7591 * Reproducer: "cmd 3>FILE" in script.
7592 * If we would call move_HFILEs_on_redirect(), child would:
7593 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7595 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7597 //bb_error_msg("sqp == NULL: [v]forked child");
7601 /* If this one of script's fds? */
7602 if (move_HFILEs_on_redirect(fd, avoid_fd))
7603 return 1; /* yes. "we closed fd" (actually moved it) */
7605 /* Are we called for "exec 3>FILE"? Came through
7606 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7607 * This case used to fail for this script:
7610 * ...100000 more lines...
7613 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7614 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7616 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7618 * write(1, "Ok\n", 3) = 3
7620 * write(1, "Ok\n", 3) = 3
7621 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7622 * ^^^^^^^^ oops, wrong fd!!!
7623 * With this case separate from sqp == NULL and *after* move_HFILEs,
7626 if (sqp == ERR_PTR) {
7627 /* Don't preserve redirected fds: exec is _meant_ to change these */
7628 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
7632 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7633 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7634 return 0; /* "we did not close fd" */
7637 static void restore_redirects(struct squirrel *sq)
7641 for (i = 0; sq[i].orig_fd >= 0; i++) {
7642 if (sq[i].moved_to >= 0) {
7643 /* We simply die on error */
7644 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7645 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7647 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7648 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7649 close(sq[i].orig_fd);
7655 /* If moved, G.interactive_fd stays on new fd, not restoring it */
7658 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
7659 static void close_saved_fds_and_FILE_fds(void)
7661 if (G_interactive_fd)
7662 close(G_interactive_fd);
7663 close_all_HFILE_list();
7667 static int internally_opened_fd(int fd, struct squirrel *sq)
7671 #if ENABLE_HUSH_INTERACTIVE
7672 if (fd == G.interactive_fd)
7675 /* If this one of script's fds? */
7676 if (fd_in_HFILEs(fd))
7679 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7680 if (fd == sq[i].moved_to)
7686 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
7687 * and stderr if they are redirected. */
7688 static int setup_redirects(struct command *prog, struct squirrel **sqp)
7690 struct redir_struct *redir;
7692 for (redir = prog->redirects; redir; redir = redir->next) {
7696 if (redir->rd_type == REDIRECT_HEREDOC2) {
7697 /* "rd_fd<<HERE" case */
7698 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
7699 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7701 debug_printf_redir("set heredoc '%s'\n",
7702 redir->rd_filename);
7703 setup_heredoc(redir);
7707 if (redir->rd_dup == REDIRFD_TO_FILE) {
7708 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
7712 if (redir->rd_filename == NULL) {
7714 * "cmd >" (no filename)
7715 * "cmd > <file" (2nd redirect starts too early)
7717 syntax_error("invalid redirect");
7720 mode = redir_table[redir->rd_type].mode;
7721 p = expand_string_to_string(redir->rd_filename,
7722 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
7723 newfd = open_or_warn(p, mode);
7726 /* Error message from open_or_warn can be lost
7727 * if stderr has been redirected, but bash
7728 * and ash both lose it as well
7729 * (though zsh doesn't!)
7733 if (newfd == redir->rd_fd && sqp) {
7734 /* open() gave us precisely the fd we wanted.
7735 * This means that this fd was not busy
7736 * (not opened to anywhere).
7737 * Remember to close it on restore:
7739 *sqp = add_squirrel_closed(*sqp, newfd);
7740 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7743 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7744 newfd = redir->rd_dup;
7747 if (newfd == redir->rd_fd)
7750 /* if "N>FILE": move newfd to redir->rd_fd */
7751 /* if "N>&M": dup newfd to redir->rd_fd */
7752 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7754 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7755 if (newfd == REDIRFD_CLOSE) {
7756 /* "N>&-" means "close me" */
7758 /* ^^^ optimization: saving may already
7759 * have closed it. If not... */
7760 close(redir->rd_fd);
7762 /* Sometimes we do another close on restore, getting EBADF.
7763 * Consider "echo 3>FILE 3>&-"
7764 * first redirect remembers "need to close 3",
7765 * and second redirect closes 3! Restore code then closes 3 again.
7768 /* if newfd is a script fd or saved fd, simulate EBADF */
7769 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
7771 //bb_perror_msg_and_die("can't duplicate file descriptor");
7772 newfd = -1; /* same effect as code above */
7774 xdup2(newfd, redir->rd_fd);
7775 if (redir->rd_dup == REDIRFD_TO_FILE)
7776 /* "rd_fd > FILE" */
7778 /* else: "rd_fd > rd_dup" */
7784 static char *find_in_path(const char *arg)
7787 const char *PATH = get_local_var_value("PATH");
7793 const char *end = strchrnul(PATH, ':');
7794 int sz = end - PATH; /* must be int! */
7798 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7800 /* We have xxx::yyyy in $PATH,
7801 * it means "use current dir" */
7804 if (access(ret, F_OK) == 0)
7817 static const struct built_in_command *find_builtin_helper(const char *name,
7818 const struct built_in_command *x,
7819 const struct built_in_command *end)
7822 if (strcmp(name, x->b_cmd) != 0) {
7826 debug_printf_exec("found builtin '%s'\n", name);
7831 static const struct built_in_command *find_builtin1(const char *name)
7833 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7835 static const struct built_in_command *find_builtin(const char *name)
7837 const struct built_in_command *x = find_builtin1(name);
7840 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7843 static void remove_nested_vars(void)
7845 struct variable *cur;
7846 struct variable **cur_pp;
7848 cur_pp = &G.top_var;
7849 while ((cur = *cur_pp) != NULL) {
7850 if (cur->var_nest_level <= G.var_nest_level) {
7851 cur_pp = &cur->next;
7855 if (cur->flg_export) {
7856 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7857 bb_unsetenv(cur->varstr);
7859 /* Remove from global list */
7860 *cur_pp = cur->next;
7862 if (!cur->max_len) {
7863 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7870 static void enter_var_nest_level(void)
7873 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7875 /* Try: f() { echo -n .; f; }; f
7876 * struct variable::var_nest_level is uint16_t,
7877 * thus limiting recursion to < 2^16.
7878 * In any case, with 8 Mbyte stack SEGV happens
7879 * not too long after 2^16 recursions anyway.
7881 if (G.var_nest_level > 0xff00)
7882 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7885 static void leave_var_nest_level(void)
7888 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7889 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7890 bb_error_msg_and_die("BUG: nesting underflow");
7892 remove_nested_vars();
7895 #if ENABLE_HUSH_FUNCTIONS
7896 static struct function **find_function_slot(const char *name)
7898 struct function *funcp;
7899 struct function **funcpp = &G.top_func;
7901 while ((funcp = *funcpp) != NULL) {
7902 if (strcmp(name, funcp->name) == 0) {
7903 debug_printf_exec("found function '%s'\n", name);
7906 funcpp = &funcp->next;
7911 static ALWAYS_INLINE const struct function *find_function(const char *name)
7913 const struct function *funcp = *find_function_slot(name);
7917 /* Note: takes ownership on name ptr */
7918 static struct function *new_function(char *name)
7920 struct function **funcpp = find_function_slot(name);
7921 struct function *funcp = *funcpp;
7923 if (funcp != NULL) {
7924 struct command *cmd = funcp->parent_cmd;
7925 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7927 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7929 /* Note: if !funcp->body, do not free body_as_string!
7930 * This is a special case of "-F name body" function:
7931 * body_as_string was not malloced! */
7933 free_pipe_list(funcp->body);
7935 free(funcp->body_as_string);
7939 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7940 cmd->argv[0] = funcp->name;
7941 cmd->group = funcp->body;
7943 cmd->group_as_string = funcp->body_as_string;
7947 debug_printf_exec("remembering new function '%s'\n", name);
7948 funcp = *funcpp = xzalloc(sizeof(*funcp));
7949 /*funcp->next = NULL;*/
7956 # if ENABLE_HUSH_UNSET
7957 static void unset_func(const char *name)
7959 struct function **funcpp = find_function_slot(name);
7960 struct function *funcp = *funcpp;
7962 if (funcp != NULL) {
7963 debug_printf_exec("freeing function '%s'\n", funcp->name);
7964 *funcpp = funcp->next;
7965 /* funcp is unlinked now, deleting it.
7966 * Note: if !funcp->body, the function was created by
7967 * "-F name body", do not free ->body_as_string
7968 * and ->name as they were not malloced. */
7970 free_pipe_list(funcp->body);
7973 free(funcp->body_as_string);
7982 #define exec_function(to_free, funcp, argv) \
7983 exec_function(funcp, argv)
7985 static void exec_function(char ***to_free,
7986 const struct function *funcp,
7987 char **argv) NORETURN;
7988 static void exec_function(char ***to_free,
7989 const struct function *funcp,
7995 argv[0] = G.global_argv[0];
7996 G.global_argv = argv;
7997 G.global_argc = n = 1 + string_array_len(argv + 1);
7999 // Example when we are here: "cmd | func"
8000 // func will run with saved-redirect fds open.
8001 // $ f() { echo /proc/self/fd/*; }
8003 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8004 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8007 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8008 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8009 // They are CLOEXEC so external programs won't see them, but
8010 // for "more correctness" we might want to close those extra fds here:
8011 //? close_saved_fds_and_FILE_fds();
8013 /* "we are in a function, ok to use return" */
8014 G_flag_return_in_progress = -1;
8015 enter_var_nest_level();
8016 IF_HUSH_LOCAL(G.func_nest_level++;)
8018 /* On MMU, funcp->body is always non-NULL */
8019 n = run_list(funcp->body);
8023 //? close_saved_fds_and_FILE_fds();
8025 //TODO: check whether "true | func_with_return" works
8027 re_execute_shell(to_free,
8028 funcp->body_as_string,
8035 static int run_function(const struct function *funcp, char **argv)
8041 save_and_replace_G_args(&sv, argv);
8043 /* "We are in function, ok to use return" */
8044 sv_flg = G_flag_return_in_progress;
8045 G_flag_return_in_progress = -1;
8047 /* Make "local" variables properly shadow previous ones */
8048 IF_HUSH_LOCAL(enter_var_nest_level();)
8049 IF_HUSH_LOCAL(G.func_nest_level++;)
8051 /* On MMU, funcp->body is always non-NULL */
8054 /* Function defined by -F */
8055 parse_and_run_string(funcp->body_as_string);
8056 rc = G.last_exitcode;
8060 rc = run_list(funcp->body);
8063 IF_HUSH_LOCAL(G.func_nest_level--;)
8064 IF_HUSH_LOCAL(leave_var_nest_level();)
8066 G_flag_return_in_progress = sv_flg;
8068 restore_G_args(&sv, argv);
8072 #endif /* ENABLE_HUSH_FUNCTIONS */
8076 #define exec_builtin(to_free, x, argv) \
8077 exec_builtin(x, argv)
8079 #define exec_builtin(to_free, x, argv) \
8080 exec_builtin(to_free, argv)
8082 static void exec_builtin(char ***to_free,
8083 const struct built_in_command *x,
8084 char **argv) NORETURN;
8085 static void exec_builtin(char ***to_free,
8086 const struct built_in_command *x,
8092 //? close_saved_fds_and_FILE_fds();
8093 rcode = x->b_function(argv);
8098 /* On NOMMU, we must never block!
8099 * Example: { sleep 99 | read line; } & echo Ok
8101 re_execute_shell(to_free,
8110 static void execvp_or_die(char **argv) NORETURN;
8111 static void execvp_or_die(char **argv)
8114 debug_printf_exec("execing '%s'\n", argv[0]);
8115 /* Don't propagate SIG_IGN to the child */
8116 if (SPECIAL_JOBSTOP_SIGS != 0)
8117 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8118 execvp(argv[0], argv);
8120 if (errno == EACCES) e = 126;
8121 if (errno == ENOENT) e = 127;
8122 bb_perror_msg("can't execute '%s'", argv[0]);
8126 #if ENABLE_HUSH_MODE_X
8127 static void x_mode_print_optionally_squoted(const char *str)
8134 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8135 /* test a char with: bash -c 'set -x; echo "CH"' */
8136 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8137 " " "\001\002\003\004\005\006\007"
8138 "\010\011\012\013\014\015\016\017"
8139 "\020\021\022\023\024\025\026\027"
8140 "\030\031\032\033\034\035\036\037"
8144 /* string has no special chars */
8151 /* print '....' up to EOL or first squote */
8152 len = (int)(strchrnul(cp, '\'') - cp);
8154 x_mode_addchr('\'');
8155 x_mode_addblock(cp, len);
8156 x_mode_addchr('\'');
8161 /* string contains squote(s), print them as \' */
8162 x_mode_addchr('\\');
8163 x_mode_addchr('\'');
8167 static void dump_cmd_in_x_mode(char **argv)
8169 if (G_x_mode && argv) {
8172 /* "+[+++...][ cmd...]\n\0" */
8177 if (argv[n][0] == '\0') {
8178 x_mode_addchr('\'');
8179 x_mode_addchr('\'');
8181 x_mode_print_optionally_squoted(argv[n]);
8189 # define dump_cmd_in_x_mode(argv) ((void)0)
8192 #if ENABLE_HUSH_COMMAND
8193 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8202 char *path = getenv("PATH");
8203 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
8205 _exit(1); /* PROG was not found */
8207 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8209 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
8215 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
8219 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8220 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8221 #define pseudo_exec(nommu_save, command, argv_expanded) \
8222 pseudo_exec(command, argv_expanded)
8225 /* Called after [v]fork() in run_pipe, or from builtin_exec.
8227 * Don't exit() here. If you don't exec, use _exit instead.
8228 * The at_exit handlers apparently confuse the calling process,
8229 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
8231 static void pseudo_exec_argv(nommu_save_t *nommu_save,
8232 char **argv, int assignment_cnt,
8233 char **argv_expanded) NORETURN;
8234 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8235 char **argv, int assignment_cnt,
8236 char **argv_expanded)
8238 const struct built_in_command *x;
8239 struct variable **sv_shadowed;
8241 IF_HUSH_COMMAND(char opt_vV = 0;)
8242 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8244 new_env = expand_assignments(argv, assignment_cnt);
8245 dump_cmd_in_x_mode(new_env);
8247 if (!argv[assignment_cnt]) {
8248 /* Case when we are here: ... | var=val | ...
8249 * (note that we do not exit early, i.e., do not optimize out
8250 * expand_assignments(): think about ... | var=`sleep 1` | ...
8252 free_strings(new_env);
8253 _exit(EXIT_SUCCESS);
8256 sv_shadowed = G.shadowed_vars_pp;
8258 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
8260 G.shadowed_vars_pp = &nommu_save->old_vars;
8263 set_vars_and_save_old(new_env);
8264 G.shadowed_vars_pp = sv_shadowed;
8266 if (argv_expanded) {
8267 argv = argv_expanded;
8269 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8271 nommu_save->argv = argv;
8274 dump_cmd_in_x_mode(argv);
8276 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8277 if (strchr(argv[0], '/') != NULL)
8281 #if ENABLE_HUSH_FUNCTIONS
8282 /* Check if the command matches any functions (this goes before bltins) */
8283 funcp = find_function(argv[0]);
8285 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
8288 #if ENABLE_HUSH_COMMAND
8289 /* "command BAR": run BAR without looking it up among functions
8290 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8291 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8293 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8298 if (p[0] != '-' || !p[1])
8299 continue; /* bash allows "command command command [-OPT] BAR" */
8307 if (p[0] != '-' || !p[1])
8309 continue; /* next arg is also -opts, process it too */
8315 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8320 # if ENABLE_HUSH_FUNCTIONS
8321 if (opt_vV && find_function(argv[0]))
8322 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8326 /* Check if the command matches any of the builtins.
8327 * Depending on context, this might be redundant. But it's
8328 * easier to waste a few CPU cycles than it is to figure out
8329 * if this is one of those cases.
8331 /* Why "BB_MMU ? :" difference in logic? -
8332 * On NOMMU, it is more expensive to re-execute shell
8333 * just in order to run echo or test builtin.
8334 * It's better to skip it here and run corresponding
8335 * non-builtin later. */
8336 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8338 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8339 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
8342 #if ENABLE_FEATURE_SH_STANDALONE
8343 /* Check if the command matches any busybox applets */
8345 int a = find_applet_by_name(argv[0]);
8347 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
8348 # if BB_MMU /* see above why on NOMMU it is not allowed */
8349 if (APPLET_IS_NOEXEC(a)) {
8350 /* Do not leak open fds from opened script files etc.
8351 * Testcase: interactive "ls -l /proc/self/fd"
8352 * should not show tty fd open.
8354 close_saved_fds_and_FILE_fds();
8355 //FIXME: should also close saved redir fds
8356 //This casuses test failures in
8357 //redir_children_should_not_see_saved_fd_2.tests
8358 //redir_children_should_not_see_saved_fd_3.tests
8359 //if you replace "busybox find" with just "find" in them
8360 /* Without this, "rm -i FILE" can't be ^C'ed: */
8361 switch_off_special_sigs(G.special_sig_mask);
8362 debug_printf_exec("running applet '%s'\n", argv[0]);
8363 run_noexec_applet_and_exit(a, argv[0], argv);
8366 /* Re-exec ourselves */
8367 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
8368 /* Don't propagate SIG_IGN to the child */
8369 if (SPECIAL_JOBSTOP_SIGS != 0)
8370 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8371 execv(bb_busybox_exec_path, argv);
8372 /* If they called chroot or otherwise made the binary no longer
8373 * executable, fall through */
8378 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8381 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
8382 execvp_or_die(argv);
8385 /* Called after [v]fork() in run_pipe
8387 static void pseudo_exec(nommu_save_t *nommu_save,
8388 struct command *command,
8389 char **argv_expanded) NORETURN;
8390 static void pseudo_exec(nommu_save_t *nommu_save,
8391 struct command *command,
8392 char **argv_expanded)
8394 #if ENABLE_HUSH_FUNCTIONS
8395 if (command->cmd_type == CMD_FUNCDEF) {
8396 /* Ignore funcdefs in pipes:
8397 * true | f() { cmd }
8403 if (command->argv) {
8404 pseudo_exec_argv(nommu_save, command->argv,
8405 command->assignment_cnt, argv_expanded);
8408 if (command->group) {
8409 /* Cases when we are here:
8412 * ... | ( list ) | ...
8413 * ... | { list } | ...
8417 debug_printf_exec("pseudo_exec: run_list\n");
8418 reset_traps_to_defaults();
8419 rcode = run_list(command->group);
8420 /* OK to leak memory by not calling free_pipe_list,
8421 * since this process is about to exit */
8424 re_execute_shell(&nommu_save->argv_from_re_execing,
8425 command->group_as_string,
8432 /* Case when we are here: ... | >file */
8433 debug_printf_exec("pseudo_exec'ed null command\n");
8434 _exit(EXIT_SUCCESS);
8438 static const char *get_cmdtext(struct pipe *pi)
8444 /* This is subtle. ->cmdtext is created only on first backgrounding.
8445 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8446 * On subsequent bg argv is trashed, but we won't use it */
8450 argv = pi->cmds[0].argv;
8452 pi->cmdtext = xzalloc(1);
8457 len += strlen(*argv) + 1;
8461 argv = pi->cmds[0].argv;
8463 p = stpcpy(p, *argv);
8470 static void remove_job_from_table(struct pipe *pi)
8472 struct pipe *prev_pipe;
8474 if (pi == G.job_list) {
8475 G.job_list = pi->next;
8477 prev_pipe = G.job_list;
8478 while (prev_pipe->next != pi)
8479 prev_pipe = prev_pipe->next;
8480 prev_pipe->next = pi->next;
8484 G.last_jobid = G.job_list->jobid;
8487 static void delete_finished_job(struct pipe *pi)
8489 remove_job_from_table(pi);
8493 static void clean_up_last_dead_job(void)
8495 if (G.job_list && !G.job_list->alive_cmds)
8496 delete_finished_job(G.job_list);
8499 static void insert_job_into_table(struct pipe *pi)
8501 struct pipe *job, **jobp;
8504 clean_up_last_dead_job();
8506 /* Find the end of the list, and find next job ID to use */
8509 while ((job = *jobp) != NULL) {
8516 /* Create a new job struct at the end */
8517 job = *jobp = xmemdup(pi, sizeof(*pi));
8519 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8520 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8521 for (i = 0; i < pi->num_cmds; i++) {
8522 job->cmds[i].pid = pi->cmds[i].pid;
8523 /* all other fields are not used and stay zero */
8525 job->cmdtext = xstrdup(get_cmdtext(pi));
8527 if (G_interactive_fd)
8528 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
8529 G.last_jobid = job->jobid;
8533 static int job_exited_or_stopped(struct pipe *pi)
8537 if (pi->alive_cmds != pi->stopped_cmds)
8540 /* All processes in fg pipe have exited or stopped */
8544 rcode = pi->cmds[i].cmd_exitcode;
8545 /* usually last process gives overall exitstatus,
8546 * but with "set -o pipefail", last *failed* process does */
8547 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8550 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8554 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
8561 dead = WIFEXITED(status) || WIFSIGNALED(status);
8564 if (WIFSTOPPED(status))
8565 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8566 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8567 if (WIFSIGNALED(status))
8568 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8569 childpid, WTERMSIG(status), WEXITSTATUS(status));
8570 if (WIFEXITED(status))
8571 debug_printf_jobs("pid %d exited, exitcode %d\n",
8572 childpid, WEXITSTATUS(status));
8574 /* Were we asked to wait for a fg pipe? */
8576 i = fg_pipe->num_cmds;
8581 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8582 if (fg_pipe->cmds[i].pid != childpid)
8586 fg_pipe->cmds[i].pid = 0;
8587 fg_pipe->alive_cmds--;
8588 ex = WEXITSTATUS(status);
8589 /* bash prints killer signal's name for *last*
8590 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8591 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8593 if (WIFSIGNALED(status)) {
8594 int sig = WTERMSIG(status);
8595 if (i == fg_pipe->num_cmds-1)
8596 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8597 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8598 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8599 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8600 * Maybe we need to use sig | 128? */
8603 fg_pipe->cmds[i].cmd_exitcode = ex;
8605 fg_pipe->stopped_cmds++;
8607 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8608 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
8609 rcode = job_exited_or_stopped(fg_pipe);
8611 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
8612 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8613 * and "killall -STOP cat" */
8614 if (G_interactive_fd) {
8616 if (fg_pipe->alive_cmds != 0)
8617 insert_job_into_table(fg_pipe);
8621 if (fg_pipe->alive_cmds == 0)
8624 /* There are still running processes in the fg_pipe */
8627 /* It wasn't in fg_pipe, look for process in bg pipes */
8631 /* We were asked to wait for bg or orphaned children */
8632 /* No need to remember exitcode in this case */
8633 for (pi = G.job_list; pi; pi = pi->next) {
8634 for (i = 0; i < pi->num_cmds; i++) {
8635 if (pi->cmds[i].pid == childpid)
8636 goto found_pi_and_prognum;
8639 /* Happens when shell is used as init process (init=/bin/sh) */
8640 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8641 return -1; /* this wasn't a process from fg_pipe */
8643 found_pi_and_prognum:
8646 int rcode = WEXITSTATUS(status);
8647 if (WIFSIGNALED(status))
8648 rcode = 128 + WTERMSIG(status);
8649 pi->cmds[i].cmd_exitcode = rcode;
8650 if (G.last_bg_pid == pi->cmds[i].pid)
8651 G.last_bg_pid_exitcode = rcode;
8652 pi->cmds[i].pid = 0;
8654 if (!pi->alive_cmds) {
8655 if (G_interactive_fd) {
8656 printf(JOB_STATUS_FORMAT, pi->jobid,
8657 "Done", pi->cmdtext);
8658 delete_finished_job(pi);
8661 * bash deletes finished jobs from job table only in interactive mode,
8662 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8663 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8664 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8665 * We only retain one "dead" job, if it's the single job on the list.
8666 * This covers most of real-world scenarios where this is useful.
8668 if (pi != G.job_list)
8669 delete_finished_job(pi);
8677 return -1; /* this wasn't a process from fg_pipe */
8680 /* Check to see if any processes have exited -- if they have,
8681 * figure out why and see if a job has completed.
8683 * If non-NULL fg_pipe: wait for its completion or stop.
8684 * Return its exitcode or zero if stopped.
8686 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8687 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8688 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8689 * or 0 if no children changed status.
8691 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8692 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8693 * or 0 if no children changed status.
8695 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8701 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8703 attributes = WUNTRACED;
8704 if (fg_pipe == NULL)
8705 attributes |= WNOHANG;
8708 #if ENABLE_HUSH_FAST
8709 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8710 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8711 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8712 /* There was neither fork nor SIGCHLD since last waitpid */
8713 /* Avoid doing waitpid syscall if possible */
8714 if (!G.we_have_children) {
8718 if (fg_pipe == NULL) { /* is WNOHANG set? */
8719 /* We have children, but they did not exit
8720 * or stop yet (we saw no SIGCHLD) */
8723 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8727 /* Do we do this right?
8728 * bash-3.00# sleep 20 | false
8730 * [3]+ Stopped sleep 20 | false
8731 * bash-3.00# echo $?
8732 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8733 * [hush 1.14.0: yes we do it right]
8737 #if ENABLE_HUSH_FAST
8739 i = G.count_SIGCHLD;
8741 childpid = waitpid(-1, &status, attributes);
8742 if (childpid <= 0) {
8743 if (childpid && errno != ECHILD)
8744 bb_perror_msg("waitpid");
8745 #if ENABLE_HUSH_FAST
8746 else { /* Until next SIGCHLD, waitpid's are useless */
8747 G.we_have_children = (childpid == 0);
8748 G.handled_SIGCHLD = i;
8749 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8752 /* ECHILD (no children), or 0 (no change in children status) */
8756 rcode = process_wait_result(fg_pipe, childpid, status);
8758 /* fg_pipe exited or stopped */
8761 if (childpid == waitfor_pid) {
8762 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
8763 rcode = WEXITSTATUS(status);
8764 if (WIFSIGNALED(status))
8765 rcode = 128 + WTERMSIG(status);
8766 if (WIFSTOPPED(status))
8767 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8768 rcode = 128 + WSTOPSIG(status);
8770 break; /* "wait PID" called us, give it exitcode+1 */
8772 /* This wasn't one of our processes, or */
8773 /* fg_pipe still has running processes, do waitpid again */
8774 } /* while (waitpid succeeds)... */
8780 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
8783 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
8784 if (G_saved_tty_pgrp) {
8785 /* Job finished, move the shell to the foreground */
8786 p = getpgrp(); /* our process group id */
8787 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8788 tcsetpgrp(G_interactive_fd, p);
8794 /* Start all the jobs, but don't wait for anything to finish.
8797 * Return code is normally -1, when the caller has to wait for children
8798 * to finish to determine the exit status of the pipe. If the pipe
8799 * is a simple builtin command, however, the action is done by the
8800 * time run_pipe returns, and the exit code is provided as the
8803 * Returns -1 only if started some children. IOW: we have to
8804 * mask out retvals of builtins etc with 0xff!
8806 * The only case when we do not need to [v]fork is when the pipe
8807 * is single, non-backgrounded, non-subshell command. Examples:
8808 * cmd ; ... { list } ; ...
8809 * cmd && ... { list } && ...
8810 * cmd || ... { list } || ...
8811 * If it is, then we can run cmd as a builtin, NOFORK,
8812 * or (if SH_STANDALONE) an applet, and we can run the { list }
8813 * with run_list. If it isn't one of these, we fork and exec cmd.
8815 * Cases when we must fork:
8816 * non-single: cmd | cmd
8817 * backgrounded: cmd & { list } &
8818 * subshell: ( list ) [&]
8820 #if !ENABLE_HUSH_MODE_X
8821 #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8822 redirect_and_varexp_helper(command, sqp)
8824 static int redirect_and_varexp_helper(
8825 struct command *command,
8826 struct squirrel **sqp,
8827 char **argv_expanded)
8829 /* Assignments occur before redirects. Try:
8830 * a=`sleep 1` sleep 2 3>/qwe/rty
8833 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8834 dump_cmd_in_x_mode(new_env);
8835 dump_cmd_in_x_mode(argv_expanded);
8836 /* this takes ownership of new_env[i] elements, and frees new_env: */
8837 set_vars_and_save_old(new_env);
8839 return setup_redirects(command, sqp);
8841 static NOINLINE int run_pipe(struct pipe *pi)
8843 static const char *const null_ptr = NULL;
8847 struct command *command;
8848 char **argv_expanded;
8850 struct squirrel *squirrel = NULL;
8853 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8856 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8857 * Result should be 3 lines: q w e, qwe, q w e
8859 if (G.ifs_whitespace != G.ifs)
8860 free(G.ifs_whitespace);
8861 G.ifs = get_local_var_value("IFS");
8864 G.ifs_whitespace = (char*)G.ifs;
8865 p = skip_whitespace(G.ifs);
8867 /* Not all $IFS is whitespace */
8869 int len = p - G.ifs;
8870 p = skip_non_whitespace(p);
8871 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8872 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8882 G.ifs_whitespace = (char*)G.ifs;
8885 IF_HUSH_JOB(pi->pgrp = -1;)
8886 pi->stopped_cmds = 0;
8887 command = &pi->cmds[0];
8888 argv_expanded = NULL;
8890 if (pi->num_cmds != 1
8891 || pi->followup == PIPE_BG
8892 || command->cmd_type == CMD_SUBSHELL
8899 debug_printf_exec(": group:%p argv:'%s'\n",
8900 command->group, command->argv ? command->argv[0] : "NONE");
8902 if (command->group) {
8903 #if ENABLE_HUSH_FUNCTIONS
8904 if (command->cmd_type == CMD_FUNCDEF) {
8905 /* "executing" func () { list } */
8906 struct function *funcp;
8908 funcp = new_function(command->argv[0]);
8909 /* funcp->name is already set to argv[0] */
8910 funcp->body = command->group;
8912 funcp->body_as_string = command->group_as_string;
8913 command->group_as_string = NULL;
8915 command->group = NULL;
8916 command->argv[0] = NULL;
8917 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8918 funcp->parent_cmd = command;
8919 command->child_func = funcp;
8921 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8923 return EXIT_SUCCESS;
8927 debug_printf_exec("non-subshell group\n");
8928 rcode = 1; /* exitcode if redir failed */
8929 if (setup_redirects(command, &squirrel) == 0) {
8930 debug_printf_exec(": run_list\n");
8931 //FIXME: we need to pass squirrel down into run_list()
8932 //for SH_STANDALONE case, or else this construct:
8933 // { find /proc/self/fd; true; } >FILE; cmd2
8934 //has no way of closing saved fd#1 for "find",
8935 //and in SH_STANDALONE mode, "find" is not execed,
8936 //therefore CLOEXEC on saved fd does not help.
8937 rcode = run_list(command->group) & 0xff;
8939 restore_redirects(squirrel);
8940 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8942 debug_printf_exec("run_pipe: return %d\n", rcode);
8946 argv = command->argv ? command->argv : (char **) &null_ptr;
8948 const struct built_in_command *x;
8949 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8950 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
8951 struct variable **sv_shadowed;
8952 struct variable *old_vars;
8954 #if ENABLE_HUSH_LINENO_VAR
8956 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8959 if (argv[command->assignment_cnt] == NULL) {
8960 /* Assignments, but no command.
8961 * Ensure redirects take effect (that is, create files).
8965 G.expand_exitcode = 0;
8967 rcode = setup_redirects(command, &squirrel);
8968 restore_redirects(squirrel);
8970 /* Set shell variables */
8972 while (i < command->assignment_cnt) {
8973 char *p = expand_string_to_string(argv[i],
8974 EXP_FLAG_ESC_GLOB_CHARS,
8977 #if ENABLE_HUSH_MODE_X
8983 eq = strchrnul(p, '=');
8985 x_mode_addblock(p, (eq - p));
8986 x_mode_print_optionally_squoted(eq);
8990 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
8991 if (set_local_var(p, /*flag:*/ 0)) {
8992 /* assignment to readonly var / putenv error? */
8997 /* Redirect error sets $? to 1. Otherwise,
8998 * if evaluating assignment value set $?, retain it.
9000 * false; q=`exit 2`; echo $? - should print 2
9001 * false; x=1; echo $? - should print 0
9002 * Because of the 2nd case, we can't just use G.last_exitcode.
9005 rcode = G.expand_exitcode;
9006 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9008 debug_printf_exec("run_pipe: return %d\n", rcode);
9012 /* Expand the rest into (possibly) many strings each */
9013 #if defined(CMD_SINGLEWORD_NOGLOB)
9014 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
9015 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9018 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
9020 /* If someone gives us an empty string: `cmd with empty output` */
9021 if (!argv_expanded[0]) {
9022 free(argv_expanded);
9023 /* `false` still has to set exitcode 1 */
9024 G.expand_exitcode = G.last_exitcode;
9025 goto only_assignments;
9029 sv_shadowed = G.shadowed_vars_pp;
9031 /* Check if argv[0] matches any functions (this goes before bltins) */
9032 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9033 IF_HUSH_FUNCTIONS(x = NULL;)
9034 IF_HUSH_FUNCTIONS(if (!funcp))
9035 x = find_builtin(argv_expanded[0]);
9037 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9038 debug_printf("exec with redirects only\n");
9040 * Variable assignments are executed, but then "forgotten":
9041 * a=`sleep 1;echo A` exec 3>&-; echo $a
9042 * sleeps, but prints nothing.
9044 enter_var_nest_level();
9045 G.shadowed_vars_pp = &old_vars;
9046 rcode = redirect_and_varexp_helper(command,
9047 /*squirrel:*/ ERR_PTR,
9050 G.shadowed_vars_pp = sv_shadowed;
9051 /* rcode=1 can be if redir file can't be opened */
9053 goto clean_up_and_ret1;
9056 /* Bump var nesting, or this will leak exported $a:
9057 * a=b true; env | grep ^a=
9059 enter_var_nest_level();
9060 /* Collect all variables "shadowed" by helper
9061 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9062 * into old_vars list:
9064 G.shadowed_vars_pp = &old_vars;
9065 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9068 /* Do not collect *to old_vars list* vars shadowed
9069 * by e.g. "local VAR" builtin (collect them
9070 * in the previously nested list instead):
9071 * don't want them to be restored immediately
9072 * after "local" completes.
9074 G.shadowed_vars_pp = sv_shadowed;
9076 debug_printf_exec(": builtin '%s' '%s'...\n",
9077 x->b_cmd, argv_expanded[1]);
9079 rcode = x->b_function(argv_expanded) & 0xff;
9082 #if ENABLE_HUSH_FUNCTIONS
9084 debug_printf_exec(": function '%s' '%s'...\n",
9085 funcp->name, argv_expanded[1]);
9086 rcode = run_function(funcp, argv_expanded) & 0xff;
9088 * But do collect *to old_vars list* vars shadowed
9089 * within function execution. To that end, restore
9090 * this pointer _after_ function run:
9092 G.shadowed_vars_pp = sv_shadowed;
9097 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
9098 int n = find_applet_by_name(argv_expanded[0]);
9099 if (n < 0 || !APPLET_IS_NOFORK(n))
9102 enter_var_nest_level();
9103 /* Collect all variables "shadowed" by helper into old_vars list */
9104 G.shadowed_vars_pp = &old_vars;
9105 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9106 G.shadowed_vars_pp = sv_shadowed;
9109 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9110 argv_expanded[0], argv_expanded[1]);
9112 * Note: signals (^C) can't interrupt here.
9113 * We remember them and they will be acted upon
9114 * after applet returns.
9115 * This makes applets which can run for a long time
9116 * and/or wait for user input ineligible for NOFORK:
9117 * for example, "yes" or "rm" (rm -i waits for input).
9119 rcode = run_nofork_applet(n, argv_expanded);
9124 restore_redirects(squirrel);
9126 leave_var_nest_level();
9130 * Try "usleep 99999999" + ^C + "echo $?"
9131 * with FEATURE_SH_NOFORK=y.
9134 /* It was builtin or nofork.
9135 * if this would be a real fork/execed program,
9136 * it should have died if a fatal sig was received.
9137 * But OTOH, there was no separate process,
9138 * the sig was sent to _shell_, not to non-existing
9140 * Let's just handle ^C only, this one is obvious:
9141 * we aren't ok with exitcode 0 when ^C was pressed
9142 * during builtin/nofork.
9144 if (sigismember(&G.pending_set, SIGINT))
9145 rcode = 128 + SIGINT;
9147 free(argv_expanded);
9148 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9150 debug_printf_exec("run_pipe return %d\n", rcode);
9155 /* NB: argv_expanded may already be created, and that
9156 * might include `cmd` runs! Do not rerun it! We *must*
9157 * use argv_expanded if it's non-NULL */
9159 /* Going to fork a child per each pipe member */
9164 while (cmd_no < pi->num_cmds) {
9165 struct fd_pair pipefds;
9167 int sv_var_nest_level = G.var_nest_level;
9168 volatile nommu_save_t nommu_save;
9169 nommu_save.old_vars = NULL;
9170 nommu_save.argv = NULL;
9171 nommu_save.argv_from_re_execing = NULL;
9173 command = &pi->cmds[cmd_no];
9175 if (command->argv) {
9176 debug_printf_exec(": pipe member '%s' '%s'...\n",
9177 command->argv[0], command->argv[1]);
9179 debug_printf_exec(": pipe member with no argv\n");
9182 /* pipes are inserted between pairs of commands */
9185 if (cmd_no < pi->num_cmds)
9186 xpiped_pair(pipefds);
9188 #if ENABLE_HUSH_LINENO_VAR
9190 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9193 command->pid = BB_MMU ? fork() : vfork();
9194 if (!command->pid) { /* child */
9196 disable_restore_tty_pgrp_on_exit();
9197 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9199 /* Every child adds itself to new process group
9200 * with pgid == pid_of_first_child_in_pipe */
9201 if (G.run_list_level == 1 && G_interactive_fd) {
9204 if (pgrp < 0) /* true for 1st process only */
9206 if (setpgid(0, pgrp) == 0
9207 && pi->followup != PIPE_BG
9208 && G_saved_tty_pgrp /* we have ctty */
9210 /* We do it in *every* child, not just first,
9212 tcsetpgrp(G_interactive_fd, pgrp);
9216 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9217 /* 1st cmd in backgrounded pipe
9218 * should have its stdin /dev/null'ed */
9220 if (open(bb_dev_null, O_RDONLY))
9221 xopen("/", O_RDONLY);
9223 xmove_fd(next_infd, 0);
9225 xmove_fd(pipefds.wr, 1);
9228 /* Like bash, explicit redirects override pipes,
9229 * and the pipe fd (fd#1) is available for dup'ing:
9230 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9231 * of cmd1 goes into pipe.
9233 if (setup_redirects(command, NULL)) {
9234 /* Happens when redir file can't be opened:
9235 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9237 * hush: can't open '/qwe/rty': No such file or directory
9239 * (echo BAR is not executed, it hits _exit(1) below)
9244 /* Stores to nommu_save list of env vars putenv'ed
9245 * (NOMMU, on MMU we don't need that) */
9246 /* cast away volatility... */
9247 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9248 /* pseudo_exec() does not return */
9251 /* parent or error */
9252 #if ENABLE_HUSH_FAST
9254 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9256 enable_restore_tty_pgrp_on_exit();
9258 /* Clean up after vforked child */
9259 free(nommu_save.argv);
9260 free(nommu_save.argv_from_re_execing);
9261 G.var_nest_level = sv_var_nest_level;
9262 remove_nested_vars();
9263 add_vars(nommu_save.old_vars);
9265 free(argv_expanded);
9266 argv_expanded = NULL;
9267 if (command->pid < 0) { /* [v]fork failed */
9268 /* Clearly indicate, was it fork or vfork */
9269 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9273 /* Second and next children need to know pid of first one */
9275 pi->pgrp = command->pid;
9281 if (cmd_no < pi->num_cmds)
9283 /* Pass read (output) pipe end to next iteration */
9284 next_infd = pipefds.rd;
9287 if (!pi->alive_cmds) {
9289 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9294 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9298 /* NB: called by pseudo_exec, and therefore must not modify any
9299 * global data until exec/_exit (we can be a child after vfork!) */
9300 static int run_list(struct pipe *pi)
9302 #if ENABLE_HUSH_CASE
9303 char *case_word = NULL;
9305 #if ENABLE_HUSH_LOOPS
9306 struct pipe *loop_top = NULL;
9307 char **for_lcur = NULL;
9308 char **for_list = NULL;
9310 smallint last_followup;
9312 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9313 smalluint cond_code = 0;
9315 enum { cond_code = 0 };
9318 smallint rword; /* RES_foo */
9319 smallint last_rword; /* ditto */
9322 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9325 #if ENABLE_HUSH_LOOPS
9326 /* Check syntax for "for" */
9329 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9330 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9332 /* current word is FOR or IN (BOLD in comments below) */
9333 if (cpipe->next == NULL) {
9334 syntax_error("malformed for");
9336 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9339 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9340 if (cpipe->next->res_word == RES_DO)
9342 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9343 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9344 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9346 syntax_error("malformed for");
9348 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9355 /* Past this point, all code paths should jump to ret: label
9356 * in order to return, no direct "return" statements please.
9357 * This helps to ensure that no memory is leaked. */
9365 last_rword = RES_XXXX;
9367 last_followup = PIPE_SEQ;
9368 rcode = G.last_exitcode;
9370 /* Go through list of pipes, (maybe) executing them. */
9371 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
9373 int sv_errexit_depth;
9377 if (G_flag_return_in_progress == 1)
9380 IF_HAS_KEYWORDS(rword = pi->res_word;)
9381 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9382 rword, cond_code, last_rword);
9384 sv_errexit_depth = G.errexit_depth;
9387 rword == RES_IF || rword == RES_ELIF ||
9389 pi->followup != PIPE_SEQ
9393 #if ENABLE_HUSH_LOOPS
9394 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9395 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9397 /* start of a loop: remember where loop starts */
9402 /* Still in the same "if...", "then..." or "do..." branch? */
9403 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9404 if ((rcode == 0 && last_followup == PIPE_OR)
9405 || (rcode != 0 && last_followup == PIPE_AND)
9407 /* It is "<true> || CMD" or "<false> && CMD"
9408 * and we should not execute CMD */
9409 debug_printf_exec("skipped cmd because of || or &&\n");
9410 last_followup = pi->followup;
9411 goto dont_check_jobs_but_continue;
9414 last_followup = pi->followup;
9415 IF_HAS_KEYWORDS(last_rword = rword;)
9418 if (rword == RES_THEN) {
9419 /* if false; then ... fi has exitcode 0! */
9420 G.last_exitcode = rcode = EXIT_SUCCESS;
9421 /* "if <false> THEN cmd": skip cmd */
9425 if (rword == RES_ELSE || rword == RES_ELIF) {
9426 /* "if <true> then ... ELSE/ELIF cmd":
9427 * skip cmd and all following ones */
9432 #if ENABLE_HUSH_LOOPS
9433 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9435 /* first loop through for */
9437 static const char encoded_dollar_at[] ALIGN1 = {
9438 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9439 }; /* encoded representation of "$@" */
9440 static const char *const encoded_dollar_at_argv[] = {
9441 encoded_dollar_at, NULL
9442 }; /* argv list with one element: "$@" */
9445 G.last_exitcode = rcode = EXIT_SUCCESS;
9446 vals = (char**)encoded_dollar_at_argv;
9447 if (pi->next->res_word == RES_IN) {
9448 /* if no variable values after "in" we skip "for" */
9449 if (!pi->next->cmds[0].argv) {
9450 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9453 vals = pi->next->cmds[0].argv;
9454 } /* else: "for var; do..." -> assume "$@" list */
9455 /* create list of variable values */
9456 debug_print_strings("for_list made from", vals);
9457 for_list = expand_strvec_to_strvec(vals);
9458 for_lcur = for_list;
9459 debug_print_strings("for_list", for_list);
9462 /* "for" loop is over, clean up */
9468 /* Insert next value from for_lcur */
9469 /* note: *for_lcur already has quotes removed, $var expanded, etc */
9470 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
9473 if (rword == RES_IN) {
9474 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9476 if (rword == RES_DONE) {
9477 continue; /* "done" has no cmds too */
9480 #if ENABLE_HUSH_CASE
9481 if (rword == RES_CASE) {
9482 debug_printf_exec("CASE cond_code:%d\n", cond_code);
9483 case_word = expand_string_to_string(pi->cmds->argv[0],
9484 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
9485 debug_printf_exec("CASE word1:'%s'\n", case_word);
9486 //unbackslash(case_word);
9487 //debug_printf_exec("CASE word2:'%s'\n", case_word);
9490 if (rword == RES_MATCH) {
9493 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
9494 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9496 /* all prev words didn't match, does this one match? */
9497 argv = pi->cmds->argv;
9500 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9501 pattern = expand_string_to_string(*argv,
9502 EXP_FLAG_ESC_GLOB_CHARS,
9505 /* TODO: which FNM_xxx flags to use? */
9506 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
9507 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9508 pattern, case_word, cond_code);
9510 if (cond_code == 0) {
9511 /* match! we will execute this branch */
9513 case_word = NULL; /* make future "word)" stop */
9520 if (rword == RES_CASE_BODY) { /* inside of a case branch */
9521 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
9523 continue; /* not matched yet, skip this pipe */
9525 if (rword == RES_ESAC) {
9526 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9528 /* "case" did not match anything: still set $? (to 0) */
9529 G.last_exitcode = rcode = EXIT_SUCCESS;
9533 /* Just pressing <enter> in shell should check for jobs.
9534 * OTOH, in non-interactive shell this is useless
9535 * and only leads to extra job checks */
9536 if (pi->num_cmds == 0) {
9537 if (G_interactive_fd)
9538 goto check_jobs_and_continue;
9542 /* After analyzing all keywords and conditions, we decided
9543 * to execute this pipe. NB: have to do checkjobs(NULL)
9544 * after run_pipe to collect any background children,
9545 * even if list execution is to be stopped. */
9546 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
9547 #if ENABLE_HUSH_LOOPS
9548 G.flag_break_continue = 0;
9550 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9552 /* We ran a builtin, function, or group.
9553 * rcode is already known
9554 * and we don't need to wait for anything. */
9555 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9556 G.last_exitcode = rcode;
9557 check_and_run_traps();
9558 #if ENABLE_HUSH_LOOPS
9559 /* Was it "break" or "continue"? */
9560 if (G.flag_break_continue) {
9561 smallint fbc = G.flag_break_continue;
9562 /* We might fall into outer *loop*,
9563 * don't want to break it too */
9565 G.depth_break_continue--;
9566 if (G.depth_break_continue == 0)
9567 G.flag_break_continue = 0;
9568 /* else: e.g. "continue 2" should *break* once, *then* continue */
9569 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9570 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
9571 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9574 /* "continue": simulate end of loop */
9579 if (G_flag_return_in_progress == 1) {
9580 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9583 } else if (pi->followup == PIPE_BG) {
9584 /* What does bash do with attempts to background builtins? */
9585 /* even bash 3.2 doesn't do that well with nested bg:
9586 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9587 * I'm NOT treating inner &'s as jobs */
9589 if (G.run_list_level == 1)
9590 insert_job_into_table(pi);
9592 /* Last command's pid goes to $! */
9593 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
9594 G.last_bg_pid_exitcode = 0;
9595 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
9596 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
9597 rcode = EXIT_SUCCESS;
9601 if (G.run_list_level == 1 && G_interactive_fd) {
9602 /* Waits for completion, then fg's main shell */
9603 rcode = checkjobs_and_fg_shell(pi);
9604 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
9608 /* This one just waits for completion */
9609 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9610 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9612 G.last_exitcode = rcode;
9613 check_and_run_traps();
9616 /* Handle "set -e" */
9617 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9618 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9619 if (G.errexit_depth == 0)
9622 G.errexit_depth = sv_errexit_depth;
9624 /* Analyze how result affects subsequent commands */
9626 if (rword == RES_IF || rword == RES_ELIF)
9629 check_jobs_and_continue:
9630 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9631 dont_check_jobs_but_continue: ;
9632 #if ENABLE_HUSH_LOOPS
9633 /* Beware of "while false; true; do ..."! */
9635 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
9636 /* check for RES_DONE is needed for "while ...; do \n done" case */
9638 if (rword == RES_WHILE) {
9640 /* "while false; do...done" - exitcode 0 */
9641 G.last_exitcode = rcode = EXIT_SUCCESS;
9642 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
9646 if (rword == RES_UNTIL) {
9648 debug_printf_exec(": until expr is true: breaking\n");
9659 #if ENABLE_HUSH_LOOPS
9664 #if ENABLE_HUSH_CASE
9668 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9672 /* Select which version we will use */
9673 static int run_and_free_list(struct pipe *pi)
9676 debug_printf_exec("run_and_free_list entered\n");
9677 if (!G.o_opt[OPT_O_NOEXEC]) {
9678 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9679 rcode = run_list(pi);
9681 /* free_pipe_list has the side effect of clearing memory.
9682 * In the long run that function can be merged with run_list,
9683 * but doing that now would hobble the debugging effort. */
9685 debug_printf_exec("run_and_free_list return %d\n", rcode);
9690 static void install_sighandlers(unsigned mask)
9692 sighandler_t old_handler;
9694 while ((mask >>= 1) != 0) {
9698 old_handler = install_sighandler(sig, pick_sighandler(sig));
9699 /* POSIX allows shell to re-enable SIGCHLD
9700 * even if it was SIG_IGN on entry.
9701 * Therefore we skip IGN check for it:
9705 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9706 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9708 //if (sig == SIGHUP) continue; - TODO?
9709 if (old_handler == SIG_IGN) {
9710 /* oops... restore back to IGN, and record this fact */
9711 install_sighandler(sig, old_handler);
9712 #if ENABLE_HUSH_TRAP
9714 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9716 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9722 /* Called a few times only (or even once if "sh -c") */
9723 static void install_special_sighandlers(void)
9727 /* Which signals are shell-special? */
9728 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
9729 if (G_interactive_fd) {
9730 mask |= SPECIAL_INTERACTIVE_SIGS;
9731 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
9732 mask |= SPECIAL_JOBSTOP_SIGS;
9734 /* Careful, do not re-install handlers we already installed */
9735 if (G.special_sig_mask != mask) {
9736 unsigned diff = mask & ~G.special_sig_mask;
9737 G.special_sig_mask = mask;
9738 install_sighandlers(diff);
9744 /* Set handlers to restore tty pgrp and exit */
9745 static void install_fatal_sighandlers(void)
9749 /* We will restore tty pgrp on these signals */
9751 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9752 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
9753 + (1 << SIGBUS ) * HUSH_DEBUG
9754 + (1 << SIGSEGV) * HUSH_DEBUG
9755 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
9757 /* bash 3.2 seems to handle these just like 'fatal' ones */
9760 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
9761 * if we aren't interactive... but in this case
9762 * we never want to restore pgrp on exit, and this fn is not called
9764 /*+ (1 << SIGHUP )*/
9765 /*+ (1 << SIGTERM)*/
9766 /*+ (1 << SIGINT )*/
9768 G_fatal_sig_mask = mask;
9770 install_sighandlers(mask);
9774 static int set_mode(int state, char mode, const char *o_opt)
9779 G.o_opt[OPT_O_NOEXEC] = state;
9782 IF_HUSH_MODE_X(G_x_mode = state;)
9783 IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
9787 /* "set -+o" without parameter.
9788 * in bash, set -o produces this output:
9792 * We always use the second form.
9794 const char *p = o_opt_strings;
9797 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9803 idx = index_in_strings(o_opt_strings, o_opt);
9805 G.o_opt[idx] = state;
9809 G.o_opt[OPT_O_ERREXIT] = state;
9812 return EXIT_FAILURE;
9814 return EXIT_SUCCESS;
9817 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
9818 int hush_main(int argc, char **argv)
9821 OPT_login = (1 << 0),
9825 unsigned builtin_argc;
9827 struct variable *cur_var;
9828 struct variable *shell_ver;
9831 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
9832 G.last_exitcode = EXIT_SUCCESS;
9834 #if ENABLE_HUSH_FAST
9835 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9838 G.argv0_for_re_execing = argv[0];
9841 /* Deal with HUSH_VERSION */
9842 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9843 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
9844 shell_ver = xzalloc(sizeof(*shell_ver));
9845 shell_ver->flg_export = 1;
9846 shell_ver->flg_read_only = 1;
9847 /* Code which handles ${var<op>...} needs writable values for all variables,
9848 * therefore we xstrdup: */
9849 shell_ver->varstr = xstrdup(hush_version_str);
9851 /* Create shell local variables from the values
9852 * currently living in the environment */
9853 G.top_var = shell_ver;
9854 cur_var = G.top_var;
9857 char *value = strchr(*e, '=');
9858 if (value) { /* paranoia */
9859 cur_var->next = xzalloc(sizeof(*cur_var));
9860 cur_var = cur_var->next;
9861 cur_var->varstr = *e;
9862 cur_var->max_len = strlen(*e);
9863 cur_var->flg_export = 1;
9867 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
9868 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9869 putenv(shell_ver->varstr);
9872 set_pwd_var(SETFLAG_EXPORT);
9874 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9875 /* Set (but not export) PS1/2 unless already set */
9876 if (!get_local_var_value("PS1"))
9877 set_local_var_from_halves("PS1", "\\w \\$ ");
9878 if (!get_local_var_value("PS2"))
9879 set_local_var_from_halves("PS2", "> ");
9882 #if BASH_HOSTNAME_VAR
9883 /* Set (but not export) HOSTNAME unless already set */
9884 if (!get_local_var_value("HOSTNAME")) {
9887 set_local_var_from_halves("HOSTNAME", uts.nodename);
9890 /* IFS is not inherited from the parent environment */
9891 set_local_var_from_halves("IFS", defifs);
9893 /* bash also exports SHLVL and _,
9894 * and sets (but doesn't export) the following variables:
9896 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9897 * BASH_VERSION='3.2.0(1)-release'
9899 * MACHTYPE=i386-pc-linux-gnu
9901 * PPID=<NNNNN> - we also do it elsewhere
9912 * PIPESTATUS=([0]="0")
9913 * HISTFILE=/<xxx>/.bash_history
9917 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9919 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9926 #if ENABLE_HUSH_LINENO_VAR
9927 if (ENABLE_HUSH_LINENO_VAR) {
9928 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9929 set_local_var(p, /*flags*/ 0);
9930 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9934 #if ENABLE_FEATURE_EDITING
9935 G.line_input_state = new_line_input_t(FOR_SHELL);
9938 /* Initialize some more globals to non-zero values */
9939 cmdedit_update_prompt();
9941 die_func = restore_ttypgrp_and__exit;
9943 /* Shell is non-interactive at first. We need to call
9944 * install_special_sighandlers() if we are going to execute "sh <script>",
9945 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9946 * If we later decide that we are interactive, we run install_special_sighandlers()
9947 * in order to intercept (more) signals.
9951 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9952 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9955 int opt = getopt(argc, argv, "+c:exinsl"
9958 # if ENABLE_HUSH_FUNCTIONS
9968 * sh ... -c 'script'
9969 * sh ... -c 'script' ARG0 [ARG1...]
9970 * On NOMMU, if builtin_argc != 0,
9971 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9972 * "" needs to be replaced with NULL
9973 * and BARGV vector fed to builtin function.
9974 * Note: the form without ARG0 never happens:
9975 * sh ... -c 'builtin' BARGV... ""
9978 G.root_pid = getpid();
9979 G.root_ppid = getppid();
9981 G.global_argv = argv + optind;
9982 G.global_argc = argc - optind;
9984 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9985 const struct built_in_command *x;
9987 install_special_sighandlers();
9988 x = find_builtin(optarg);
9989 if (x) { /* paranoia */
9990 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9991 G.global_argv += builtin_argc;
9992 G.global_argv[-1] = NULL; /* replace "" */
9994 G.last_exitcode = x->b_function(argv + optind - 1);
9998 if (!G.global_argv[0]) {
9999 /* -c 'script' (no params): prevent empty $0 */
10000 G.global_argv--; /* points to argv[i] of 'script' */
10001 G.global_argv[0] = argv[0];
10003 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10004 install_special_sighandlers();
10005 parse_and_run_string(optarg);
10008 /* Well, we cannot just declare interactiveness,
10009 * we have to have some stuff (ctty, etc) */
10010 /* G_interactive_fd++; */
10016 flags |= OPT_login;
10019 case '<': /* "big heredoc" support */
10020 full_write1_str(optarg);
10023 unsigned long long empty_trap_mask;
10025 G.root_pid = bb_strtou(optarg, &optarg, 16);
10027 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10029 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10031 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
10033 builtin_argc = bb_strtou(optarg, &optarg, 16);
10035 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10036 if (empty_trap_mask != 0) {
10037 IF_HUSH_TRAP(int sig;)
10038 install_special_sighandlers();
10039 # if ENABLE_HUSH_TRAP
10040 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10041 for (sig = 1; sig < NSIG; sig++) {
10042 if (empty_trap_mask & (1LL << sig)) {
10043 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
10044 install_sighandler(sig, SIG_IGN);
10049 # if ENABLE_HUSH_LOOPS
10051 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
10053 # if ENABLE_HUSH_FUNCTIONS
10054 /* nommu uses re-exec trick for "... | func | ...",
10055 * should allow "return".
10056 * This accidentally allows returns in subshells.
10058 G_flag_return_in_progress = -1;
10064 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
10066 # if ENABLE_HUSH_FUNCTIONS
10068 struct function *funcp = new_function(optarg);
10069 /* funcp->name is already set to optarg */
10070 /* funcp->body is set to NULL. It's a special case. */
10071 funcp->body_as_string = argv[optind];
10080 if (set_mode(1, opt, NULL) == 0) /* no error */
10084 fprintf(stderr, "Usage: sh [FILE]...\n"
10085 " or: sh -c command [args]...\n\n");
10086 exit(EXIT_FAILURE);
10091 } /* option parsing loop */
10093 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10094 G.global_argc = argc - (optind - 1);
10095 G.global_argv = argv + (optind - 1);
10096 G.global_argv[0] = argv[0];
10099 G.root_pid = getpid();
10100 G.root_ppid = getppid();
10103 /* If we are login shell... */
10104 if (flags & OPT_login) {
10106 debug_printf("sourcing /etc/profile\n");
10107 input = hfopen("/etc/profile");
10108 if (input != NULL) {
10109 install_special_sighandlers();
10110 parse_and_run_file(input);
10113 /* bash: after sourcing /etc/profile,
10114 * tries to source (in the given order):
10115 * ~/.bash_profile, ~/.bash_login, ~/.profile,
10116 * stopping on first found. --noprofile turns this off.
10117 * bash also sources ~/.bash_logout on exit.
10118 * If called as sh, skips .bash_XXX files.
10122 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10123 if (!(flags & OPT_s) && G.global_argv[1]) {
10126 * "bash <script>" (which is never interactive (unless -i?))
10127 * sources $BASH_ENV here (without scanning $PATH).
10128 * If called as sh, does the same but with $ENV.
10129 * Also NB, per POSIX, $ENV should undergo parameter expansion.
10133 debug_printf("running script '%s'\n", G.global_argv[0]);
10134 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
10135 input = hfopen(G.global_argv[0]);
10137 bb_simple_perror_msg_and_die(G.global_argv[0]);
10139 xfunc_error_retval = 1;
10140 install_special_sighandlers();
10141 parse_and_run_file(input);
10142 #if ENABLE_FEATURE_CLEAN_UP
10148 /* Up to here, shell was non-interactive. Now it may become one.
10149 * NB: don't forget to (re)run install_special_sighandlers() as needed.
10152 /* A shell is interactive if the '-i' flag was given,
10153 * or if all of the following conditions are met:
10155 * no arguments remaining or the -s flag given
10156 * standard input is a terminal
10157 * standard output is a terminal
10158 * Refer to Posix.2, the description of the 'sh' utility.
10160 #if ENABLE_HUSH_JOB
10161 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10162 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10163 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10164 if (G_saved_tty_pgrp < 0)
10165 G_saved_tty_pgrp = 0;
10167 /* try to dup stdin to high fd#, >= 255 */
10168 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10169 if (G_interactive_fd < 0) {
10170 /* try to dup to any fd */
10171 G_interactive_fd = dup(STDIN_FILENO);
10172 if (G_interactive_fd < 0) {
10174 G_interactive_fd = 0;
10175 G_saved_tty_pgrp = 0;
10178 // TODO: track & disallow any attempts of user
10179 // to (inadvertently) close/redirect G_interactive_fd
10181 debug_printf("interactive_fd:%d\n", G_interactive_fd);
10182 if (G_interactive_fd) {
10183 close_on_exec_on(G_interactive_fd);
10185 if (G_saved_tty_pgrp) {
10186 /* If we were run as 'hush &', sleep until we are
10187 * in the foreground (tty pgrp == our pgrp).
10188 * If we get started under a job aware app (like bash),
10189 * make sure we are now in charge so we don't fight over
10190 * who gets the foreground */
10192 pid_t shell_pgrp = getpgrp();
10193 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10194 if (G_saved_tty_pgrp == shell_pgrp)
10196 /* send TTIN to ourself (should stop us) */
10197 kill(- shell_pgrp, SIGTTIN);
10201 /* Install more signal handlers */
10202 install_special_sighandlers();
10204 if (G_saved_tty_pgrp) {
10205 /* Set other signals to restore saved_tty_pgrp */
10206 install_fatal_sighandlers();
10207 /* Put ourselves in our own process group
10208 * (bash, too, does this only if ctty is available) */
10209 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10210 /* Grab control of the terminal */
10211 tcsetpgrp(G_interactive_fd, getpid());
10213 enable_restore_tty_pgrp_on_exit();
10215 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10217 const char *hp = get_local_var_value("HISTFILE");
10219 hp = get_local_var_value("HOME");
10221 hp = concat_path_file(hp, ".hush_history");
10226 G.line_input_state->hist_file = hp;
10227 //set_local_var(xasprintf("HISTFILE=%s", ...));
10229 # if ENABLE_FEATURE_SH_HISTFILESIZE
10230 hp = get_local_var_value("HISTFILESIZE");
10231 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10236 install_special_sighandlers();
10238 #elif ENABLE_HUSH_INTERACTIVE
10239 /* No job control compiled in, only prompt/line editing */
10240 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10241 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10242 if (G_interactive_fd < 0) {
10243 /* try to dup to any fd */
10244 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
10245 if (G_interactive_fd < 0)
10247 G_interactive_fd = 0;
10250 if (G_interactive_fd) {
10251 close_on_exec_on(G_interactive_fd);
10253 install_special_sighandlers();
10255 /* We have interactiveness code disabled */
10256 install_special_sighandlers();
10259 * if interactive but not a login shell, sources ~/.bashrc
10260 * (--norc turns this off, --rcfile <file> overrides)
10263 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
10264 /* note: ash and hush share this string */
10265 printf("\n\n%s %s\n"
10266 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10269 "hush - the humble shell"
10273 parse_and_run_file(hfopen(NULL)); /* stdin */
10276 hush_exit(G.last_exitcode);
10283 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
10288 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
10289 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
10291 int argc = string_array_len(argv);
10292 return applet_main_func(argc, argv);
10295 #if ENABLE_HUSH_TEST || BASH_TEST2
10296 static int FAST_FUNC builtin_test(char **argv)
10298 return run_applet_main(argv, test_main);
10301 #if ENABLE_HUSH_ECHO
10302 static int FAST_FUNC builtin_echo(char **argv)
10304 return run_applet_main(argv, echo_main);
10307 #if ENABLE_HUSH_PRINTF
10308 static int FAST_FUNC builtin_printf(char **argv)
10310 return run_applet_main(argv, printf_main);
10314 #if ENABLE_HUSH_HELP
10315 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10317 const struct built_in_command *x;
10320 "Built-in commands:\n"
10321 "------------------\n");
10322 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10324 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10326 return EXIT_SUCCESS;
10330 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
10331 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10333 show_history(G.line_input_state);
10334 return EXIT_SUCCESS;
10338 static char **skip_dash_dash(char **argv)
10341 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10346 static int FAST_FUNC builtin_cd(char **argv)
10348 const char *newdir;
10350 argv = skip_dash_dash(argv);
10352 if (newdir == NULL) {
10353 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
10354 * bash says "bash: cd: HOME not set" and does nothing
10357 const char *home = get_local_var_value("HOME");
10358 newdir = home ? home : "/";
10360 if (chdir(newdir)) {
10361 /* Mimic bash message exactly */
10362 bb_perror_msg("cd: %s", newdir);
10363 return EXIT_FAILURE;
10365 /* Read current dir (get_cwd(1) is inside) and set PWD.
10366 * Note: do not enforce exporting. If PWD was unset or unexported,
10367 * set it again, but do not export. bash does the same.
10369 set_pwd_var(/*flag:*/ 0);
10370 return EXIT_SUCCESS;
10373 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10376 return EXIT_SUCCESS;
10379 static int FAST_FUNC builtin_eval(char **argv)
10381 argv = skip_dash_dash(argv);
10384 return EXIT_SUCCESS;
10386 IF_HUSH_MODE_X(G.x_mode_depth++;)
10387 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
10390 * eval "echo Hi; done" ("done" is syntax error):
10391 * "echo Hi" will not execute too.
10393 parse_and_run_string(argv[0]);
10395 /* "The eval utility shall construct a command by
10396 * concatenating arguments together, separating
10397 * each with a <space> character."
10403 len += strlen(*pp) + 1;
10405 str = p = xmalloc(len);
10408 p = stpcpy(p, *pp);
10414 parse_and_run_string(str);
10417 IF_HUSH_MODE_X(G.x_mode_depth--;)
10418 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
10419 return G.last_exitcode;
10422 static int FAST_FUNC builtin_exec(char **argv)
10424 argv = skip_dash_dash(argv);
10425 if (argv[0] == NULL)
10426 return EXIT_SUCCESS; /* bash does this */
10428 /* Careful: we can end up here after [v]fork. Do not restore
10429 * tty pgrp then, only top-level shell process does that */
10430 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10431 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10433 /* Saved-redirect fds, script fds and G_interactive_fd are still
10434 * open here. However, they are all CLOEXEC, and execv below
10435 * closes them. Try interactive "exec ls -l /proc/self/fd",
10436 * it should show no extra open fds in the "ls" process.
10437 * If we'd try to run builtins/NOEXECs, this would need improving.
10439 //close_saved_fds_and_FILE_fds();
10441 /* TODO: if exec fails, bash does NOT exit! We do.
10442 * We'll need to undo trap cleanup (it's inside execvp_or_die)
10443 * and tcsetpgrp, and this is inherently racy.
10445 execvp_or_die(argv);
10448 static int FAST_FUNC builtin_exit(char **argv)
10450 debug_printf_exec("%s()\n", __func__);
10452 /* interactive bash:
10453 * # trap "echo EEE" EXIT
10456 * There are stopped jobs.
10457 * (if there are _stopped_ jobs, running ones don't count)
10460 * EEE (then bash exits)
10462 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
10465 /* note: EXIT trap is run by hush_exit */
10466 argv = skip_dash_dash(argv);
10467 if (argv[0] == NULL)
10468 hush_exit(G.last_exitcode);
10469 /* mimic bash: exit 123abc == exit 255 + error msg */
10470 xfunc_error_retval = 255;
10471 /* bash: exit -2 == exit 254, no error msg */
10472 hush_exit(xatoi(argv[0]) & 0xff);
10475 #if ENABLE_HUSH_TYPE
10476 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10477 static int FAST_FUNC builtin_type(char **argv)
10479 int ret = EXIT_SUCCESS;
10485 if (0) {} /* make conditional compile easier below */
10486 /*else if (find_alias(*argv))
10487 type = "an alias";*/
10488 #if ENABLE_HUSH_FUNCTIONS
10489 else if (find_function(*argv))
10490 type = "a function";
10492 else if (find_builtin(*argv))
10493 type = "a shell builtin";
10494 else if ((path = find_in_path(*argv)) != NULL)
10497 bb_error_msg("type: %s: not found", *argv);
10498 ret = EXIT_FAILURE;
10502 printf("%s is %s\n", *argv, type);
10510 #if ENABLE_HUSH_READ
10511 /* Interruptibility of read builtin in bash
10512 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10514 * Empty trap makes read ignore corresponding signal, for any signal.
10517 * - terminates non-interactive shell;
10518 * - interrupts read in interactive shell;
10519 * if it has non-empty trap:
10520 * - executes trap and returns to command prompt in interactive shell;
10521 * - executes trap and returns to read in non-interactive shell;
10523 * - is ignored (does not interrupt) read in interactive shell;
10524 * - terminates non-interactive shell;
10525 * if it has non-empty trap:
10526 * - executes trap and returns to read;
10528 * - terminates shell (regardless of interactivity);
10529 * if it has non-empty trap:
10530 * - executes trap and returns to read;
10531 * SIGCHLD from children:
10532 * - does not interrupt read regardless of interactivity:
10533 * try: sleep 1 & read x; echo $x
10535 static int FAST_FUNC builtin_read(char **argv)
10538 struct builtin_read_params params;
10540 memset(¶ms, 0, sizeof(params));
10542 /* "!": do not abort on errors.
10543 * Option string must start with "sr" to match BUILTIN_READ_xxx
10545 params.read_flags = getopt32(argv,
10547 "!srn:p:t:u:d:", ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u, ¶ms.opt_d
10549 "!srn:p:t:u:", ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u
10552 if ((uint32_t)params.read_flags == (uint32_t)-1)
10553 return EXIT_FAILURE;
10555 params.argv = argv;
10556 params.setvar = set_local_var_from_halves;
10557 params.ifs = get_local_var_value("IFS"); /* can be NULL */
10560 r = shell_builtin_read(¶ms);
10562 if ((uintptr_t)r == 1 && errno == EINTR) {
10563 unsigned sig = check_and_run_traps();
10568 if ((uintptr_t)r > 1) {
10569 bb_error_msg("%s", r);
10570 r = (char*)(uintptr_t)1;
10573 return (uintptr_t)r;
10577 #if ENABLE_HUSH_UMASK
10578 static int FAST_FUNC builtin_umask(char **argv)
10585 argv = skip_dash_dash(argv);
10587 mode_t old_mask = mask;
10589 /* numeric umasks are taken as-is */
10590 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10591 if (!isdigit(argv[0][0]))
10593 mask = bb_parse_mode(argv[0], mask);
10594 if (!isdigit(argv[0][0]))
10596 if ((unsigned)mask > 0777) {
10599 * bash: umask: 'q': invalid symbolic mode operator
10600 * bash: umask: 999: octal number out of range
10602 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10607 printf("%04o\n", (unsigned) mask);
10608 /* fall through and restore mask which we set to 0 */
10612 return !rc; /* rc != 0 - success */
10616 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
10617 static void print_escaped(const char *s)
10622 const char *p = strchrnul(s, '\'');
10623 /* print 'xxxx', possibly just '' */
10624 printf("'%.*s'", (int)(p - s), s);
10629 /* s points to '; print "'''...'''" */
10631 do putchar('\''); while (*++s == '\'');
10637 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
10638 static int helper_export_local(char **argv, unsigned flags)
10641 char *name = *argv;
10642 char *name_end = strchrnul(name, '=');
10644 /* So far we do not check that name is valid (TODO?) */
10646 if (*name_end == '\0') {
10647 struct variable *var, **vpp;
10649 vpp = get_ptr_to_local_var(name, name_end - name);
10650 var = vpp ? *vpp : NULL;
10652 if (flags & SETFLAG_UNEXPORT) {
10653 /* export -n NAME (without =VALUE) */
10655 var->flg_export = 0;
10656 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10658 } /* else: export -n NOT_EXISTING_VAR: no-op */
10661 if (flags & SETFLAG_EXPORT) {
10662 /* export NAME (without =VALUE) */
10664 var->flg_export = 1;
10665 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10666 putenv(var->varstr);
10670 if (flags & SETFLAG_MAKE_RO) {
10671 /* readonly NAME (without =VALUE) */
10673 var->flg_read_only = 1;
10677 # if ENABLE_HUSH_LOCAL
10678 /* Is this "local" bltin? */
10679 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
10680 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10681 if (var && var->var_nest_level == lvl) {
10682 /* "local x=abc; ...; local x" - ignore second local decl */
10687 /* Exporting non-existing variable.
10688 * bash does not put it in environment,
10689 * but remembers that it is exported,
10690 * and does put it in env when it is set later.
10691 * We just set it to "" and export.
10693 /* Or, it's "local NAME" (without =VALUE).
10694 * bash sets the value to "".
10696 /* Or, it's "readonly NAME" (without =VALUE).
10697 * bash remembers NAME and disallows its creation
10700 name = xasprintf("%s=", name);
10702 /* (Un)exporting/making local NAME=VALUE */
10703 name = xstrdup(name);
10705 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
10706 if (set_local_var(name, flags))
10707 return EXIT_FAILURE;
10709 return EXIT_SUCCESS;
10713 #if ENABLE_HUSH_EXPORT
10714 static int FAST_FUNC builtin_export(char **argv)
10716 unsigned opt_unexport;
10718 #if ENABLE_HUSH_EXPORT_N
10719 /* "!": do not abort on errors */
10720 opt_unexport = getopt32(argv, "!n");
10721 if (opt_unexport == (uint32_t)-1)
10722 return EXIT_FAILURE;
10729 if (argv[0] == NULL) {
10730 char **e = environ;
10736 /* ash emits: export VAR='VAL'
10737 * bash: declare -x VAR="VAL"
10738 * we follow ash example */
10739 const char *s = *e++;
10740 const char *p = strchr(s, '=');
10742 if (!p) /* wtf? take next variable */
10745 printf("export %.*s", (int)(p - s) + 1, s);
10746 print_escaped(p + 1);
10750 /*fflush_all(); - done after each builtin anyway */
10752 return EXIT_SUCCESS;
10755 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
10759 #if ENABLE_HUSH_LOCAL
10760 static int FAST_FUNC builtin_local(char **argv)
10762 if (G.func_nest_level == 0) {
10763 bb_error_msg("%s: not in a function", argv[0]);
10764 return EXIT_FAILURE; /* bash compat */
10767 /* Since all builtins run in a nested variable level,
10768 * need to use level - 1 here. Or else the variable will be removed at once
10769 * after builtin returns.
10771 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
10775 #if ENABLE_HUSH_READONLY
10776 static int FAST_FUNC builtin_readonly(char **argv)
10779 if (*argv == NULL) {
10780 /* bash: readonly [-p]: list all readonly VARs
10781 * (-p has no effect in bash)
10783 struct variable *e;
10784 for (e = G.top_var; e; e = e->next) {
10785 if (e->flg_read_only) {
10786 //TODO: quote value: readonly VAR='VAL'
10787 printf("readonly %s\n", e->varstr);
10790 return EXIT_SUCCESS;
10792 return helper_export_local(argv, SETFLAG_MAKE_RO);
10796 #if ENABLE_HUSH_UNSET
10797 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10798 static int FAST_FUNC builtin_unset(char **argv)
10803 /* "!": do not abort on errors */
10804 /* "+": stop at 1st non-option */
10805 opts = getopt32(argv, "!+vf");
10806 if (opts == (unsigned)-1)
10807 return EXIT_FAILURE;
10809 bb_error_msg("unset: -v and -f are exclusive");
10810 return EXIT_FAILURE;
10814 ret = EXIT_SUCCESS;
10816 if (!(opts & 2)) { /* not -f */
10817 if (unset_local_var(*argv)) {
10818 /* unset <nonexistent_var> doesn't fail.
10819 * Error is when one tries to unset RO var.
10820 * Message was printed by unset_local_var. */
10821 ret = EXIT_FAILURE;
10824 # if ENABLE_HUSH_FUNCTIONS
10835 #if ENABLE_HUSH_SET
10836 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10837 * built-in 'set' handler
10839 * set [-abCefhmnuvx] [-o option] [argument...]
10840 * set [+abCefhmnuvx] [+o option] [argument...]
10841 * set -- [argument...]
10844 * Implementations shall support the options in both their hyphen and
10845 * plus-sign forms. These options can also be specified as options to sh.
10847 * Write out all variables and their values: set
10848 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10849 * Turn on the -x and -v options: set -xv
10850 * Unset all positional parameters: set --
10851 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10852 * Set the positional parameters to the expansion of x, even if x expands
10853 * with a leading '-' or '+': set -- $x
10855 * So far, we only support "set -- [argument...]" and some of the short names.
10857 static int FAST_FUNC builtin_set(char **argv)
10860 char **pp, **g_argv;
10861 char *arg = *++argv;
10864 struct variable *e;
10865 for (e = G.top_var; e; e = e->next)
10867 return EXIT_SUCCESS;
10871 if (strcmp(arg, "--") == 0) {
10875 if (arg[0] != '+' && arg[0] != '-')
10877 for (n = 1; arg[n]; ++n) {
10878 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10880 if (arg[n] == 'o' && argv[1])
10883 } while ((arg = *++argv) != NULL);
10884 /* Now argv[0] is 1st argument */
10887 return EXIT_SUCCESS;
10890 /* NB: G.global_argv[0] ($0) is never freed/changed */
10891 g_argv = G.global_argv;
10892 if (G.global_args_malloced) {
10898 G.global_args_malloced = 1;
10899 pp = xzalloc(sizeof(pp[0]) * 2);
10900 pp[0] = g_argv[0]; /* retain $0 */
10903 /* This realloc's G.global_argv */
10904 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10906 G.global_argc = 1 + string_array_len(pp + 1);
10908 return EXIT_SUCCESS;
10910 /* Nothing known, so abort */
10912 bb_error_msg("%s: %s: invalid option", "set", arg);
10913 return EXIT_FAILURE;
10917 static int FAST_FUNC builtin_shift(char **argv)
10920 argv = skip_dash_dash(argv);
10922 n = bb_strtou(argv[0], NULL, 10);
10923 if (errno || n < 0) {
10924 /* shared string with ash.c */
10925 bb_error_msg("Illegal number: %s", argv[0]);
10927 * ash aborts in this case.
10928 * bash prints error message and set $? to 1.
10929 * Interestingly, for "shift 99999" bash does not
10930 * print error message, but does set $? to 1
10931 * (and does no shifting at all).
10935 if (n >= 0 && n < G.global_argc) {
10936 if (G_global_args_malloced) {
10939 free(G.global_argv[m++]);
10941 G.global_argc -= n;
10942 memmove(&G.global_argv[1], &G.global_argv[n+1],
10943 G.global_argc * sizeof(G.global_argv[0]));
10944 return EXIT_SUCCESS;
10946 return EXIT_FAILURE;
10949 #if ENABLE_HUSH_GETOPTS
10950 static int FAST_FUNC builtin_getopts(char **argv)
10952 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10955 If a required argument is not found, and getopts is not silent,
10956 a question mark (?) is placed in VAR, OPTARG is unset, and a
10957 diagnostic message is printed. If getopts is silent, then a
10958 colon (:) is placed in VAR and OPTARG is set to the option
10961 Test that VAR is a valid variable name?
10963 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10966 const char *cp, *optstring, *var;
10967 int c, n, exitcode, my_opterr;
10970 optstring = *++argv;
10971 if (!optstring || !(var = *++argv)) {
10972 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10973 return EXIT_FAILURE;
10977 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10979 argv = G.global_argv;
10983 if (optstring[0] != ':') {
10984 cp = get_local_var_value("OPTERR");
10985 /* 0 if "OPTERR=0", 1 otherwise */
10986 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
10989 /* getopts stops on first non-option. Add "+" to force that */
10990 /*if (optstring[0] != '+')*/ {
10991 char *s = alloca(strlen(optstring) + 2);
10992 sprintf(s, "+%s", optstring);
10996 /* Naively, now we should just
10997 * cp = get_local_var_value("OPTIND");
10998 * optind = cp ? atoi(cp) : 0;
11000 * opterr = my_opterr;
11001 * c = getopt(string_array_len(argv), argv, optstring);
11002 * and be done? Not so fast...
11003 * Unlike normal getopt() usage in C programs, here
11004 * each successive call will (usually) have the same argv[] CONTENTS,
11005 * but not the ADDRESSES. Worse yet, it's possible that between
11006 * invocations of "getopts", there will be calls to shell builtins
11007 * which use getopt() internally. Example:
11008 * while getopts "abc" RES -a -bc -abc de; do
11011 * This would not work correctly: getopt() call inside "unset"
11012 * modifies internal libc state which is tracking position in
11013 * multi-option strings ("-abc"). At best, it can skip options
11014 * or return the same option infinitely. With glibc implementation
11015 * of getopt(), it would use outright invalid pointers and return
11016 * garbage even _without_ "unset" mangling internal state.
11018 * We resort to resetting getopt() state and calling it N times,
11019 * until we get Nth result (or failure).
11020 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11024 n = string_array_len(argv);
11027 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11028 c = getopt(n, argv, optstring);
11032 } while (count <= G.getopt_count);
11034 /* Set OPTIND. Prevent resetting of the magic counter! */
11035 set_local_var_from_halves("OPTIND", utoa(optind));
11036 G.getopt_count = count; /* "next time, give me N+1'th result" */
11037 GETOPT_RESET(); /* just in case */
11040 /* Always set or unset, never left as-is, even on exit/error:
11041 * "If no option was found, or if the option that was found
11042 * does not have an option-argument, OPTARG shall be unset."
11046 /* If ":optstring" and unknown option is seen,
11047 * it is stored to OPTARG.
11049 if (optstring[1] == ':') {
11055 set_local_var_from_halves("OPTARG", cp);
11057 unset_local_var("OPTARG");
11059 /* Convert -1 to "?" */
11060 exitcode = EXIT_SUCCESS;
11061 if (c < 0) { /* -1: end of options */
11062 exitcode = EXIT_FAILURE;
11068 set_local_var_from_halves(var, cbuf);
11074 static int FAST_FUNC builtin_source(char **argv)
11076 char *arg_path, *filename;
11079 char *args_need_save;
11080 #if ENABLE_HUSH_FUNCTIONS
11084 argv = skip_dash_dash(argv);
11085 filename = argv[0];
11087 /* bash says: "bash: .: filename argument required" */
11088 return 2; /* bash compat */
11091 if (!strchr(filename, '/')) {
11092 arg_path = find_in_path(filename);
11094 filename = arg_path;
11095 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
11097 bb_simple_perror_msg(filename);
11098 return EXIT_FAILURE;
11101 input = hfopen(filename);
11104 bb_perror_msg("%s", filename);
11105 /* POSIX: non-interactive shell should abort here,
11106 * not merely fail. So far no one complained :)
11108 return EXIT_FAILURE;
11111 #if ENABLE_HUSH_FUNCTIONS
11112 sv_flg = G_flag_return_in_progress;
11113 /* "we are inside sourced file, ok to use return" */
11114 G_flag_return_in_progress = -1;
11116 args_need_save = argv[1]; /* used as a boolean variable */
11117 if (args_need_save)
11118 save_and_replace_G_args(&sv, argv);
11120 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11121 G.last_exitcode = 0;
11122 parse_and_run_file(input);
11125 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11126 restore_G_args(&sv, argv);
11127 #if ENABLE_HUSH_FUNCTIONS
11128 G_flag_return_in_progress = sv_flg;
11131 return G.last_exitcode;
11134 #if ENABLE_HUSH_TRAP
11135 static int FAST_FUNC builtin_trap(char **argv)
11141 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
11146 /* No args: print all trapped */
11147 for (i = 0; i < NSIG; ++i) {
11149 printf("trap -- ");
11150 print_escaped(G_traps[i]);
11151 /* note: bash adds "SIG", but only if invoked
11152 * as "bash". If called as "sh", or if set -o posix,
11153 * then it prints short signal names.
11154 * We are printing short names: */
11155 printf(" %s\n", get_signame(i));
11158 /*fflush_all(); - done after each builtin anyway */
11159 return EXIT_SUCCESS;
11163 /* If first arg is a number: reset all specified signals */
11164 sig = bb_strtou(*argv, NULL, 10);
11168 ret = EXIT_SUCCESS;
11170 sighandler_t handler;
11172 sig = get_signum(*argv++);
11174 ret = EXIT_FAILURE;
11175 /* Mimic bash message exactly */
11176 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
11180 free(G_traps[sig]);
11181 G_traps[sig] = xstrdup(new_cmd);
11183 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
11184 get_signame(sig), sig, G_traps[sig]);
11186 /* There is no signal for 0 (EXIT) */
11191 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11193 /* We are removing trap handler */
11194 handler = pick_sighandler(sig);
11195 install_sighandler(sig, handler);
11200 if (!argv[1]) { /* no second arg */
11201 bb_error_msg("trap: invalid arguments");
11202 return EXIT_FAILURE;
11205 /* First arg is "-": reset all specified to default */
11206 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11207 /* Everything else: set arg as signal handler
11208 * (includes "" case, which ignores signal) */
11209 if (argv[0][0] == '-') {
11210 if (argv[0][1] == '\0') { /* "-" */
11211 /* new_cmd remains NULL: "reset these sigs" */
11214 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11217 /* else: "-something", no special meaning */
11222 goto process_sig_list;
11226 #if ENABLE_HUSH_JOB
11227 static struct pipe *parse_jobspec(const char *str)
11232 if (sscanf(str, "%%%u", &jobnum) != 1) {
11234 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11236 bb_error_msg("bad argument '%s'", str);
11239 /* It is "%%", "%+" or "%" - current job */
11240 jobnum = G.last_jobid;
11242 bb_error_msg("no current job");
11246 for (pi = G.job_list; pi; pi = pi->next) {
11247 if (pi->jobid == jobnum) {
11251 bb_error_msg("%u: no such job", jobnum);
11255 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11258 const char *status_string;
11260 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11261 for (job = G.job_list; job; job = job->next) {
11262 if (job->alive_cmds == job->stopped_cmds)
11263 status_string = "Stopped";
11265 status_string = "Running";
11267 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11270 clean_up_last_dead_job();
11272 return EXIT_SUCCESS;
11275 /* built-in 'fg' and 'bg' handler */
11276 static int FAST_FUNC builtin_fg_bg(char **argv)
11281 if (!G_interactive_fd)
11282 return EXIT_FAILURE;
11284 /* If they gave us no args, assume they want the last backgrounded task */
11286 for (pi = G.job_list; pi; pi = pi->next) {
11287 if (pi->jobid == G.last_jobid) {
11291 bb_error_msg("%s: no current job", argv[0]);
11292 return EXIT_FAILURE;
11295 pi = parse_jobspec(argv[1]);
11297 return EXIT_FAILURE;
11299 /* TODO: bash prints a string representation
11300 * of job being foregrounded (like "sleep 1 | cat") */
11301 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
11302 /* Put the job into the foreground. */
11303 tcsetpgrp(G_interactive_fd, pi->pgrp);
11306 /* Restart the processes in the job */
11307 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11308 for (i = 0; i < pi->num_cmds; i++) {
11309 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
11311 pi->stopped_cmds = 0;
11313 i = kill(- pi->pgrp, SIGCONT);
11315 if (errno == ESRCH) {
11316 delete_finished_job(pi);
11317 return EXIT_SUCCESS;
11319 bb_perror_msg("kill (SIGCONT)");
11322 if (argv[0][0] == 'f') {
11323 remove_job_from_table(pi); /* FG job shouldn't be in job table */
11324 return checkjobs_and_fg_shell(pi);
11326 return EXIT_SUCCESS;
11330 #if ENABLE_HUSH_KILL
11331 static int FAST_FUNC builtin_kill(char **argv)
11335 # if ENABLE_HUSH_JOB
11336 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11344 if (argv[i][0] != '%')
11347 * "kill %N" - job kill
11348 * Converting to pgrp / pid kill
11350 pi = parse_jobspec(argv[i]);
11352 /* Eat bad jobspec */
11356 argv[j - 1] = argv[j];
11363 * In jobs started under job control, we signal
11364 * entire process group by kill -PGRP_ID.
11365 * This happens, f.e., in interactive shell.
11367 * Otherwise, we signal each child via
11368 * kill PID1 PID2 PID3.
11370 * sh -c 'sleep 1|sleep 1 & kill %1'
11371 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11372 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11374 n = G_interactive_fd ? 1 : pi->num_cmds;
11375 dst = alloca(n * sizeof(int)*4);
11377 if (G_interactive_fd)
11378 dst += sprintf(dst, " -%u", (int)pi->pgrp);
11379 else for (j = 0; j < n; j++) {
11380 struct command *cmd = &pi->cmds[j];
11381 /* Skip exited members of the job */
11385 * kill_main has matching code to expect
11386 * leading space. Needed to not confuse
11387 * negative pids with "kill -SIGNAL_NO" syntax
11389 dst += sprintf(dst, " %u", (int)cmd->pid);
11392 } while (argv[++i]);
11396 if (argv[1] || ret == 0) {
11397 ret = run_applet_main(argv, kill_main);
11399 /* else: ret = 1, "kill %bad_jobspec" case */
11404 #if ENABLE_HUSH_WAIT
11405 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
11406 #if !ENABLE_HUSH_JOB
11407 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11409 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
11416 if (!sigisemptyset(&G.pending_set))
11419 /* waitpid is not interruptible by SA_RESTARTed
11420 * signals which we use. Thus, this ugly dance:
11423 /* Make sure possible SIGCHLD is stored in kernel's
11424 * pending signal mask before we call waitpid.
11425 * Or else we may race with SIGCHLD, lose it,
11426 * and get stuck in sigsuspend...
11428 sigfillset(&oldset); /* block all signals, remember old set */
11429 sigprocmask(SIG_SETMASK, &oldset, &oldset);
11431 if (!sigisemptyset(&G.pending_set)) {
11432 /* Crap! we raced with some signal! */
11436 /*errno = 0; - checkjobs does this */
11437 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
11438 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
11439 debug_printf_exec("checkjobs:%d\n", ret);
11440 #if ENABLE_HUSH_JOB
11441 if (waitfor_pipe) {
11442 int rcode = job_exited_or_stopped(waitfor_pipe);
11443 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11446 sigprocmask(SIG_SETMASK, &oldset, NULL);
11451 /* if ECHILD, there are no children (ret is -1 or 0) */
11452 /* if ret == 0, no children changed state */
11453 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
11454 if (errno == ECHILD || ret) {
11456 if (ret < 0) /* if ECHILD, may need to fix "ret" */
11458 sigprocmask(SIG_SETMASK, &oldset, NULL);
11461 /* Wait for SIGCHLD or any other signal */
11462 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11463 /* Note: sigsuspend invokes signal handler */
11464 sigsuspend(&oldset);
11466 sigprocmask(SIG_SETMASK, &oldset, NULL);
11468 /* So, did we get a signal? */
11469 sig = check_and_run_traps();
11470 if (sig /*&& sig != SIGCHLD - always true */) {
11471 /* Do this for any (non-ignored) signal, not only for ^C */
11475 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11480 static int FAST_FUNC builtin_wait(char **argv)
11485 argv = skip_dash_dash(argv);
11486 if (argv[0] == NULL) {
11487 /* Don't care about wait results */
11488 /* Note 1: must wait until there are no more children */
11489 /* Note 2: must be interruptible */
11491 * $ sleep 3 & sleep 6 & wait
11492 * [1] 30934 sleep 3
11493 * [2] 30935 sleep 6
11496 * $ sleep 3 & sleep 6 & wait
11497 * [1] 30936 sleep 3
11498 * [2] 30937 sleep 6
11500 * ^C <-- after ~4 sec from keyboard
11503 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
11507 pid_t pid = bb_strtou(*argv, NULL, 10);
11508 if (errno || pid <= 0) {
11509 #if ENABLE_HUSH_JOB
11510 if (argv[0][0] == '%') {
11511 struct pipe *wait_pipe;
11512 ret = 127; /* bash compat for bad jobspecs */
11513 wait_pipe = parse_jobspec(*argv);
11515 ret = job_exited_or_stopped(wait_pipe);
11517 ret = wait_for_child_or_signal(wait_pipe, 0);
11519 /* waiting on "last dead job" removes it */
11520 clean_up_last_dead_job();
11523 /* else: parse_jobspec() already emitted error msg */
11527 /* mimic bash message */
11528 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
11529 ret = EXIT_FAILURE;
11530 continue; /* bash checks all argv[] */
11533 /* Do we have such child? */
11534 ret = waitpid(pid, &status, WNOHANG);
11538 if (errno == ECHILD) {
11539 if (pid == G.last_bg_pid) {
11540 /* "wait $!" but last bg task has already exited. Try:
11541 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11542 * In bash it prints exitcode 0, then 3.
11543 * In dash, it is 127.
11545 ret = G.last_bg_pid_exitcode;
11547 /* Example: "wait 1". mimic bash message */
11548 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
11552 bb_perror_msg("wait %s", *argv);
11554 continue; /* bash checks all argv[] */
11557 /* Yes, and it still runs */
11558 ret = wait_for_child_or_signal(NULL, pid);
11560 /* Yes, and it just exited */
11561 process_wait_result(NULL, pid, status);
11562 ret = WEXITSTATUS(status);
11563 if (WIFSIGNALED(status))
11564 ret = 128 + WTERMSIG(status);
11572 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11573 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11576 def = bb_strtou(argv[1], NULL, 10);
11577 if (errno || def < def_min || argv[2]) {
11578 bb_error_msg("%s: bad arguments", argv[0]);
11586 #if ENABLE_HUSH_LOOPS
11587 static int FAST_FUNC builtin_break(char **argv)
11590 if (G.depth_of_loop == 0) {
11591 bb_error_msg("%s: only meaningful in a loop", argv[0]);
11592 /* if we came from builtin_continue(), need to undo "= 1" */
11593 G.flag_break_continue = 0;
11594 return EXIT_SUCCESS; /* bash compat */
11596 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
11598 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11599 if (depth == UINT_MAX)
11600 G.flag_break_continue = BC_BREAK;
11601 if (G.depth_of_loop < depth)
11602 G.depth_break_continue = G.depth_of_loop;
11604 return EXIT_SUCCESS;
11607 static int FAST_FUNC builtin_continue(char **argv)
11609 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11610 return builtin_break(argv);
11614 #if ENABLE_HUSH_FUNCTIONS
11615 static int FAST_FUNC builtin_return(char **argv)
11619 if (G_flag_return_in_progress != -1) {
11620 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11621 return EXIT_FAILURE; /* bash compat */
11624 G_flag_return_in_progress = 1;
11627 * out of range: wraps around at 256, does not error out
11628 * non-numeric param:
11629 * f() { false; return qwe; }; f; echo $?
11630 * bash: return: qwe: numeric argument required <== we do this
11631 * 255 <== we also do this
11633 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11638 #if ENABLE_HUSH_TIMES
11639 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11641 static const uint8_t times_tbl[] ALIGN1 = {
11642 ' ', offsetof(struct tms, tms_utime),
11643 '\n', offsetof(struct tms, tms_stime),
11644 ' ', offsetof(struct tms, tms_cutime),
11645 '\n', offsetof(struct tms, tms_cstime),
11652 clk_tck = bb_clk_tck();
11657 unsigned sec, frac;
11659 t = *(clock_t *)(((char *) &buf) + p[1]);
11661 frac = t % clk_tck;
11662 printf("%um%u.%03us%c",
11663 sec / 60, sec % 60,
11664 (frac * 1000) / clk_tck,
11669 return EXIT_SUCCESS;
11673 #if ENABLE_HUSH_MEMLEAK
11674 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11679 # ifdef M_TRIM_THRESHOLD
11680 /* Optional. Reduces probability of false positives */
11683 /* Crude attempt to find where "free memory" starts,
11684 * sans fragmentation. */
11686 l = (unsigned long)p;
11689 if (l < (unsigned long)p) l = (unsigned long)p;
11695 struct mallinfo mi = mallinfo();
11696 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11697 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11701 if (!G.memleak_value)
11702 G.memleak_value = l;
11704 l -= G.memleak_value;
11711 /* Exitcode is "how many kilobytes we leaked since 1st call" */