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 /*hfclose(fl); - unsafe */
1690 fl = fl->next_hfile;
1694 static int fd_in_HFILEs(int fd)
1696 HFILE *fl = G.HFILE_list;
1700 fl = fl->next_hfile;
1706 /* Helpers for setting new $n and restoring them back
1708 typedef struct save_arg_t {
1712 IF_HUSH_SET(smallint sv_g_malloced;)
1715 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1717 sv->sv_argv0 = argv[0];
1718 sv->sv_g_argv = G.global_argv;
1719 sv->sv_g_argc = G.global_argc;
1720 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1722 argv[0] = G.global_argv[0]; /* retain $0 */
1723 G.global_argv = argv;
1724 IF_HUSH_SET(G.global_args_malloced = 0;)
1726 G.global_argc = 1 + string_array_len(argv + 1);
1729 static void restore_G_args(save_arg_t *sv, char **argv)
1732 if (G.global_args_malloced) {
1733 /* someone ran "set -- arg1 arg2 ...", undo */
1734 char **pp = G.global_argv;
1735 while (*++pp) /* note: does not free $0 */
1737 free(G.global_argv);
1740 argv[0] = sv->sv_argv0;
1741 G.global_argv = sv->sv_g_argv;
1742 G.global_argc = sv->sv_g_argc;
1743 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1747 /* Basic theory of signal handling in shell
1748 * ========================================
1749 * This does not describe what hush does, rather, it is current understanding
1750 * what it _should_ do. If it doesn't, it's a bug.
1751 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1753 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1754 * is finished or backgrounded. It is the same in interactive and
1755 * non-interactive shells, and is the same regardless of whether
1756 * a user trap handler is installed or a shell special one is in effect.
1757 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1758 * backgrounds (i.e. stops) or kills all members of currently running
1761 * Wait builtin is interruptible by signals for which user trap is set
1762 * or by SIGINT in interactive shell.
1764 * Trap handlers will execute even within trap handlers. (right?)
1766 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1767 * except for handlers set to '' (empty string).
1769 * If job control is off, backgrounded commands ("cmd &")
1770 * have SIGINT, SIGQUIT set to SIG_IGN.
1772 * Commands which are run in command substitution ("`cmd`")
1773 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1775 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1776 * by the shell from its parent.
1778 * Signals which differ from SIG_DFL action
1779 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1782 * SIGTERM (interactive): ignore
1783 * SIGHUP (interactive):
1784 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1785 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1786 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1787 * that all pipe members are stopped. Try this in bash:
1788 * while :; do :; done - ^Z does not background it
1789 * (while :; do :; done) - ^Z backgrounds it
1790 * SIGINT (interactive): wait for last pipe, ignore the rest
1791 * of the command line, show prompt. NB: ^C does not send SIGINT
1792 * to interactive shell while shell is waiting for a pipe,
1793 * since shell is bg'ed (is not in foreground process group).
1794 * Example 1: this waits 5 sec, but does not execute ls:
1795 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1796 * Example 2: this does not wait and does not execute ls:
1797 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1798 * Example 3: this does not wait 5 sec, but executes ls:
1799 * "sleep 5; ls -l" + press ^C
1800 * Example 4: this does not wait and does not execute ls:
1801 * "sleep 5 & wait; ls -l" + press ^C
1803 * (What happens to signals which are IGN on shell start?)
1804 * (What happens with signal mask on shell start?)
1806 * Old implementation
1807 * ==================
1808 * We use in-kernel pending signal mask to determine which signals were sent.
1809 * We block all signals which we don't want to take action immediately,
1810 * i.e. we block all signals which need to have special handling as described
1811 * above, and all signals which have traps set.
1812 * After each pipe execution, we extract any pending signals via sigtimedwait()
1815 * unsigned special_sig_mask: a mask of such "special" signals
1816 * sigset_t blocked_set: current blocked signal set
1819 * clear bit in blocked_set unless it is also in special_sig_mask
1820 * "trap 'cmd' SIGxxx":
1821 * set bit in blocked_set (even if 'cmd' is '')
1822 * after [v]fork, if we plan to be a shell:
1823 * unblock signals with special interactive handling
1824 * (child shell is not interactive),
1825 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1826 * after [v]fork, if we plan to exec:
1827 * POSIX says fork clears pending signal mask in child - no need to clear it.
1828 * Restore blocked signal set to one inherited by shell just prior to exec.
1830 * Note: as a result, we do not use signal handlers much. The only uses
1831 * are to count SIGCHLDs
1832 * and to restore tty pgrp on signal-induced exit.
1835 * Standard says "When a subshell is entered, traps that are not being ignored
1836 * are set to the default actions". bash interprets it so that traps which
1837 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1839 * Problem: the above approach makes it unwieldy to catch signals while
1840 * we are in read builtin, or while we read commands from stdin:
1841 * masked signals are not visible!
1843 * New implementation
1844 * ==================
1845 * We record each signal we are interested in by installing signal handler
1846 * for them - a bit like emulating kernel pending signal mask in userspace.
1847 * We are interested in: signals which need to have special handling
1848 * as described above, and all signals which have traps set.
1849 * Signals are recorded in pending_set.
1850 * After each pipe execution, we extract any pending signals
1853 * unsigned special_sig_mask: a mask of shell-special signals.
1854 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1855 * char *traps[sig] if trap for sig is set (even if it's '').
1856 * sigset_t pending_set: set of sigs we received.
1859 * if sig is in special_sig_mask, set handler back to:
1860 * record_pending_signo, or to IGN if it's a tty stop signal
1861 * if sig is in fatal_sig_mask, set handler back to sigexit.
1862 * else: set handler back to SIG_DFL
1863 * "trap 'cmd' SIGxxx":
1864 * set handler to record_pending_signo.
1866 * set handler to SIG_IGN.
1867 * after [v]fork, if we plan to be a shell:
1868 * set signals with special interactive handling to SIG_DFL
1869 * (because child shell is not interactive),
1870 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1871 * after [v]fork, if we plan to exec:
1872 * POSIX says fork clears pending signal mask in child - no need to clear it.
1874 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1875 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1878 * Standard says "When a subshell is entered, traps that are not being ignored
1879 * are set to the default actions". bash interprets it so that traps which
1880 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1883 SPECIAL_INTERACTIVE_SIGS = 0
1888 SPECIAL_JOBSTOP_SIGS = 0
1897 static void record_pending_signo(int sig)
1899 sigaddset(&G.pending_set, sig);
1900 #if ENABLE_HUSH_FAST
1901 if (sig == SIGCHLD) {
1903 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1908 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1910 struct sigaction old_sa;
1912 /* We could use signal() to install handlers... almost:
1913 * except that we need to mask ALL signals while handlers run.
1914 * I saw signal nesting in strace, race window isn't small.
1915 * SA_RESTART is also needed, but in Linux, signal()
1916 * sets SA_RESTART too.
1918 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1919 /* sigfillset(&G.sa.sa_mask); - already done */
1920 /* G.sa.sa_flags = SA_RESTART; - already done */
1921 G.sa.sa_handler = handler;
1922 sigaction(sig, &G.sa, &old_sa);
1923 return old_sa.sa_handler;
1926 static void hush_exit(int exitcode) NORETURN;
1928 static void restore_ttypgrp_and__exit(void) NORETURN;
1929 static void restore_ttypgrp_and__exit(void)
1931 /* xfunc has failed! die die die */
1932 /* no EXIT traps, this is an escape hatch! */
1934 hush_exit(xfunc_error_retval);
1939 /* Needed only on some libc:
1940 * It was observed that on exit(), fgetc'ed buffered data
1941 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1942 * With the net effect that even after fork(), not vfork(),
1943 * exit() in NOEXECed applet in "sh SCRIPT":
1944 * noexec_applet_here
1945 * echo END_OF_SCRIPT
1946 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1947 * This makes "echo END_OF_SCRIPT" executed twice.
1948 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1949 * and in `cmd` handling.
1950 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1952 static void fflush_and__exit(void) NORETURN;
1953 static void fflush_and__exit(void)
1956 _exit(xfunc_error_retval);
1959 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1960 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1961 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1962 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1964 /* Restores tty foreground process group, and exits.
1965 * May be called as signal handler for fatal signal
1966 * (will resend signal to itself, producing correct exit state)
1967 * or called directly with -EXITCODE.
1968 * We also call it if xfunc is exiting.
1970 static void sigexit(int sig) NORETURN;
1971 static void sigexit(int sig)
1973 /* Careful: we can end up here after [v]fork. Do not restore
1974 * tty pgrp then, only top-level shell process does that */
1975 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1976 /* Disable all signals: job control, SIGPIPE, etc.
1977 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1979 sigprocmask_allsigs(SIG_BLOCK);
1980 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1983 /* Not a signal, just exit */
1987 kill_myself_with_sig(sig); /* does not return */
1991 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1992 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1996 static sighandler_t pick_sighandler(unsigned sig)
1998 sighandler_t handler = SIG_DFL;
1999 if (sig < sizeof(unsigned)*8) {
2000 unsigned sigmask = (1 << sig);
2004 if (G_fatal_sig_mask & sigmask)
2008 /* sig has special handling? */
2009 if (G.special_sig_mask & sigmask) {
2010 handler = record_pending_signo;
2011 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
2012 * in order to ignore them: they will be raised
2013 * in an endless loop when we try to do some
2014 * terminal ioctls! We do have to _ignore_ these.
2016 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2023 /* Restores tty foreground process group, and exits. */
2024 static void hush_exit(int exitcode)
2026 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2027 save_history(G.line_input_state);
2031 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
2033 /* argv[0] is unused */
2034 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
2036 G.exiting = 1; /* prevent EXIT trap recursion */
2037 /* Note: G_traps[0] is not cleared!
2038 * "trap" will still show it, if executed
2043 #if ENABLE_FEATURE_CLEAN_UP
2045 struct variable *cur_var;
2046 if (G.cwd != bb_msg_unknown)
2048 cur_var = G.top_var;
2050 struct variable *tmp = cur_var;
2051 if (!cur_var->max_len)
2052 free(cur_var->varstr);
2053 cur_var = cur_var->next;
2061 sigexit(- (exitcode & 0xff));
2068 //TODO: return a mask of ALL handled sigs?
2069 static int check_and_run_traps(void)
2076 if (sigisemptyset(&G.pending_set))
2081 if (sigismember(&G.pending_set, sig)) {
2082 sigdelset(&G.pending_set, sig);
2085 } while (sig < NSIG);
2088 if (G_traps && G_traps[sig]) {
2089 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
2090 if (G_traps[sig][0]) {
2091 /* We have user-defined handler */
2092 smalluint save_rcode;
2094 /* argv[0] is unused */
2095 argv[1] = xstrdup(G_traps[sig]);
2096 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
2098 save_rcode = G.last_exitcode;
2101 //FIXME: shouldn't it be set to 128 + sig instead?
2102 G.last_exitcode = save_rcode;
2104 } /* else: "" trap, ignoring signal */
2107 /* not a trap: special action */
2110 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2116 //TODO: why are we doing this? ash and dash don't do this,
2117 //they have no handler for SIGHUP at all,
2118 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2120 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2121 /* bash is observed to signal whole process groups,
2122 * not individual processes */
2123 for (job = G.job_list; job; job = job->next) {
2126 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2127 if (kill(- job->pgrp, SIGHUP) == 0)
2128 kill(- job->pgrp, SIGCONT);
2133 #if ENABLE_HUSH_FAST
2135 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2137 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2139 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2140 * This simplifies wait builtin a bit.
2144 default: /* ignored: */
2145 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2146 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2148 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2149 * Example: wait is not interrupted by TERM
2150 * in interactive shell, because TERM is ignored.
2159 static const char *get_cwd(int force)
2161 if (force || G.cwd == NULL) {
2162 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2163 * we must not try to free(bb_msg_unknown) */
2164 if (G.cwd == bb_msg_unknown)
2166 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2168 G.cwd = bb_msg_unknown;
2175 * Shell and environment variable support
2177 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2179 struct variable **pp;
2180 struct variable *cur;
2183 while ((cur = *pp) != NULL) {
2184 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2191 static const char* FAST_FUNC get_local_var_value(const char *name)
2193 struct variable **vpp;
2194 unsigned len = strlen(name);
2196 if (G.expanded_assignments) {
2197 char **cpp = G.expanded_assignments;
2200 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2201 return cp + len + 1;
2206 vpp = get_ptr_to_local_var(name, len);
2208 return (*vpp)->varstr + len + 1;
2210 if (strcmp(name, "PPID") == 0)
2211 return utoa(G.root_ppid);
2212 // bash compat: UID? EUID?
2213 #if ENABLE_HUSH_RANDOM_SUPPORT
2214 if (strcmp(name, "RANDOM") == 0)
2215 return utoa(next_random(&G.random_gen));
2220 static void handle_changed_special_names(const char *name, unsigned name_len)
2222 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2223 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2225 cmdedit_update_prompt();
2229 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2232 #if ENABLE_HUSH_LINENO_VAR
2233 if (strncmp(name, "LINENO", 6) == 0) {
2234 G.lineno_var = NULL;
2238 #if ENABLE_HUSH_GETOPTS
2239 if (strncmp(name, "OPTIND", 6) == 0) {
2247 /* str holds "NAME=VAL" and is expected to be malloced.
2248 * We take ownership of it.
2250 #define SETFLAG_EXPORT (1 << 0)
2251 #define SETFLAG_UNEXPORT (1 << 1)
2252 #define SETFLAG_MAKE_RO (1 << 2)
2253 #define SETFLAG_VARLVL_SHIFT 3
2254 static int set_local_var(char *str, unsigned flags)
2256 struct variable **cur_pp;
2257 struct variable *cur;
2258 char *free_me = NULL;
2261 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
2263 eq_sign = strchr(str, '=');
2264 if (HUSH_DEBUG && !eq_sign)
2265 bb_error_msg_and_die("BUG in setvar");
2267 name_len = eq_sign - str + 1; /* including '=' */
2268 cur_pp = &G.top_var;
2269 while ((cur = *cur_pp) != NULL) {
2270 if (strncmp(cur->varstr, str, name_len) != 0) {
2271 cur_pp = &cur->next;
2275 /* We found an existing var with this name */
2276 if (cur->flg_read_only) {
2277 bb_error_msg("%s: readonly variable", str);
2279 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2280 //but export per se succeeds (does put the var in env). We don't mimic that.
2283 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2284 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2289 if (cur->var_nest_level < local_lvl) {
2290 /* bash 3.2.33(1) and exported vars:
2292 * # f() { local z=a; env | grep ^z; }
2298 if (cur->flg_export)
2299 flags |= SETFLAG_EXPORT;
2300 /* New variable is local ("local VAR=VAL" or
2302 * and existing one is global, or local
2303 * on a lower level that new one.
2304 * Remove it from global variable list:
2306 *cur_pp = cur->next;
2307 if (G.shadowed_vars_pp) {
2308 /* Save in "shadowed" list */
2309 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2310 cur->flg_export ? "exported " : "",
2311 cur->varstr, cur->var_nest_level, str, local_lvl
2313 cur->next = *G.shadowed_vars_pp;
2314 *G.shadowed_vars_pp = cur;
2316 /* Came from pseudo_exec_argv(), no need to save: delete it */
2317 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2318 cur->flg_export ? "exported " : "",
2319 cur->varstr, cur->var_nest_level, str, local_lvl
2321 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2322 free_me = cur->varstr; /* then free it later */
2328 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2329 debug_printf_env("assignement '%s' does not change anything\n", str);
2335 /* Replace the value in the found "struct variable" */
2336 if (cur->max_len != 0) {
2337 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
2338 /* This one is from startup env, reuse space */
2339 debug_printf_env("reusing startup env for '%s'\n", str);
2340 strcpy(cur->varstr, str);
2345 goto set_str_and_exp;
2347 /* max_len == 0 signifies "malloced" var, which we can
2348 * (and have to) free. But we can't free(cur->varstr) here:
2349 * if cur->flg_export is 1, it is in the environment.
2350 * We should either unsetenv+free, or wait until putenv,
2351 * then putenv(new)+free(old).
2353 free_me = cur->varstr;
2354 goto set_str_and_exp;
2357 /* Not found or shadowed - create new variable struct */
2358 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
2359 cur = xzalloc(sizeof(*cur));
2360 cur->var_nest_level = local_lvl;
2361 cur->next = *cur_pp;
2367 #if !BB_MMU || ENABLE_HUSH_READONLY
2368 if (flags & SETFLAG_MAKE_RO) {
2369 cur->flg_read_only = 1;
2372 if (flags & SETFLAG_EXPORT)
2373 cur->flg_export = 1;
2374 if (cur->flg_export) {
2375 if (flags & SETFLAG_UNEXPORT) {
2376 cur->flg_export = 0;
2377 /* unsetenv was already done */
2380 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
2381 i = putenv(cur->varstr);
2382 /* only now we can free old exported malloced string */
2389 handle_changed_special_names(cur->varstr, name_len - 1);
2394 /* Used at startup and after each cd */
2395 static void set_pwd_var(unsigned flag)
2397 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2400 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2401 static int unset_local_var_len(const char *name, int name_len)
2403 struct variable *cur;
2404 struct variable **cur_pp;
2406 cur_pp = &G.top_var;
2407 while ((cur = *cur_pp) != NULL) {
2408 if (strncmp(cur->varstr, name, name_len) == 0
2409 && cur->varstr[name_len] == '='
2411 if (cur->flg_read_only) {
2412 bb_error_msg("%s: readonly variable", name);
2413 return EXIT_FAILURE;
2416 *cur_pp = cur->next;
2417 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2418 bb_unsetenv(cur->varstr);
2425 cur_pp = &cur->next;
2428 /* Handle "unset PS1" et al even if did not find the variable to unset */
2429 handle_changed_special_names(name, name_len);
2431 return EXIT_SUCCESS;
2434 static int unset_local_var(const char *name)
2436 return unset_local_var_len(name, strlen(name));
2440 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2441 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
2442 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2444 char *var = xasprintf("%s=%s", name, val);
2445 set_local_var(var, /*flag:*/ 0);
2451 * Helpers for "var1=val1 var2=val2 cmd" feature
2453 static void add_vars(struct variable *var)
2455 struct variable *next;
2459 var->next = G.top_var;
2461 if (var->flg_export) {
2462 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2463 putenv(var->varstr);
2465 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2471 /* We put strings[i] into variable table and possibly putenv them.
2472 * If variable is read only, we can free the strings[i]
2473 * which attempts to overwrite it.
2474 * The strings[] vector itself is freed.
2476 static void set_vars_and_save_old(char **strings)
2485 struct variable *var_p;
2486 struct variable **var_pp;
2489 eq = strchr(*s, '=');
2490 if (HUSH_DEBUG && !eq)
2491 bb_error_msg_and_die("BUG in varexp4");
2492 var_pp = get_ptr_to_local_var(*s, eq - *s);
2495 if (var_p->flg_read_only) {
2497 bb_error_msg("%s: readonly variable", *s);
2499 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2500 * If VAR is readonly, leaving it in the list
2501 * after asssignment error (msg above)
2502 * causes doubled error message later, on unset.
2504 debug_printf_env("removing/freeing '%s' element\n", *s);
2507 do { *p = p[1]; p++; } while (*p);
2510 /* below, set_local_var() with nest level will
2511 * "shadow" (remove) this variable from
2512 * global linked list.
2515 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2516 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2527 static void reinit_unicode_for_hush(void)
2529 /* Unicode support should be activated even if LANG is set
2530 * _during_ shell execution, not only if it was set when
2531 * shell was started. Therefore, re-check LANG every time:
2533 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2534 || ENABLE_UNICODE_USING_LOCALE
2536 const char *s = get_local_var_value("LC_ALL");
2537 if (!s) s = get_local_var_value("LC_CTYPE");
2538 if (!s) s = get_local_var_value("LANG");
2544 * in_str support (strings, and "strings" read from files).
2547 #if ENABLE_HUSH_INTERACTIVE
2548 /* To test correct lineedit/interactive behavior, type from command line:
2554 * It exercises a lot of corner cases.
2556 # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2557 static void cmdedit_update_prompt(void)
2559 G.PS1 = get_local_var_value("PS1");
2562 G.PS2 = get_local_var_value("PS2");
2567 static const char *setup_prompt_string(void)
2569 const char *prompt_str;
2571 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
2573 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2574 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
2575 if (G.promptmode == 0) { /* PS1 */
2576 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2577 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2579 /* bash uses $PWD value, even if it is set by user.
2580 * It uses current dir only if PWD is unset.
2581 * We always use current dir. */
2582 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2586 debug_printf("prompt_str '%s'\n", prompt_str);
2589 static int get_user_input(struct in_str *i)
2592 const char *prompt_str;
2594 prompt_str = setup_prompt_string();
2595 # if ENABLE_FEATURE_EDITING
2597 reinit_unicode_for_hush();
2598 if (G.flag_SIGINT) {
2599 /* There was ^C'ed, make it look prettier: */
2603 /* buglet: SIGINT will not make new prompt to appear _at once_,
2604 * only after <Enter>. (^C works immediately) */
2605 r = read_line_input(G.line_input_state, prompt_str,
2606 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2608 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2611 check_and_run_traps();
2612 if (r != 0 && !G.flag_SIGINT)
2614 /* ^C or SIGINT: repeat */
2615 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2616 write(STDOUT_FILENO, "^C", 2);
2617 G.last_exitcode = 128 + SIGINT;
2620 /* EOF/error detected */
2622 i->peek_buf[0] = r = EOF;
2625 i->p = G.user_input_buf;
2626 return (unsigned char)*i->p++;
2630 if (i->last_char == '\0' || i->last_char == '\n') {
2631 /* Why check_and_run_traps here? Try this interactively:
2632 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2633 * $ <[enter], repeatedly...>
2634 * Without check_and_run_traps, handler never runs.
2636 check_and_run_traps();
2637 fputs(prompt_str, stdout);
2640 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2641 r = hfgetc(i->file);
2642 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2643 * no ^C masking happens during fgetc, no special code for ^C:
2644 * it generates SIGINT as usual.
2646 check_and_run_traps();
2648 G.last_exitcode = 128 + SIGINT;
2655 /* This is the magic location that prints prompts
2656 * and gets data back from the user */
2657 static int fgetc_interactive(struct in_str *i)
2660 /* If it's interactive stdin, get new line. */
2661 if (G_interactive_fd && i->file->is_stdin) {
2662 /* Returns first char (or EOF), the rest is in i->p[] */
2663 ch = get_user_input(i);
2664 G.promptmode = 1; /* PS2 */
2665 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
2667 /* Not stdin: script file, sourced file, etc */
2668 do ch = hfgetc(i->file); while (ch == '\0');
2673 static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
2676 do ch = hfgetc(i->file); while (ch == '\0');
2679 #endif /* INTERACTIVE */
2681 static int i_getch(struct in_str *i)
2686 /* string-based in_str */
2687 ch = (unsigned char)*i->p;
2696 /* FILE-based in_str */
2698 #if ENABLE_FEATURE_EDITING
2699 /* This can be stdin, check line editing char[] buffer */
2700 if (i->p && *i->p != '\0') {
2701 ch = (unsigned char)*i->p++;
2705 /* peek_buf[] is an int array, not char. Can contain EOF. */
2706 ch = i->peek_buf[0];
2708 int ch2 = i->peek_buf[1];
2709 i->peek_buf[0] = ch2;
2710 if (ch2 == 0) /* very likely, avoid redundant write */
2716 ch = fgetc_interactive(i);
2718 debug_printf("file_get: got '%c' %d\n", ch, ch);
2720 #if ENABLE_HUSH_LINENO_VAR
2723 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2729 static int i_peek(struct in_str *i)
2734 /* string-based in_str */
2735 /* Doesn't report EOF on NUL. None of the callers care. */
2736 return (unsigned char)*i->p;
2739 /* FILE-based in_str */
2741 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2742 /* This can be stdin, check line editing char[] buffer */
2743 if (i->p && *i->p != '\0')
2744 return (unsigned char)*i->p;
2746 /* peek_buf[] is an int array, not char. Can contain EOF. */
2747 ch = i->peek_buf[0];
2751 /* Need to get a new char */
2752 ch = fgetc_interactive(i);
2753 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2755 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2756 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2762 i->peek_buf[0] = ch;
2763 /*i->peek_buf[1] = 0; - already is */
2767 /* Only ever called if i_peek() was called, and did not return EOF.
2768 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2769 * not end-of-line. Therefore we never need to read a new editing line here.
2771 static int i_peek2(struct in_str *i)
2775 /* There are two cases when i->p[] buffer exists.
2776 * (1) it's a string in_str.
2777 * (2) It's a file, and we have a saved line editing buffer.
2778 * In both cases, we know that i->p[0] exists and not NUL, and
2779 * the peek2 result is in i->p[1].
2782 return (unsigned char)i->p[1];
2784 /* Now we know it is a file-based in_str. */
2786 /* peek_buf[] is an int array, not char. Can contain EOF. */
2787 /* Is there 2nd char? */
2788 ch = i->peek_buf[1];
2790 /* We did not read it yet, get it now */
2791 do ch = hfgetc(i->file); while (ch == '\0');
2792 i->peek_buf[1] = ch;
2795 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2799 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2804 ch = i_getch(input);
2807 ch2 = i_peek(input);
2810 /* backslash+newline, skip it */
2815 /* Note: this function _eats_ \<newline> pairs, safe to use plain
2816 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2818 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2826 ch2 = i_peek2(input);
2829 /* backslash+newline, skip it */
2835 static void setup_file_in_str(struct in_str *i, HFILE *fp)
2837 memset(i, 0, sizeof(*i));
2842 static void setup_string_in_str(struct in_str *i, const char *s)
2844 memset(i, 0, sizeof(*i));
2845 /*i->file = NULL */;
2853 #define B_CHUNK (32 * sizeof(char*))
2855 static void o_reset_to_empty_unquoted(o_string *o)
2858 o->has_quoted_part = 0;
2863 static void o_free_and_set_NULL(o_string *o)
2866 memset(o, 0, sizeof(*o));
2869 static ALWAYS_INLINE void o_free(o_string *o)
2874 static void o_grow_by(o_string *o, int len)
2876 if (o->length + len > o->maxlen) {
2877 o->maxlen += (2 * len) | (B_CHUNK-1);
2878 o->data = xrealloc(o->data, 1 + o->maxlen);
2882 static void o_addchr(o_string *o, int ch)
2884 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2885 if (o->length < o->maxlen) {
2886 /* likely. avoid o_grow_by() call */
2888 o->data[o->length] = ch;
2890 o->data[o->length] = '\0';
2898 /* Valid only if we know o_string is not empty */
2899 static void o_delchr(o_string *o)
2902 o->data[o->length] = '\0';
2906 static void o_addblock(o_string *o, const char *str, int len)
2909 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2913 static void o_addstr(o_string *o, const char *str)
2915 o_addblock(o, str, strlen(str));
2918 static void o_addstr_with_NUL(o_string *o, const char *str)
2920 o_addblock(o, str, strlen(str) + 1);
2924 static void nommu_addchr(o_string *o, int ch)
2930 # define nommu_addchr(o, str) ((void)0)
2933 #if ENABLE_HUSH_MODE_X
2934 static void x_mode_addchr(int ch)
2936 o_addchr(&G.x_mode_buf, ch);
2938 static void x_mode_addstr(const char *str)
2940 o_addstr(&G.x_mode_buf, str);
2942 static void x_mode_addblock(const char *str, int len)
2944 o_addblock(&G.x_mode_buf, str, len);
2946 static void x_mode_prefix(void)
2948 int n = G.x_mode_depth;
2949 do x_mode_addchr('+'); while (--n >= 0);
2951 static void x_mode_flush(void)
2953 int len = G.x_mode_buf.length;
2956 if (G.x_mode_fd > 0) {
2957 G.x_mode_buf.data[len] = '\n';
2958 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2960 G.x_mode_buf.length = 0;
2965 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2966 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2967 * Apparently, on unquoted $v bash still does globbing
2968 * ("v='*.txt'; echo $v" prints all .txt files),
2969 * but NOT brace expansion! Thus, there should be TWO independent
2970 * quoting mechanisms on $v expansion side: one protects
2971 * $v from brace expansion, and other additionally protects "$v" against globbing.
2972 * We have only second one.
2975 #if ENABLE_HUSH_BRACE_EXPANSION
2976 # define MAYBE_BRACES "{}"
2978 # define MAYBE_BRACES ""
2981 /* My analysis of quoting semantics tells me that state information
2982 * is associated with a destination, not a source.
2984 static void o_addqchr(o_string *o, int ch)
2987 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2992 o->data[o->length] = '\\';
2995 o->data[o->length] = ch;
2997 o->data[o->length] = '\0';
3000 static void o_addQchr(o_string *o, int ch)
3003 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3004 && strchr("*?[\\" MAYBE_BRACES, ch)
3007 o->data[o->length] = '\\';
3011 o->data[o->length] = ch;
3013 o->data[o->length] = '\0';
3016 static void o_addqblock(o_string *o, const char *str, int len)
3021 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
3022 if (ordinary_cnt > len) /* paranoia */
3024 o_addblock(o, str, ordinary_cnt);
3025 if (ordinary_cnt == len)
3026 return; /* NUL is already added by o_addblock */
3027 str += ordinary_cnt;
3028 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
3032 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
3034 o->data[o->length] = '\\';
3038 o->data[o->length] = ch;
3041 o->data[o->length] = '\0';
3044 static void o_addQblock(o_string *o, const char *str, int len)
3046 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
3047 o_addblock(o, str, len);
3050 o_addqblock(o, str, len);
3053 static void o_addQstr(o_string *o, const char *str)
3055 o_addQblock(o, str, strlen(str));
3058 /* A special kind of o_string for $VAR and `cmd` expansion.
3059 * It contains char* list[] at the beginning, which is grown in 16 element
3060 * increments. Actual string data starts at the next multiple of 16 * (char*).
3061 * list[i] contains an INDEX (int!) into this string data.
3062 * It means that if list[] needs to grow, data needs to be moved higher up
3063 * but list[i]'s need not be modified.
3064 * NB: remembering how many list[i]'s you have there is crucial.
3065 * o_finalize_list() operation post-processes this structure - calculates
3066 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3068 #if DEBUG_EXPAND || DEBUG_GLOB
3069 static void debug_print_list(const char *prefix, o_string *o, int n)
3071 char **list = (char**)o->data;
3072 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3076 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
3077 prefix, list, n, string_start, o->length, o->maxlen,
3078 !!(o->o_expflags & EXP_FLAG_GLOB),
3080 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3083 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3084 o->data + (int)(uintptr_t)list[i] + string_start,
3085 o->data + (int)(uintptr_t)list[i] + string_start);
3089 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
3091 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
3095 # define debug_print_list(prefix, o, n) ((void)0)
3098 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3099 * in list[n] so that it points past last stored byte so far.
3100 * It returns n+1. */
3101 static int o_save_ptr_helper(o_string *o, int n)
3103 char **list = (char**)o->data;
3107 if (!o->has_empty_slot) {
3108 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3109 string_len = o->length - string_start;
3110 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
3111 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
3112 /* list[n] points to string_start, make space for 16 more pointers */
3113 o->maxlen += 0x10 * sizeof(list[0]);
3114 o->data = xrealloc(o->data, o->maxlen + 1);
3115 list = (char**)o->data;
3116 memmove(list + n + 0x10, list + n, string_len);
3118 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3119 * check. (grep for -prev-ifs-check-).
3120 * Ensure that argv[-1][last] is not garbage
3121 * but zero bytes, to save index check there.
3123 list[n + 0x10 - 1] = 0;
3124 o->length += 0x10 * sizeof(list[0]);
3126 debug_printf_list("list[%d]=%d string_start=%d\n",
3127 n, string_len, string_start);
3130 /* We have empty slot at list[n], reuse without growth */
3131 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3132 string_len = o->length - string_start;
3133 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3134 n, string_len, string_start);
3135 o->has_empty_slot = 0;
3137 o->has_quoted_part = 0;
3138 list[n] = (char*)(uintptr_t)string_len;
3142 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
3143 static int o_get_last_ptr(o_string *o, int n)
3145 char **list = (char**)o->data;
3146 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3148 return ((int)(uintptr_t)list[n-1]) + string_start;
3151 #if ENABLE_HUSH_BRACE_EXPANSION
3152 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
3153 * first, it processes even {a} (no commas), second,
3154 * I didn't manage to make it return strings when they don't match
3155 * existing files. Need to re-implement it.
3159 static int glob_needed(const char *s)
3168 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3174 /* Return pointer to next closing brace or to comma */
3175 static const char *next_brace_sub(const char *cp)
3179 while (*cp != '\0') {
3186 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3192 return *cp != '\0' ? cp : NULL;
3194 /* Recursive brace globber. Note: may garble pattern[]. */
3195 static int glob_brace(char *pattern, o_string *o, int n)
3197 char *new_pattern_buf;
3204 debug_printf_glob("glob_brace('%s')\n", pattern);
3210 if (*begin == '{') {
3211 /* Find the first sub-pattern and at the same time
3212 * find the rest after the closing brace */
3213 next = next_brace_sub(begin);
3215 /* An illegal expression */
3219 /* "{abc}" with no commas - illegal
3220 * brace expr, disregard and skip it */
3226 if (*begin == '\\' && begin[1] != '\0')
3230 debug_printf_glob("begin:%s\n", begin);
3231 debug_printf_glob("next:%s\n", next);
3233 /* Now find the end of the whole brace expression */
3235 while (*rest != '}') {
3236 rest = next_brace_sub(rest);
3238 /* An illegal expression */
3241 debug_printf_glob("rest:%s\n", rest);
3243 rest_len = strlen(++rest) + 1;
3245 /* We are sure the brace expression is well-formed */
3247 /* Allocate working buffer large enough for our work */
3248 new_pattern_buf = xmalloc(strlen(pattern));
3250 /* We have a brace expression. BEGIN points to the opening {,
3251 * NEXT points past the terminator of the first element, and REST
3252 * points past the final }. We will accumulate result names from
3253 * recursive runs for each brace alternative in the buffer using
3258 /* Construct the new glob expression */
3261 mempcpy(new_pattern_buf,
3262 /* We know the prefix for all sub-patterns */
3263 pattern, begin - pattern),
3267 /* Note: glob_brace() may garble new_pattern_buf[].
3268 * That's why we re-copy prefix every time (1st memcpy above).
3270 n = glob_brace(new_pattern_buf, o, n);
3272 /* We saw the last entry */
3276 next = next_brace_sub(next);
3278 free(new_pattern_buf);
3286 memset(&globdata, 0, sizeof(globdata));
3287 gr = glob(pattern, 0, NULL, &globdata);
3288 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3290 if (gr == GLOB_NOMATCH) {
3291 globfree(&globdata);
3292 /* NB: garbles parameter */
3293 unbackslash(pattern);
3294 o_addstr_with_NUL(o, pattern);
3295 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3296 return o_save_ptr_helper(o, n);
3298 if (gr == GLOB_NOSPACE)
3299 bb_die_memory_exhausted();
3300 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3301 * but we didn't specify it. Paranoia again. */
3302 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3304 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3305 char **argv = globdata.gl_pathv;
3307 o_addstr_with_NUL(o, *argv);
3308 n = o_save_ptr_helper(o, n);
3314 globfree(&globdata);
3318 /* Performs globbing on last list[],
3319 * saving each result as a new list[].
3321 static int perform_glob(o_string *o, int n)
3323 char *pattern, *copy;
3325 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3327 return o_save_ptr_helper(o, n);
3328 pattern = o->data + o_get_last_ptr(o, n);
3329 debug_printf_glob("glob pattern '%s'\n", pattern);
3330 if (!glob_needed(pattern)) {
3331 /* unbackslash last string in o in place, fix length */
3332 o->length = unbackslash(pattern) - o->data;
3333 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3334 return o_save_ptr_helper(o, n);
3337 copy = xstrdup(pattern);
3338 /* "forget" pattern in o */
3339 o->length = pattern - o->data;
3340 n = glob_brace(copy, o, n);
3343 debug_print_list("perform_glob returning", o, n);
3347 #else /* !HUSH_BRACE_EXPANSION */
3350 static int glob_needed(const char *s)
3359 if (*s == '*' || *s == '[' || *s == '?')
3365 /* Performs globbing on last list[],
3366 * saving each result as a new list[].
3368 static int perform_glob(o_string *o, int n)
3374 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3376 return o_save_ptr_helper(o, n);
3377 pattern = o->data + o_get_last_ptr(o, n);
3378 debug_printf_glob("glob pattern '%s'\n", pattern);
3379 if (!glob_needed(pattern)) {
3381 /* unbackslash last string in o in place, fix length */
3382 o->length = unbackslash(pattern) - o->data;
3383 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3384 return o_save_ptr_helper(o, n);
3387 memset(&globdata, 0, sizeof(globdata));
3388 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3389 * If we glob "*.\*" and don't find anything, we need
3390 * to fall back to using literal "*.*", but GLOB_NOCHECK
3391 * will return "*.\*"!
3393 gr = glob(pattern, 0, NULL, &globdata);
3394 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3396 if (gr == GLOB_NOMATCH) {
3397 globfree(&globdata);
3400 if (gr == GLOB_NOSPACE)
3401 bb_die_memory_exhausted();
3402 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3403 * but we didn't specify it. Paranoia again. */
3404 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3406 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3407 char **argv = globdata.gl_pathv;
3408 /* "forget" pattern in o */
3409 o->length = pattern - o->data;
3411 o_addstr_with_NUL(o, *argv);
3412 n = o_save_ptr_helper(o, n);
3418 globfree(&globdata);
3420 debug_print_list("perform_glob returning", o, n);
3424 #endif /* !HUSH_BRACE_EXPANSION */
3426 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3427 * Otherwise, just finish current list[] and start new */
3428 static int o_save_ptr(o_string *o, int n)
3430 if (o->o_expflags & EXP_FLAG_GLOB) {
3431 /* If o->has_empty_slot, list[n] was already globbed
3432 * (if it was requested back then when it was filled)
3433 * so don't do that again! */
3434 if (!o->has_empty_slot)
3435 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3437 return o_save_ptr_helper(o, n);
3440 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3441 static char **o_finalize_list(o_string *o, int n)
3447 debug_print_list("finalized", o, n);
3448 debug_printf_expand("finalized n:%d\n", n);
3449 list = (char**)o->data;
3450 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3454 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3459 static void free_pipe_list(struct pipe *pi);
3461 /* Returns pi->next - next pipe in the list */
3462 static struct pipe *free_pipe(struct pipe *pi)
3467 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3468 for (i = 0; i < pi->num_cmds; i++) {
3469 struct command *command;
3470 struct redir_struct *r, *rnext;
3472 command = &pi->cmds[i];
3473 debug_printf_clean(" command %d:\n", i);
3474 if (command->argv) {
3478 for (a = 0, p = command->argv; *p; a++, p++) {
3479 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3482 free_strings(command->argv);
3483 //command->argv = NULL;
3485 /* not "else if": on syntax error, we may have both! */
3486 if (command->group) {
3487 debug_printf_clean(" begin group (cmd_type:%d)\n",
3489 free_pipe_list(command->group);
3490 debug_printf_clean(" end group\n");
3491 //command->group = NULL;
3493 /* else is crucial here.
3494 * If group != NULL, child_func is meaningless */
3495 #if ENABLE_HUSH_FUNCTIONS
3496 else if (command->child_func) {
3497 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3498 command->child_func->parent_cmd = NULL;
3502 free(command->group_as_string);
3503 //command->group_as_string = NULL;
3505 for (r = command->redirects; r; r = rnext) {
3506 debug_printf_clean(" redirect %d%s",
3507 r->rd_fd, redir_table[r->rd_type].descrip);
3508 /* guard against the case >$FOO, where foo is unset or blank */
3509 if (r->rd_filename) {
3510 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3511 free(r->rd_filename);
3512 //r->rd_filename = NULL;
3514 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3518 //command->redirects = NULL;
3520 free(pi->cmds); /* children are an array, they get freed all at once */
3524 //pi->cmdtext = NULL;
3532 static void free_pipe_list(struct pipe *pi)
3536 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3538 debug_printf_clean("pipe followup code %d\n", pi->followup);
3544 /*** Parsing routines ***/
3546 #ifndef debug_print_tree
3547 static void debug_print_tree(struct pipe *pi, int lvl)
3549 static const char *const PIPE[] = {
3555 static const char *RES[] = {
3556 [RES_NONE ] = "NONE" ,
3559 [RES_THEN ] = "THEN" ,
3560 [RES_ELIF ] = "ELIF" ,
3561 [RES_ELSE ] = "ELSE" ,
3564 # if ENABLE_HUSH_LOOPS
3565 [RES_FOR ] = "FOR" ,
3566 [RES_WHILE] = "WHILE",
3567 [RES_UNTIL] = "UNTIL",
3569 [RES_DONE ] = "DONE" ,
3571 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3574 # if ENABLE_HUSH_CASE
3575 [RES_CASE ] = "CASE" ,
3576 [RES_CASE_IN ] = "CASE_IN" ,
3577 [RES_MATCH] = "MATCH",
3578 [RES_CASE_BODY] = "CASE_BODY",
3579 [RES_ESAC ] = "ESAC" ,
3581 [RES_XXXX ] = "XXXX" ,
3582 [RES_SNTX ] = "SNTX" ,
3584 static const char *const CMDTYPE[] = {
3588 # if ENABLE_HUSH_FUNCTIONS
3597 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3600 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3602 pi->followup, PIPE[pi->followup]
3605 while (prn < pi->num_cmds) {
3606 struct command *command = &pi->cmds[prn];
3607 char **argv = command->argv;
3609 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3611 command->assignment_cnt);
3612 #if ENABLE_HUSH_LINENO_VAR
3613 fdprintf(2, " LINENO:%u", command->lineno);
3615 if (command->group) {
3616 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3617 CMDTYPE[command->cmd_type],
3620 , " group_as_string:", command->group_as_string
3625 debug_print_tree(command->group, lvl+1);
3629 if (argv) while (*argv) {
3630 fdprintf(2, " '%s'", *argv);
3633 if (command->redirects)
3634 fdprintf(2, " {redir}");
3642 #endif /* debug_print_tree */
3644 static struct pipe *new_pipe(void)
3647 pi = xzalloc(sizeof(struct pipe));
3648 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3652 /* Command (member of a pipe) is complete, or we start a new pipe
3653 * if ctx->command is NULL.
3654 * No errors possible here.
3656 static int done_command(struct parse_context *ctx)
3658 /* The command is really already in the pipe structure, so
3659 * advance the pipe counter and make a new, null command. */
3660 struct pipe *pi = ctx->pipe;
3661 struct command *command = ctx->command;
3663 #if 0 /* Instead we emit error message at run time */
3664 if (ctx->pending_redirect) {
3665 /* For example, "cmd >" (no filename to redirect to) */
3666 syntax_error("invalid redirect");
3667 ctx->pending_redirect = NULL;
3672 if (IS_NULL_CMD(command)) {
3673 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3677 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3678 //debug_print_tree(ctx->list_head, 20);
3680 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3683 /* Only real trickiness here is that the uncommitted
3684 * command structure is not counted in pi->num_cmds. */
3685 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3686 ctx->command = command = &pi->cmds[pi->num_cmds];
3688 memset(command, 0, sizeof(*command));
3689 #if ENABLE_HUSH_LINENO_VAR
3690 command->lineno = G.lineno;
3691 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
3693 return pi->num_cmds; /* used only for 0/nonzero check */
3696 static void done_pipe(struct parse_context *ctx, pipe_style type)
3700 debug_printf_parse("done_pipe entered, followup %d\n", type);
3701 /* Close previous command */
3702 not_null = done_command(ctx);
3704 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3705 ctx->ctx_inverted = 0;
3706 ctx->pipe->res_word = ctx->ctx_res_w;
3708 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3709 /* Necessary since && and || have precedence over &:
3710 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3711 * in a backgrounded subshell.
3714 struct command *command;
3716 /* Is this actually this construct, all pipes end with && or ||? */
3717 pi = ctx->list_head;
3718 while (pi != ctx->pipe) {
3719 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3724 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3725 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3726 pi = xzalloc(sizeof(*pi));
3727 pi->followup = PIPE_BG;
3729 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3730 command = &pi->cmds[0];
3731 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3732 command->cmd_type = CMD_NORMAL;
3733 command->group = ctx->list_head;
3735 command->group_as_string = xstrndup(
3736 ctx->as_string.data,
3737 ctx->as_string.length - 1 /* do not copy last char, "&" */
3740 /* Replace all pipes in ctx with one newly created */
3741 ctx->list_head = ctx->pipe = pi;
3744 ctx->pipe->followup = type;
3747 /* Without this check, even just <enter> on command line generates
3748 * tree of three NOPs (!). Which is harmless but annoying.
3749 * IOW: it is safe to do it unconditionally. */
3752 || ctx->ctx_res_w == RES_FI
3754 #if ENABLE_HUSH_LOOPS
3755 || ctx->ctx_res_w == RES_DONE
3756 || ctx->ctx_res_w == RES_FOR
3757 || ctx->ctx_res_w == RES_IN
3759 #if ENABLE_HUSH_CASE
3760 || ctx->ctx_res_w == RES_ESAC
3764 debug_printf_parse("done_pipe: adding new pipe: "
3765 "not_null:%d ctx->ctx_res_w:%d\n",
3766 not_null, ctx->ctx_res_w);
3768 ctx->pipe->next = new_p;
3770 /* RES_THEN, RES_DO etc are "sticky" -
3771 * they remain set for pipes inside if/while.
3772 * This is used to control execution.
3773 * RES_FOR and RES_IN are NOT sticky (needed to support
3774 * cases where variable or value happens to match a keyword):
3776 #if ENABLE_HUSH_LOOPS
3777 if (ctx->ctx_res_w == RES_FOR
3778 || ctx->ctx_res_w == RES_IN)
3779 ctx->ctx_res_w = RES_NONE;
3781 #if ENABLE_HUSH_CASE
3782 if (ctx->ctx_res_w == RES_MATCH)
3783 ctx->ctx_res_w = RES_CASE_BODY;
3784 if (ctx->ctx_res_w == RES_CASE)
3785 ctx->ctx_res_w = RES_CASE_IN;
3787 ctx->command = NULL; /* trick done_command below */
3788 /* Create the memory for command, roughly:
3789 * ctx->pipe->cmds = new struct command;
3790 * ctx->command = &ctx->pipe->cmds[0];
3793 //debug_print_tree(ctx->list_head, 10);
3795 debug_printf_parse("done_pipe return\n");
3798 static void initialize_context(struct parse_context *ctx)
3800 memset(ctx, 0, sizeof(*ctx));
3801 if (MAYBE_ASSIGNMENT != 0)
3802 ctx->is_assignment = MAYBE_ASSIGNMENT;
3803 ctx->pipe = ctx->list_head = new_pipe();
3804 /* Create the memory for command, roughly:
3805 * ctx->pipe->cmds = new struct command;
3806 * ctx->command = &ctx->pipe->cmds[0];
3811 /* If a reserved word is found and processed, parse context is modified
3812 * and 1 is returned.
3815 struct reserved_combo {
3818 unsigned char assignment_flag;
3822 FLAG_END = (1 << RES_NONE ),
3824 FLAG_IF = (1 << RES_IF ),
3825 FLAG_THEN = (1 << RES_THEN ),
3826 FLAG_ELIF = (1 << RES_ELIF ),
3827 FLAG_ELSE = (1 << RES_ELSE ),
3828 FLAG_FI = (1 << RES_FI ),
3830 # if ENABLE_HUSH_LOOPS
3831 FLAG_FOR = (1 << RES_FOR ),
3832 FLAG_WHILE = (1 << RES_WHILE),
3833 FLAG_UNTIL = (1 << RES_UNTIL),
3834 FLAG_DO = (1 << RES_DO ),
3835 FLAG_DONE = (1 << RES_DONE ),
3836 FLAG_IN = (1 << RES_IN ),
3838 # if ENABLE_HUSH_CASE
3839 FLAG_MATCH = (1 << RES_MATCH),
3840 FLAG_ESAC = (1 << RES_ESAC ),
3842 FLAG_START = (1 << RES_XXXX ),
3845 static const struct reserved_combo* match_reserved_word(o_string *word)
3847 /* Mostly a list of accepted follow-up reserved words.
3848 * FLAG_END means we are done with the sequence, and are ready
3849 * to turn the compound list into a command.
3850 * FLAG_START means the word must start a new compound list.
3852 static const struct reserved_combo reserved_list[] = {
3854 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3855 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3856 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3857 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3858 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3859 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3861 # if ENABLE_HUSH_LOOPS
3862 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3863 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3864 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3865 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3866 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3867 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3869 # if ENABLE_HUSH_CASE
3870 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3871 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3874 const struct reserved_combo *r;
3876 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3877 if (strcmp(word->data, r->literal) == 0)
3882 /* Return NULL: not a keyword, else: keyword
3884 static const struct reserved_combo* reserved_word(struct parse_context *ctx)
3886 # if ENABLE_HUSH_CASE
3887 static const struct reserved_combo reserved_match = {
3888 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3891 const struct reserved_combo *r;
3893 if (ctx->word.has_quoted_part)
3895 r = match_reserved_word(&ctx->word);
3897 return r; /* NULL */
3899 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3900 # if ENABLE_HUSH_CASE
3901 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3902 /* "case word IN ..." - IN part starts first MATCH part */
3903 r = &reserved_match;
3906 if (r->flag == 0) { /* '!' */
3907 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3908 syntax_error("! ! command");
3909 ctx->ctx_res_w = RES_SNTX;
3911 ctx->ctx_inverted = 1;
3914 if (r->flag & FLAG_START) {
3915 struct parse_context *old;
3917 old = xmemdup(ctx, sizeof(*ctx));
3918 debug_printf_parse("push stack %p\n", old);
3919 initialize_context(ctx);
3921 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3922 syntax_error_at(ctx->word.data);
3923 ctx->ctx_res_w = RES_SNTX;
3926 /* "{...} fi" is ok. "{...} if" is not
3928 * if { echo foo; } then { echo bar; } fi */
3929 if (ctx->command->group)
3930 done_pipe(ctx, PIPE_SEQ);
3933 ctx->ctx_res_w = r->res;
3934 ctx->old_flag = r->flag;
3935 ctx->is_assignment = r->assignment_flag;
3936 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
3938 if (ctx->old_flag & FLAG_END) {
3939 struct parse_context *old;
3941 done_pipe(ctx, PIPE_SEQ);
3942 debug_printf_parse("pop stack %p\n", ctx->stack);
3944 old->command->group = ctx->list_head;
3945 old->command->cmd_type = CMD_NORMAL;
3947 /* At this point, the compound command's string is in
3948 * ctx->as_string... except for the leading keyword!
3949 * Consider this example: "echo a | if true; then echo a; fi"
3950 * ctx->as_string will contain "true; then echo a; fi",
3951 * with "if " remaining in old->as_string!
3955 int len = old->as_string.length;
3956 /* Concatenate halves */
3957 o_addstr(&old->as_string, ctx->as_string.data);
3958 o_free(&ctx->as_string);
3959 /* Find where leading keyword starts in first half */
3960 str = old->as_string.data + len;
3961 if (str > old->as_string.data)
3962 str--; /* skip whitespace after keyword */
3963 while (str > old->as_string.data && isalpha(str[-1]))
3965 /* Ugh, we're done with this horrid hack */
3966 old->command->group_as_string = xstrdup(str);
3967 debug_printf_parse("pop, remembering as:'%s'\n",
3968 old->command->group_as_string);
3971 *ctx = *old; /* physical copy */
3976 #endif /* HAS_KEYWORDS */
3978 /* Word is complete, look at it and update parsing context.
3979 * Normal return is 0. Syntax errors return 1.
3980 * Note: on return, word is reset, but not o_free'd!
3982 static int done_word(struct parse_context *ctx)
3984 struct command *command = ctx->command;
3986 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3987 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
3988 debug_printf_parse("done_word return 0: true null, ignored\n");
3992 if (ctx->pending_redirect) {
3993 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3994 * only if run as "bash", not "sh" */
3995 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
3997 * If the redirection operator is "<<" or "<<-", the word
3998 * that follows the redirection operator shall be
3999 * subjected to quote removal; it is unspecified whether
4000 * any of the other expansions occur. For the other
4001 * redirection operators, the word that follows the
4002 * redirection operator shall be subjected to tilde
4003 * expansion, parameter expansion, command substitution,
4004 * arithmetic expansion, and quote removal.
4005 * Pathname expansion shall not be performed
4006 * on the word by a non-interactive shell; an interactive
4007 * shell may perform it, but shall do so only when
4008 * the expansion would result in one word."
4010 //bash does not do parameter/command substitution or arithmetic expansion
4011 //for _heredoc_ redirection word: these constructs look for exact eof marker
4015 // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4017 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
4018 /* Cater for >\file case:
4019 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4020 * Same with heredocs:
4021 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4023 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4024 unbackslash(ctx->pending_redirect->rd_filename);
4025 /* Is it <<"HEREDOC"? */
4026 if (ctx->word.has_quoted_part) {
4027 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4030 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
4031 ctx->pending_redirect = NULL;
4034 # if ENABLE_HUSH_CASE
4035 if (ctx->ctx_dsemicolon
4036 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4038 /* already done when ctx_dsemicolon was set to 1: */
4039 /* ctx->ctx_res_w = RES_MATCH; */
4040 ctx->ctx_dsemicolon = 0;
4043 if (!command->argv /* if it's the first word... */
4044 # if ENABLE_HUSH_LOOPS
4045 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4046 && ctx->ctx_res_w != RES_IN
4048 # if ENABLE_HUSH_CASE
4049 && ctx->ctx_res_w != RES_CASE
4052 const struct reserved_combo *reserved;
4053 reserved = reserved_word(ctx);
4054 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
4056 # if ENABLE_HUSH_LINENO_VAR
4060 * If we don't close the pipe _now_, immediately after "do", lineno logic
4061 * sees "cmd" as starting at "do" - i.e., at the previous line.
4064 IF_HUSH_IF(|| reserved->res == RES_THEN)
4065 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4066 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4067 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4069 done_pipe(ctx, PIPE_SEQ);
4072 o_reset_to_empty_unquoted(&ctx->word);
4073 debug_printf_parse("done_word return %d\n",
4074 (ctx->ctx_res_w == RES_SNTX));
4075 return (ctx->ctx_res_w == RES_SNTX);
4077 # if defined(CMD_SINGLEWORD_NOGLOB)
4080 || strcmp(ctx->word.data, "[[") == 0
4082 /* In bash, local/export/readonly are special, args
4083 * are assignments and therefore expansion of them
4084 * should be "one-word" expansion:
4085 * $ export i=`echo 'a b'` # one arg: "i=a b"
4087 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4088 * ls: cannot access i=a: No such file or directory
4089 * ls: cannot access b: No such file or directory
4090 * Note: bash 3.2.33(1) does this only if export word
4091 * itself is not quoted:
4092 * $ export i=`echo 'aaa bbb'`; echo "$i"
4094 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4097 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4098 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4099 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
4101 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4106 #endif /* HAS_KEYWORDS */
4108 if (command->group) {
4109 /* "{ echo foo; } echo bar" - bad */
4110 syntax_error_at(ctx->word.data);
4111 debug_printf_parse("done_word return 1: syntax error, "
4112 "groups and arglists don't mix\n");
4116 /* If this word wasn't an assignment, next ones definitely
4117 * can't be assignments. Even if they look like ones. */
4118 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4119 && ctx->is_assignment != WORD_IS_KEYWORD
4121 ctx->is_assignment = NOT_ASSIGNMENT;
4123 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
4124 command->assignment_cnt++;
4125 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4127 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4128 ctx->is_assignment = MAYBE_ASSIGNMENT;
4130 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4131 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
4132 debug_print_strings("word appended to argv", command->argv);
4135 #if ENABLE_HUSH_LOOPS
4136 if (ctx->ctx_res_w == RES_FOR) {
4137 if (ctx->word.has_quoted_part
4138 || !is_well_formed_var_name(command->argv[0], '\0')
4140 /* bash says just "not a valid identifier" */
4141 syntax_error("not a valid identifier in for");
4144 /* Force FOR to have just one word (variable name) */
4145 /* NB: basically, this makes hush see "for v in ..."
4146 * syntax as if it is "for v; in ...". FOR and IN become
4147 * two pipe structs in parse tree. */
4148 done_pipe(ctx, PIPE_SEQ);
4151 #if ENABLE_HUSH_CASE
4152 /* Force CASE to have just one word */
4153 if (ctx->ctx_res_w == RES_CASE) {
4154 done_pipe(ctx, PIPE_SEQ);
4158 o_reset_to_empty_unquoted(&ctx->word);
4160 debug_printf_parse("done_word return 0\n");
4165 /* Peek ahead in the input to find out if we have a "&n" construct,
4166 * as in "2>&1", that represents duplicating a file descriptor.
4168 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4169 * REDIRFD_SYNTAX_ERR if syntax error,
4170 * REDIRFD_TO_FILE if no & was seen,
4171 * or the number found.
4174 #define parse_redir_right_fd(as_string, input) \
4175 parse_redir_right_fd(input)
4177 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4183 return REDIRFD_TO_FILE;
4185 ch = i_getch(input); /* get the & */
4186 nommu_addchr(as_string, ch);
4189 ch = i_getch(input);
4190 nommu_addchr(as_string, ch);
4191 return REDIRFD_CLOSE;
4195 while (ch != EOF && isdigit(ch)) {
4196 d = d*10 + (ch-'0');
4198 ch = i_getch(input);
4199 nommu_addchr(as_string, ch);
4204 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4206 bb_error_msg("ambiguous redirect");
4207 return REDIRFD_SYNTAX_ERR;
4210 /* Return code is 0 normal, 1 if a syntax error is detected
4212 static int parse_redirect(struct parse_context *ctx,
4215 struct in_str *input)
4217 struct command *command = ctx->command;
4218 struct redir_struct *redir;
4219 struct redir_struct **redirp;
4222 dup_num = REDIRFD_TO_FILE;
4223 if (style != REDIRECT_HEREDOC) {
4224 /* Check for a '>&1' type redirect */
4225 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4226 if (dup_num == REDIRFD_SYNTAX_ERR)
4229 int ch = i_peek_and_eat_bkslash_nl(input);
4230 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4231 if (dup_num) { /* <<-... */
4232 ch = i_getch(input);
4233 nommu_addchr(&ctx->as_string, ch);
4238 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4239 int ch = i_peek_and_eat_bkslash_nl(input);
4241 /* >|FILE redirect ("clobbering" >).
4242 * Since we do not support "set -o noclobber" yet,
4243 * >| and > are the same for now. Just eat |.
4245 ch = i_getch(input);
4246 nommu_addchr(&ctx->as_string, ch);
4250 /* Create a new redir_struct and append it to the linked list */
4251 redirp = &command->redirects;
4252 while ((redir = *redirp) != NULL) {
4253 redirp = &(redir->next);
4255 *redirp = redir = xzalloc(sizeof(*redir));
4256 /* redir->next = NULL; */
4257 /* redir->rd_filename = NULL; */
4258 redir->rd_type = style;
4259 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4261 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4262 redir_table[style].descrip);
4264 redir->rd_dup = dup_num;
4265 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4266 /* Erik had a check here that the file descriptor in question
4267 * is legit; I postpone that to "run time"
4268 * A "-" representation of "close me" shows up as a -3 here */
4269 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4270 redir->rd_fd, redir->rd_dup);
4272 #if 0 /* Instead we emit error message at run time */
4273 if (ctx->pending_redirect) {
4274 /* For example, "cmd > <file" */
4275 syntax_error("invalid redirect");
4278 /* Set ctx->pending_redirect, so we know what to do at the
4279 * end of the next parsed word. */
4280 ctx->pending_redirect = redir;
4285 /* If a redirect is immediately preceded by a number, that number is
4286 * supposed to tell which file descriptor to redirect. This routine
4287 * looks for such preceding numbers. In an ideal world this routine
4288 * needs to handle all the following classes of redirects...
4289 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4290 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4291 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4292 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4294 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4296 * ... If n is quoted, the number shall not be recognized as part of
4297 * the redirection expression. For example:
4299 * writes the character 2 into file a"
4300 * We are getting it right by setting ->has_quoted_part on any \<char>
4302 * A -1 return means no valid number was found,
4303 * the caller should use the appropriate default for this redirection.
4305 static int redirect_opt_num(o_string *o)
4309 if (o->data == NULL)
4311 num = bb_strtou(o->data, NULL, 10);
4312 if (errno || num < 0)
4314 o_reset_to_empty_unquoted(o);
4319 #define fetch_till_str(as_string, input, word, skip_tabs) \
4320 fetch_till_str(input, word, skip_tabs)
4322 static char *fetch_till_str(o_string *as_string,
4323 struct in_str *input,
4327 o_string heredoc = NULL_O_STRING;
4329 int prev = 0; /* not \ */
4332 /* Starting with "" is necessary for this case:
4338 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4343 ch = i_getch(input);
4345 nommu_addchr(as_string, ch);
4346 if (ch == '\n' || ch == EOF) {
4348 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4349 /* End-of-line, and not a line continuation */
4350 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4351 heredoc.data[past_EOL] = '\0';
4352 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
4353 return heredoc.data;
4356 /* This is a new line.
4357 * Remember position and backslash-escaping status.
4359 o_addchr(&heredoc, ch);
4362 past_EOL = heredoc.length;
4363 /* Get 1st char of next line, possibly skipping leading tabs */
4365 ch = i_getch(input);
4367 nommu_addchr(as_string, ch);
4368 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4369 /* If this immediately ended the line,
4370 * go back to end-of-line checks.
4373 goto check_heredoc_end;
4376 /* Backslash-line continuation in an unquoted
4377 * heredoc. This does not need special handling
4378 * for heredoc body (unquoted heredocs are
4379 * expanded on "execution" and that would take
4380 * care of this case too), but not the case
4381 * of line continuation *in terminator*:
4387 heredoc.data[--heredoc.length] = '\0';
4388 prev = 0; /* not '\' */
4394 return NULL; /* error */
4396 o_addchr(&heredoc, ch);
4397 nommu_addchr(as_string, ch);
4398 if (prev == '\\' && ch == '\\')
4399 /* Correctly handle foo\\<eol> (not a line cont.) */
4400 prev = 0; /* not '\' */
4406 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4407 * and load them all. There should be exactly heredoc_cnt of them.
4410 #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4411 fetch_heredocs(pi, heredoc_cnt, input)
4413 static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
4415 while (pi && heredoc_cnt) {
4417 struct command *cmd = pi->cmds;
4419 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4421 cmd->argv ? cmd->argv[0] : "NONE"
4423 for (i = 0; i < pi->num_cmds; i++) {
4424 struct redir_struct *redir = cmd->redirects;
4426 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
4427 i, cmd->argv ? cmd->argv[0] : "NONE");
4429 if (redir->rd_type == REDIRECT_HEREDOC) {
4432 redir->rd_type = REDIRECT_HEREDOC2;
4433 /* redir->rd_dup is (ab)used to indicate <<- */
4434 p = fetch_till_str(as_string, input,
4435 redir->rd_filename, redir->rd_dup);
4437 syntax_error("unexpected EOF in here document");
4440 free(redir->rd_filename);
4441 redir->rd_filename = p;
4444 redir = redir->next;
4447 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4448 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4449 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4450 if (heredoc_cnt < 0)
4451 return heredoc_cnt; /* error */
4461 static int run_list(struct pipe *pi);
4463 #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4464 parse_stream(heredoc_cnt_ptr, input, end_trigger)
4466 static struct pipe *parse_stream(char **pstring,
4467 int *heredoc_cnt_ptr,
4468 struct in_str *input,
4471 /* Returns number of heredocs not yet consumed,
4474 static int parse_group(struct parse_context *ctx,
4475 struct in_str *input, int ch)
4477 /* ctx->word contains characters seen prior to ( or {.
4478 * Typically it's empty, but for function defs,
4479 * it contains function name (without '()'). */
4481 # define as_string NULL
4483 char *as_string = NULL;
4485 struct pipe *pipe_list;
4486 int heredoc_cnt = 0;
4488 struct command *command = ctx->command;
4490 debug_printf_parse("parse_group entered\n");
4491 #if ENABLE_HUSH_FUNCTIONS
4492 if (ch == '(' && !ctx->word.has_quoted_part) {
4493 if (ctx->word.length)
4497 goto skip; /* (... */
4498 if (command->argv[1]) { /* word word ... (... */
4499 syntax_error_unexpected_ch('(');
4502 /* it is "word(..." or "word (..." */
4504 ch = i_getch(input);
4505 while (ch == ' ' || ch == '\t');
4507 syntax_error_unexpected_ch(ch);
4510 nommu_addchr(&ctx->as_string, ch);
4512 ch = i_getch(input);
4513 while (ch == ' ' || ch == '\t' || ch == '\n');
4514 if (ch != '{' && ch != '(') {
4515 syntax_error_unexpected_ch(ch);
4518 nommu_addchr(&ctx->as_string, ch);
4519 command->cmd_type = CMD_FUNCDEF;
4524 #if 0 /* Prevented by caller */
4525 if (command->argv /* word [word]{... */
4526 || ctx->word.length /* word{... */
4527 || ctx->word.has_quoted_part /* ""{... */
4530 debug_printf_parse("parse_group return -1: "
4531 "syntax error, groups and arglists don't mix\n");
4536 IF_HUSH_FUNCTIONS(skip:)
4541 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4542 command->cmd_type = CMD_SUBSHELL;
4544 /* bash does not allow "{echo...", requires whitespace */
4546 if (ch != ' ' && ch != '\t' && ch != '\n'
4547 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4549 syntax_error_unexpected_ch(ch);
4553 ch = i_getch(input);
4554 nommu_addchr(&ctx->as_string, ch);
4558 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4559 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4560 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
4563 o_addstr(&ctx->as_string, as_string);
4566 /* empty ()/{} or parse error? */
4567 if (!pipe_list || pipe_list == ERR_PTR) {
4568 /* parse_stream already emitted error msg */
4571 debug_printf_parse("parse_group return -1: "
4572 "parse_stream returned %p\n", pipe_list);
4576 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4577 command->group_as_string = as_string;
4578 debug_printf_parse("end of group, remembering as:'%s'\n",
4579 command->group_as_string);
4582 #if ENABLE_HUSH_FUNCTIONS
4583 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4584 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4585 struct command *cmd2;
4587 cmd2 = xzalloc(sizeof(*cmd2));
4588 cmd2->cmd_type = CMD_SUBSHELL;
4589 cmd2->group = pipe_list;
4592 cmd2->group_as_string = command->group_as_string;
4593 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4596 pipe_list = new_pipe();
4597 pipe_list->cmds = cmd2;
4598 pipe_list->num_cmds = 1;
4602 command->group = pipe_list;
4604 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4606 /* command remains "open", available for possible redirects */
4610 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4611 /* Subroutines for copying $(...) and `...` things */
4613 static int add_till_single_quote(o_string *dest, struct in_str *input)
4616 int ch = i_getch(input);
4618 syntax_error_unterm_ch('\'');
4626 static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4629 int ch = i_getch(input);
4631 syntax_error_unterm_ch('\'');
4636 o_addqchr(dest, ch);
4639 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4640 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4641 static int add_till_double_quote(o_string *dest, struct in_str *input)
4644 int ch = i_getch(input);
4646 syntax_error_unterm_ch('"');
4651 if (ch == '\\') { /* \x. Copy both chars. */
4653 ch = i_getch(input);
4657 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4662 //if (ch == '$') ...
4665 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4667 * "Within the backquoted style of command substitution, backslash
4668 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4669 * The search for the matching backquote shall be satisfied by the first
4670 * backquote found without a preceding backslash; during this search,
4671 * if a non-escaped backquote is encountered within a shell comment,
4672 * a here-document, an embedded command substitution of the $(command)
4673 * form, or a quoted string, undefined results occur. A single-quoted
4674 * or double-quoted string that begins, but does not end, within the
4675 * "`...`" sequence produces undefined results."
4677 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4679 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4682 int ch = i_getch(input);
4686 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4687 ch = i_getch(input);
4691 && (!in_dquote || ch != '"')
4693 o_addchr(dest, '\\');
4697 syntax_error_unterm_ch('`');
4703 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4704 * quoting and nested ()s.
4705 * "With the $(command) style of command substitution, all characters
4706 * following the open parenthesis to the matching closing parenthesis
4707 * constitute the command. Any valid shell script can be used for command,
4708 * except a script consisting solely of redirections which produces
4709 * unspecified results."
4711 * echo $(echo '(TEST)' BEST) (TEST) BEST
4712 * echo $(echo 'TEST)' BEST) TEST) BEST
4713 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4715 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4716 * can contain arbitrary constructs, just like $(cmd).
4717 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4718 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4720 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4721 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4724 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4725 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4726 char end_char2 = end_ch >> 8;
4728 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4730 #if ENABLE_HUSH_INTERACTIVE
4731 G.promptmode = 1; /* PS2 */
4733 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4736 ch = i_getch(input);
4738 syntax_error_unterm_ch(end_ch);
4742 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4748 /* we look for closing )) of $((EXPR)) */
4749 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4750 i_getch(input); /* eat second ')' */
4755 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
4756 if (ch == '(' || ch == '{') {
4757 ch = (ch == '(' ? ')' : '}');
4758 if (!add_till_closing_bracket(dest, input, ch))
4764 if (!add_till_single_quote(dest, input))
4770 if (!add_till_double_quote(dest, input))
4776 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4782 /* \x. Copy verbatim. Important for \(, \) */
4783 ch = i_getch(input);
4785 syntax_error_unterm_ch(end_ch);
4790 /* "backslash+newline", ignore both */
4791 o_delchr(dest); /* undo insertion of '\' */
4796 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
4800 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
4803 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4805 /* Return code: 0 for OK, 1 for syntax error */
4807 #define parse_dollar(as_string, dest, input, quote_mask) \
4808 parse_dollar(dest, input, quote_mask)
4809 #define as_string NULL
4811 static int parse_dollar(o_string *as_string,
4813 struct in_str *input, unsigned char quote_mask)
4815 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4817 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4820 ch = i_getch(input);
4821 nommu_addchr(as_string, ch);
4823 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4825 debug_printf_parse(": '%c'\n", ch);
4826 o_addchr(dest, ch | quote_mask);
4828 ch = i_peek_and_eat_bkslash_nl(input);
4829 if (!isalnum(ch) && ch != '_') {
4830 /* End of variable name reached */
4833 ch = i_getch(input);
4834 nommu_addchr(as_string, ch);
4836 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4837 } else if (isdigit(ch)) {
4839 ch = i_getch(input);
4840 nommu_addchr(as_string, ch);
4841 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4842 debug_printf_parse(": '%c'\n", ch);
4843 o_addchr(dest, ch | quote_mask);
4844 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4845 } else switch (ch) {
4847 case '!': /* last bg pid */
4848 case '?': /* last exit code */
4849 case '#': /* number of args */
4850 case '*': /* args */
4851 case '@': /* args */
4852 goto make_one_char_var;
4856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4858 ch = i_getch(input); /* eat '{' */
4859 nommu_addchr(as_string, ch);
4861 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4862 /* It should be ${?}, or ${#var},
4863 * or even ${?+subst} - operator acting on a special variable,
4864 * or the beginning of variable name.
4867 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4870 syntax_error_unterm_str("${name}");
4871 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4874 nommu_addchr(as_string, ch);
4878 /* It's possible to just call add_till_closing_bracket() at this point.
4879 * However, this regresses some of our testsuite cases
4880 * which check invalid constructs like ${%}.
4881 * Oh well... let's check that the var name part is fine... */
4887 debug_printf_parse(": '%c'\n", ch);
4889 ch = i_getch(input);
4890 nommu_addchr(as_string, ch);
4894 if (!isalnum(ch) && ch != '_') {
4896 unsigned char last_ch;
4897 /* handle parameter expansions
4898 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4900 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4901 if (len_single_ch != '#'
4902 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4903 || i_peek(input) != '}'
4905 goto bad_dollar_syntax;
4907 /* else: it's "length of C" ${#C} op,
4908 * where C is a single char
4909 * special var name, e.g. ${#!}.
4912 /* Eat everything until closing '}' (or ':') */
4916 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4918 /* It's ${var:N[:M]} thing */
4919 end_ch = '}' * 0x100 + ':';
4921 if (BASH_PATTERN_SUBST
4924 /* It's ${var/[/]pattern[/repl]} thing */
4925 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4927 nommu_addchr(as_string, '/');
4930 end_ch = '}' * 0x100 + '/';
4936 #if ENABLE_HUSH_DOLLAR_OPS
4937 last_ch = add_till_closing_bracket(dest, input, end_ch);
4938 if (last_ch == 0) /* error? */
4941 #error Simple code to only allow ${var} is not implemented
4944 o_addstr(as_string, dest->data + pos);
4945 o_addchr(as_string, last_ch);
4948 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4949 && (end_ch & 0xff00)
4951 /* close the first block: */
4952 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4953 /* while parsing N from ${var:N[:M]}
4954 * or pattern from ${var/[/]pattern[/repl]} */
4955 if ((end_ch & 0xff) == last_ch) {
4956 /* got ':' or '/'- parse the rest */
4961 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4962 /* it's ${var:N} - emulate :999999999 */
4963 o_addstr(dest, "999999999");
4964 } /* else: it's ${var/[/]pattern} */
4968 len_single_ch = 0; /* it can't be ${#C} op */
4970 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4973 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4977 ch = i_getch(input);
4978 nommu_addchr(as_string, ch);
4979 # if ENABLE_FEATURE_SH_MATH
4980 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4981 ch = i_getch(input);
4982 nommu_addchr(as_string, ch);
4983 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4984 o_addchr(dest, /*quote_mask |*/ '+');
4987 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4988 return 0; /* error */
4990 o_addstr(as_string, dest->data + pos);
4991 o_addchr(as_string, ')');
4992 o_addchr(as_string, ')');
4994 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4998 # if ENABLE_HUSH_TICK
4999 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5000 o_addchr(dest, quote_mask | '`');
5003 if (!add_till_closing_bracket(dest, input, ')'))
5004 return 0; /* error */
5006 o_addstr(as_string, dest->data + pos);
5007 o_addchr(as_string, ')');
5009 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5017 /* TODO: $_ and $-: */
5018 /* $_ Shell or shell script name; or last argument of last command
5019 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5020 * but in command's env, set to full pathname used to invoke it */
5021 /* $- Option flags set by set builtin or shell options (-i etc) */
5022 ch = i_getch(input);
5023 nommu_addchr(as_string, ch);
5024 ch = i_peek_and_eat_bkslash_nl(input);
5025 if (isalnum(ch)) { /* it's $_name or $_123 */
5032 o_addQchr(dest, '$');
5034 debug_printf_parse("parse_dollar return 1 (ok)\n");
5040 #define encode_string(as_string, dest, input, dquote_end) \
5041 encode_string(dest, input, dquote_end)
5042 #define as_string NULL
5044 static int encode_string(o_string *as_string,
5046 struct in_str *input,
5053 ch = i_getch(input);
5055 nommu_addchr(as_string, ch);
5056 if (ch == dquote_end) { /* may be only '"' or EOF */
5057 debug_printf_parse("encode_string return 1 (ok)\n");
5060 /* note: can't move it above ch == dquote_end check! */
5062 syntax_error_unterm_ch('"');
5063 return 0; /* error */
5067 next = i_peek(input);
5069 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
5070 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5073 /* Testcase: in interactive shell a file with
5074 * echo "unterminated string\<eof>
5077 syntax_error_unterm_ch('"');
5078 return 0; /* error */
5081 * "The backslash retains its special meaning [in "..."]
5082 * only when followed by one of the following characters:
5083 * $, `, ", \, or <newline>. A double quote may be quoted
5084 * within double quotes by preceding it with a backslash."
5085 * NB: in (unquoted) heredoc, above does not apply to ",
5086 * therefore we check for it by "next == dquote_end" cond.
5088 if (next == dquote_end || strchr("$`\\\n", next)) {
5089 ch = i_getch(input); /* eat next */
5091 goto again; /* skip \<newline> */
5092 } /* else: ch remains == '\\', and we double it below: */
5093 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
5094 nommu_addchr(as_string, ch);
5098 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5099 debug_printf_parse("encode_string return 0: "
5100 "parse_dollar returned 0 (error)\n");
5105 #if ENABLE_HUSH_TICK
5107 //unsigned pos = dest->length;
5108 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5109 o_addchr(dest, 0x80 | '`');
5110 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5111 return 0; /* error */
5112 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5113 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5117 o_addQchr(dest, ch);
5123 * Scan input until EOF or end_trigger char.
5124 * Return a list of pipes to execute, or NULL on EOF
5125 * or if end_trigger character is met.
5126 * On syntax error, exit if shell is not interactive,
5127 * reset parsing machinery and start parsing anew,
5128 * or return ERR_PTR.
5130 static struct pipe *parse_stream(char **pstring,
5131 int *heredoc_cnt_ptr,
5132 struct in_str *input,
5135 struct parse_context ctx;
5138 /* Single-quote triggers a bypass of the main loop until its mate is
5139 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
5141 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5142 end_trigger ? end_trigger : 'X');
5145 initialize_context(&ctx);
5147 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5150 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
5152 /* We used to separate words on $IFS here. This was wrong.
5153 * $IFS is used only for word splitting when $var is expanded,
5154 * here we should use blank chars as separators, not $IFS
5159 const char *is_blank;
5160 const char *is_special;
5164 redir_type redir_style;
5166 ch = i_getch(input);
5167 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5168 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5173 syntax_error_unterm_str("here document");
5176 if (end_trigger == ')') {
5177 syntax_error_unterm_ch('(');
5180 if (end_trigger == '}') {
5181 syntax_error_unterm_ch('{');
5185 if (done_word(&ctx)) {
5188 o_free_and_set_NULL(&ctx.word);
5189 done_pipe(&ctx, PIPE_SEQ);
5191 /* If we got nothing... */
5192 /* (this makes bare "&" cmd a no-op.
5193 * bash says: "syntax error near unexpected token '&'") */
5194 if (pi->num_cmds == 0
5195 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
5201 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
5203 *pstring = ctx.as_string.data;
5205 o_free(&ctx.as_string);
5207 // heredoc_cnt must be 0 here anyway
5208 //if (heredoc_cnt_ptr)
5209 // *heredoc_cnt_ptr = heredoc_cnt;
5211 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5212 debug_printf_parse("parse_stream return %p\n", pi);
5216 /* Handle "'" and "\" first, as they won't play nice with
5217 * i_peek_and_eat_bkslash_nl() anyway:
5225 ch = i_getch(input);
5227 continue; /* drop \<newline>, get next char */
5228 nommu_addchr(&ctx.as_string, '\\');
5229 o_addchr(&ctx.word, '\\');
5231 /* Testcase: eval 'echo Ok\' */
5232 /* bash-4.3.43 was removing backslash,
5233 * but 4.4.19 retains it, most other shells too
5235 continue; /* get next char */
5237 /* Example: echo Hello \2>file
5238 * we need to know that word 2 is quoted
5240 ctx.word.has_quoted_part = 1;
5241 nommu_addchr(&ctx.as_string, ch);
5242 o_addchr(&ctx.word, ch);
5243 continue; /* get next char */
5245 nommu_addchr(&ctx.as_string, ch);
5247 ctx.word.has_quoted_part = 1;
5248 next = i_getch(input);
5249 if (next == '\'' && !ctx.pending_redirect)
5250 goto insert_empty_quoted_str_marker;
5255 syntax_error_unterm_ch('\'');
5258 nommu_addchr(&ctx.as_string, ch);
5261 if (ch == SPECIAL_VAR_SYMBOL) {
5262 /* Convert raw ^C to corresponding special variable reference */
5263 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5264 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5266 o_addqchr(&ctx.word, ch);
5267 ch = i_getch(input);
5269 continue; /* get next char */
5274 next = i_peek_and_eat_bkslash_nl(input);
5276 is_special = "{}<>;&|()#" /* special outside of "str" */
5277 "$\"" IF_HUSH_TICK("`") /* always special */
5278 SPECIAL_VAR_SYMBOL_STR;
5279 /* Are { and } special here? */
5280 if (ctx.command->argv /* word [word]{... - non-special */
5281 || ctx.word.length /* word{... - non-special */
5282 || ctx.word.has_quoted_part /* ""{... - non-special */
5283 || (next != ';' /* }; - special */
5284 && next != ')' /* }) - special */
5285 && next != '(' /* {( - special */
5286 && next != '&' /* }& and }&& ... - special */
5287 && next != '|' /* }|| ... - special */
5288 && !strchr(defifs, next) /* {word - non-special */
5291 /* They are not special, skip "{}" */
5294 is_special = strchr(is_special, ch);
5295 is_blank = strchr(defifs, ch);
5297 if (!is_special && !is_blank) { /* ordinary char */
5299 o_addQchr(&ctx.word, ch);
5300 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5301 || ctx.is_assignment == WORD_IS_KEYWORD)
5303 && is_well_formed_var_name(ctx.word.data, '=')
5305 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5306 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5312 #if ENABLE_HUSH_LINENO_VAR
5314 * "while ...; do<whitespace><newline>
5316 * would think that "cmd" starts in <whitespace> -
5317 * i.e., at the previous line.
5318 * We need to skip all whitespace before newlines.
5320 while (ch != '\n') {
5321 next = i_peek(input);
5322 if (next != ' ' && next != '\t' && next != '\n')
5323 break; /* next char is not ws */
5324 ch = i_getch(input);
5326 /* ch == last eaten whitespace char */
5328 if (done_word(&ctx)) {
5332 /* Is this a case when newline is simply ignored?
5334 * "cmd | <newline> cmd ..."
5335 * "case ... in <newline> word) ..."
5337 if (IS_NULL_CMD(ctx.command)
5338 && ctx.word.length == 0
5339 && !ctx.word.has_quoted_part
5342 /* This newline can be ignored. But...
5343 * Without check #1, interactive shell
5344 * ignores even bare <newline>,
5345 * and shows the continuation prompt:
5346 * ps1_prompt$ <enter>
5347 * ps2> _ <=== wrong, should be ps1
5348 * Without check #2, "cmd & <newline>"
5349 * is similarly mistreated.
5350 * (BTW, this makes "cmd & cmd"
5351 * and "cmd && cmd" non-orthogonal.
5352 * Really, ask yourself, why
5353 * "cmd && <newline>" doesn't start
5354 * cmd but waits for more input?
5355 * The only reason is that it might be
5356 * a "cmd1 && <nl> cmd2 &" construct,
5357 * cmd1 may need to run in BG).
5359 struct pipe *pi = ctx.list_head;
5360 if (pi->num_cmds != 0 /* check #1 */
5361 && pi->followup != PIPE_BG /* check #2 */
5366 /* Treat newline as a command separator. */
5367 done_pipe(&ctx, PIPE_SEQ);
5368 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
5370 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5371 if (heredoc_cnt != 0)
5374 ctx.is_assignment = MAYBE_ASSIGNMENT;
5375 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5377 /* note: if (is_blank) continue;
5378 * will still trigger for us */
5382 /* "cmd}" or "cmd }..." without semicolon or &:
5383 * } is an ordinary char in this case, even inside { cmd; }
5384 * Pathological example: { ""}; } should exec "}" cmd
5387 if (ctx.word.length != 0 /* word} */
5388 || ctx.word.has_quoted_part /* ""} */
5392 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5393 /* Generally, there should be semicolon: "cmd; }"
5394 * However, bash allows to omit it if "cmd" is
5395 * a group. Examples:
5398 * { echo 0 >&2 | { echo 1; } }
5399 * { while false; do :; done }
5400 * { case a in b) ;; esac }
5402 if (ctx.command->group)
5406 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5407 /* Can't be an end of {cmd}, skip the check */
5408 goto skip_end_trigger;
5409 /* else: } does terminate a group */
5412 if (end_trigger && end_trigger == ch
5413 && (ch != ';' || heredoc_cnt == 0)
5414 #if ENABLE_HUSH_CASE
5416 || ctx.ctx_res_w != RES_MATCH
5417 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
5421 if (done_word(&ctx)) {
5424 done_pipe(&ctx, PIPE_SEQ);
5425 ctx.is_assignment = MAYBE_ASSIGNMENT;
5426 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5427 /* Do we sit outside of any if's, loops or case's? */
5429 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5431 o_free_and_set_NULL(&ctx.word);
5433 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5435 *pstring = ctx.as_string.data;
5437 o_free(&ctx.as_string);
5439 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5440 /* Example: bare "{ }", "()" */
5441 G.last_exitcode = 2; /* bash compat */
5442 syntax_error_unexpected_ch(ch);
5445 if (heredoc_cnt_ptr)
5446 *heredoc_cnt_ptr = heredoc_cnt;
5447 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5448 debug_printf_parse("parse_stream return %p: "
5449 "end_trigger char found\n",
5452 return ctx.list_head;
5459 /* Catch <, > before deciding whether this word is
5460 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5463 redir_fd = redirect_opt_num(&ctx.word);
5464 if (done_word(&ctx)) {
5467 redir_style = REDIRECT_OVERWRITE;
5469 redir_style = REDIRECT_APPEND;
5470 ch = i_getch(input);
5471 nommu_addchr(&ctx.as_string, ch);
5474 else if (next == '(') {
5475 syntax_error(">(process) not supported");
5479 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5481 continue; /* get next char */
5483 redir_fd = redirect_opt_num(&ctx.word);
5484 if (done_word(&ctx)) {
5487 redir_style = REDIRECT_INPUT;
5489 redir_style = REDIRECT_HEREDOC;
5491 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
5492 ch = i_getch(input);
5493 nommu_addchr(&ctx.as_string, ch);
5494 } else if (next == '>') {
5495 redir_style = REDIRECT_IO;
5496 ch = i_getch(input);
5497 nommu_addchr(&ctx.as_string, ch);
5500 else if (next == '(') {
5501 syntax_error("<(process) not supported");
5505 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5507 continue; /* get next char */
5509 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
5510 /* skip "#comment" */
5511 /* note: we do not add it to &ctx.as_string */
5513 * comment inside $() goes to the next \n, even inside quoted string (!):
5514 * cmd "$(cmd2 #comment)" - syntax error
5515 * cmd "`cmd2 #comment`" - ok
5516 * We accept both (comment ends where command subst ends, in both cases).
5521 nommu_addchr(&ctx.as_string, '\n');
5524 ch = i_getch(input);
5528 continue; /* get next char */
5534 if (ctx.is_assignment == MAYBE_ASSIGNMENT
5535 /* check that we are not in word in "a=1 2>word b=1": */
5536 && !ctx.pending_redirect
5538 /* ch is a special char and thus this word
5539 * cannot be an assignment */
5540 ctx.is_assignment = NOT_ASSIGNMENT;
5541 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5544 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5547 case SPECIAL_VAR_SYMBOL:
5548 /* Convert raw ^C to corresponding special variable reference */
5549 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5550 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5553 /* non-comment #: "echo a#b" etc */
5554 o_addchr(&ctx.word, ch);
5555 continue; /* get next char */
5557 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
5558 debug_printf_parse("parse_stream parse error: "
5559 "parse_dollar returned 0 (error)\n");
5562 continue; /* get next char */
5564 ctx.word.has_quoted_part = 1;
5565 if (next == '"' && !ctx.pending_redirect) {
5566 i_getch(input); /* eat second " */
5567 insert_empty_quoted_str_marker:
5568 nommu_addchr(&ctx.as_string, next);
5569 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5570 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5571 continue; /* get next char */
5573 if (ctx.is_assignment == NOT_ASSIGNMENT)
5574 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5575 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
5577 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5578 continue; /* get next char */
5579 #if ENABLE_HUSH_TICK
5581 USE_FOR_NOMMU(unsigned pos;)
5583 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5584 o_addchr(&ctx.word, '`');
5585 USE_FOR_NOMMU(pos = ctx.word.length;)
5586 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
5589 o_addstr(&ctx.as_string, ctx.word.data + pos);
5590 o_addchr(&ctx.as_string, '`');
5592 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5593 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
5594 continue; /* get next char */
5598 #if ENABLE_HUSH_CASE
5601 if (done_word(&ctx)) {
5604 done_pipe(&ctx, PIPE_SEQ);
5605 #if ENABLE_HUSH_CASE
5606 /* Eat multiple semicolons, detect
5607 * whether it means something special */
5609 ch = i_peek_and_eat_bkslash_nl(input);
5612 ch = i_getch(input);
5613 nommu_addchr(&ctx.as_string, ch);
5614 if (ctx.ctx_res_w == RES_CASE_BODY) {
5615 ctx.ctx_dsemicolon = 1;
5616 ctx.ctx_res_w = RES_MATCH;
5622 /* We just finished a cmd. New one may start
5623 * with an assignment */
5624 ctx.is_assignment = MAYBE_ASSIGNMENT;
5625 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5626 continue; /* get next char */
5628 if (done_word(&ctx)) {
5632 ch = i_getch(input);
5633 nommu_addchr(&ctx.as_string, ch);
5634 done_pipe(&ctx, PIPE_AND);
5636 done_pipe(&ctx, PIPE_BG);
5640 if (done_word(&ctx)) {
5643 #if ENABLE_HUSH_CASE
5644 if (ctx.ctx_res_w == RES_MATCH)
5645 break; /* we are in case's "word | word)" */
5647 if (next == '|') { /* || */
5648 ch = i_getch(input);
5649 nommu_addchr(&ctx.as_string, ch);
5650 done_pipe(&ctx, PIPE_OR);
5652 /* we could pick up a file descriptor choice here
5653 * with redirect_opt_num(), but bash doesn't do it.
5654 * "echo foo 2| cat" yields "foo 2". */
5659 #if ENABLE_HUSH_CASE
5660 /* "case... in [(]word)..." - skip '(' */
5661 if (ctx.ctx_res_w == RES_MATCH
5662 && ctx.command->argv == NULL /* not (word|(... */
5663 && ctx.word.length == 0 /* not word(... */
5664 && ctx.word.has_quoted_part == 0 /* not ""(... */
5666 continue; /* get next char */
5671 int n = parse_group(&ctx, input, ch);
5675 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5680 #if ENABLE_HUSH_CASE
5681 if (ctx.ctx_res_w == RES_MATCH)
5686 /* proper use of this character is caught by end_trigger:
5687 * if we see {, we call parse_group(..., end_trigger='}')
5688 * and it will match } earlier (not here). */
5689 G.last_exitcode = 2;
5690 syntax_error_unexpected_ch(ch);
5694 bb_error_msg_and_die("BUG: unexpected %c", ch);
5699 G.last_exitcode = 1;
5702 struct parse_context *pctx;
5703 IF_HAS_KEYWORDS(struct parse_context *p2;)
5705 /* Clean up allocated tree.
5706 * Sample for finding leaks on syntax error recovery path.
5707 * Run it from interactive shell, watch pmap `pidof hush`.
5708 * while if false; then false; fi; do break; fi
5709 * Samples to catch leaks at execution:
5710 * while if (true | { true;}); then echo ok; fi; do break; done
5711 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5715 /* Update pipe/command counts,
5716 * otherwise freeing may miss some */
5717 done_pipe(pctx, PIPE_SEQ);
5718 debug_printf_clean("freeing list %p from ctx %p\n",
5719 pctx->list_head, pctx);
5720 debug_print_tree(pctx->list_head, 0);
5721 free_pipe_list(pctx->list_head);
5722 debug_printf_clean("freed list %p\n", pctx->list_head);
5724 o_free(&pctx->as_string);
5726 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5730 IF_HAS_KEYWORDS(pctx = p2;)
5731 } while (HAS_KEYWORDS && pctx);
5744 /*** Execution routines ***/
5746 /* Expansion can recurse, need forward decls: */
5747 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5748 #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
5749 expand_string_to_string(str)
5751 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
5752 #if ENABLE_HUSH_TICK
5753 static int process_command_subs(o_string *dest, const char *s);
5755 static int expand_vars_to_list(o_string *output, int n, char *arg);
5757 /* expand_strvec_to_strvec() takes a list of strings, expands
5758 * all variable references within and returns a pointer to
5759 * a list of expanded strings, possibly with larger number
5760 * of strings. (Think VAR="a b"; echo $VAR).
5761 * This new list is allocated as a single malloc block.
5762 * NULL-terminated list of char* pointers is at the beginning of it,
5763 * followed by strings themselves.
5764 * Caller can deallocate entire list by single free(list). */
5766 /* A horde of its helpers come first: */
5768 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5770 while (--len >= 0) {
5773 #if ENABLE_HUSH_BRACE_EXPANSION
5774 if (c == '{' || c == '}') {
5775 /* { -> \{, } -> \} */
5777 /* And now we want to add { or } and continue:
5780 * luckily, just falling through achieves this.
5786 /* \z -> \\\z; \<eol> -> \\<eol> */
5791 o_addchr(o, *str++);
5797 /* Store given string, finalizing the word and starting new one whenever
5798 * we encounter IFS char(s). This is used for expanding variable values.
5799 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5800 * Return in output->ended_in_ifs:
5801 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5803 static int expand_on_ifs(o_string *output, int n, const char *str)
5805 int last_is_ifs = 0;
5810 if (!*str) /* EOL - do not finalize word */
5812 word_len = strcspn(str, G.ifs);
5814 /* We have WORD_LEN leading non-IFS chars */
5815 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5816 o_addblock(output, str, word_len);
5818 /* Protect backslashes against globbing up :)
5819 * Example: "v='\*'; echo b$v" prints "b\*"
5820 * (and does not try to glob on "*")
5822 o_addblock_duplicate_backslash(output, str, word_len);
5823 /*/ Why can't we do it easier? */
5824 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5825 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5829 if (!*str) /* EOL - do not finalize word */
5833 /* We know str here points to at least one IFS char */
5835 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
5836 if (!*str) /* EOL - do not finalize word */
5839 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5840 && strchr(G.ifs, *str) /* the second check would fail */
5842 /* This is a non-whitespace $IFS char */
5843 /* Skip it and IFS whitespace chars, start new word */
5845 str += strspn(str, G.ifs_whitespace);
5849 /* Start new word... but not always! */
5850 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5851 if (output->has_quoted_part
5853 * Case "v=' a'; echo $v":
5854 * here nothing precedes the space in $v expansion,
5855 * therefore we should not finish the word
5856 * (IOW: if there *is* word to finalize, only then do it):
5857 * It's okay if this accesses the byte before first argv[]:
5858 * past call to o_save_ptr() cleared it to zero byte
5859 * (grep for -prev-ifs-check-).
5861 || output->data[output->length - 1]
5864 o_addchr(output, '\0');
5865 debug_print_list("expand_on_ifs", output, n);
5866 n = o_save_ptr(output, n);
5870 output->ended_in_ifs = last_is_ifs;
5871 debug_print_list("expand_on_ifs[1]", output, n);
5875 /* Helper to expand $((...)) and heredoc body. These act as if
5876 * they are in double quotes, with the exception that they are not :).
5877 * Just the rules are similar: "expand only $var and `cmd`"
5879 * Returns malloced string.
5880 * As an optimization, we return NULL if expansion is not needed.
5882 static char *encode_then_expand_string(const char *str)
5885 struct in_str input;
5886 o_string dest = NULL_O_STRING;
5891 if (!*cp) return NULL; /* string has no special chars */
5892 if (*cp == '$') break;
5893 if (*cp == '\\') break;
5894 #if ENABLE_HUSH_TICK
5895 if (*cp == '`') break;
5900 /* We need to expand. Example:
5901 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5903 setup_string_in_str(&input, str);
5904 encode_string(NULL, &dest, &input, EOF);
5905 //TODO: error check (encode_string returns 0 on error)?
5906 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5907 exp_str = expand_string_to_string(dest.data,
5908 EXP_FLAG_ESC_GLOB_CHARS,
5911 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5916 static const char *first_special_char_in_vararg(const char *cp)
5919 if (!*cp) return NULL; /* string has no special chars */
5920 if (*cp == '$') return cp;
5921 if (*cp == '\\') return cp;
5922 if (*cp == '\'') return cp;
5923 if (*cp == '"') return cp;
5924 #if ENABLE_HUSH_TICK
5925 if (*cp == '`') return cp;
5927 /* dquoted "${x:+ARG}" should not glob, therefore
5928 * '*' et al require some non-literal processing: */
5929 if (*cp == '*') return cp;
5930 if (*cp == '?') return cp;
5931 if (*cp == '[') return cp;
5936 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5937 * These can contain single- and double-quoted strings,
5938 * and treated as if the ARG string is initially unquoted. IOW:
5939 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5940 * a dquoted string: "${var#"zz"}"), the difference only comes later
5941 * (word splitting and globbing of the ${var...} result).
5943 #if !BASH_PATTERN_SUBST
5944 #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5945 encode_then_expand_vararg(str, handle_squotes)
5947 static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5949 #if !BASH_PATTERN_SUBST
5950 const int do_unbackslash = 0;
5953 struct in_str input;
5954 o_string dest = NULL_O_STRING;
5956 if (!first_special_char_in_vararg(str)) {
5957 /* string has no special chars */
5961 setup_string_in_str(&input, str);
5962 dest.data = xzalloc(1); /* start as "", not as NULL */
5968 ch = i_getch(&input);
5969 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5970 __func__, ch, ch, !!dest.o_expflags);
5972 if (!dest.o_expflags) {
5975 if (handle_squotes && ch == '\'') {
5976 if (!add_till_single_quote_dquoted(&dest, &input))
5977 goto ret; /* error */
5982 syntax_error_unterm_ch('"');
5983 goto ret; /* error */
5986 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5990 ch = i_getch(&input);
5992 //example? error message? syntax_error_unterm_ch('"');
5993 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5996 o_addqchr(&dest, ch);
6000 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6001 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6006 #if ENABLE_HUSH_TICK
6008 //unsigned pos = dest->length;
6009 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6010 o_addchr(&dest, 0x80 | '`');
6011 if (!add_till_backquote(&dest, &input,
6012 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6015 goto ret; /* error */
6017 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6018 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6022 o_addQchr(&dest, ch);
6025 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6026 exp_str = expand_string_to_string(dest.data,
6027 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6031 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
6036 /* Expanding ARG in ${var+ARG}, ${var-ARG}
6038 static int encode_then_append_var_plusminus(o_string *output, int n,
6039 char *str, int dquoted)
6041 struct in_str input;
6042 o_string dest = NULL_O_STRING;
6044 if (!first_special_char_in_vararg(str)
6045 && '\0' == str[strcspn(str, G.ifs)]
6047 /* string has no special chars
6048 * && string has no $IFS chars
6050 return expand_vars_to_list(output, n, str);
6053 setup_string_in_str(&input, str);
6058 ch = i_getch(&input);
6059 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6060 __func__, ch, ch, dest.o_expflags);
6062 if (!dest.o_expflags) {
6065 if (!dquoted && strchr(G.ifs, ch)) {
6066 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6067 * do not assume we are at the start of the word (PREFIX above).
6070 n = expand_vars_to_list(output, n, dest.data);
6071 o_free_and_set_NULL(&dest);
6072 o_addchr(output, '\0');
6073 n = o_save_ptr(output, n); /* create next word */
6075 if (output->length != o_get_last_ptr(output, n)
6076 || output->has_quoted_part
6079 * f() { for i; do echo "|$i|"; done; }; x=x
6080 * f a${x:+ }b # 1st condition
6083 * f ""${x:+ }b # 2nd condition
6087 o_addchr(output, '\0');
6088 n = o_save_ptr(output, n); /* create next word */
6092 if (!dquoted && ch == '\'') {
6093 if (!add_till_single_quote_dquoted(&dest, &input))
6094 goto ret; /* error */
6095 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6096 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6101 syntax_error_unterm_ch('"');
6102 goto ret; /* error */
6105 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6106 if (dest.o_expflags) {
6107 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6108 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6113 ch = i_getch(&input);
6115 //example? error message? syntax_error_unterm_ch('"');
6116 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6119 o_addqchr(&dest, ch);
6123 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6124 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6129 #if ENABLE_HUSH_TICK
6131 //unsigned pos = dest->length;
6132 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6133 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6134 if (!add_till_backquote(&dest, &input,
6135 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6138 goto ret; /* error */
6140 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6141 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6146 /* Always glob-protect if in dquotes:
6147 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6148 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6150 o_addqchr(&dest, ch);
6152 /* Glob-protect only if char is quoted:
6153 * x=x; echo ${x:+/bin/c*} - prints many filenames
6154 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6156 o_addQchr(&dest, ch);
6161 n = expand_vars_to_list(output, n, dest.data);
6168 #if ENABLE_FEATURE_SH_MATH
6169 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
6171 arith_state_t math_state;
6175 math_state.lookupvar = get_local_var_value;
6176 math_state.setvar = set_local_var_from_halves;
6177 //math_state.endofname = endofname;
6178 exp_str = encode_then_expand_string(arg);
6179 res = arith(&math_state, exp_str ? exp_str : arg);
6182 *errmsg_p = math_state.errmsg;
6183 if (math_state.errmsg)
6184 msg_and_die_if_script(math_state.errmsg);
6189 #if BASH_PATTERN_SUBST
6190 /* ${var/[/]pattern[/repl]} helpers */
6191 static char *strstr_pattern(char *val, const char *pattern, int *size)
6194 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6195 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6202 /* Optimization: if "*pat" did not match the start of "string",
6203 * we know that "tring", "ring" etc will not match too:
6205 if (pattern[0] == '*')
6210 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6212 char *result = NULL;
6213 unsigned res_len = 0;
6214 unsigned repl_len = strlen(repl);
6216 /* Null pattern never matches, including if "var" is empty */
6218 return result; /* NULL, no replaces happened */
6222 char *s = strstr_pattern(val, pattern, &size);
6226 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
6227 strcpy(mempcpy(result + res_len, val, s - val), repl);
6228 res_len += (s - val) + repl_len;
6229 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6235 if (*val && result) {
6236 result = xrealloc(result, res_len + strlen(val) + 1);
6237 strcpy(result + res_len, val);
6238 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6240 debug_printf_varexp("result:'%s'\n", result);
6243 #endif /* BASH_PATTERN_SUBST */
6245 static int append_str_maybe_ifs_split(o_string *output, int n,
6246 int first_ch, const char *val)
6248 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6249 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6250 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6252 n = expand_on_ifs(output, n, val);
6253 } else { /* quoted "$VAR" */
6254 output->has_quoted_part = 1;
6255 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6256 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6258 o_addQstr(output, val);
6263 /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6265 static NOINLINE int expand_one_var(o_string *output, int n,
6266 int first_ch, char *arg, char **pp)
6273 char exp_save = exp_save; /* for compiler */
6274 char *exp_saveptr; /* points to expansion operator */
6275 char *exp_word = exp_word; /* for compiler */
6281 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
6283 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
6285 arg[0] = (arg0 & 0x7f);
6288 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
6289 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6290 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6291 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
6293 /* It must be length operator: ${#var} */
6297 /* Maybe handle parameter expansion */
6298 if (exp_saveptr /* if 2nd char is one of expansion operators */
6299 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
6301 /* ${?:0}, ${#[:]%0} etc */
6302 exp_saveptr = var + 1;
6304 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6305 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6307 exp_op = exp_save = *exp_saveptr;
6309 exp_word = exp_saveptr + 1;
6310 if (exp_op == ':') {
6311 exp_op = *exp_word++;
6312 //TODO: try ${var:} and ${var:bogus} in non-bash config
6314 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
6316 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6321 *exp_saveptr = '\0';
6322 } /* else: it's not an expansion op, but bare ${var} */
6325 /* Look up the variable in question */
6326 if (isdigit(var[0])) {
6327 /* parse_dollar should have vetted var for us */
6328 int nn = xatoi_positive(var);
6329 if (nn < G.global_argc)
6330 val = G.global_argv[nn];
6331 /* else val remains NULL: $N with too big N */
6335 val = utoa(G.root_pid);
6337 case '!': /* bg pid */
6338 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6340 case '?': /* exitcode */
6341 val = utoa(G.last_exitcode);
6343 case '#': /* argc */
6344 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6347 val = get_local_var_value(var);
6351 /* Handle any expansions */
6352 if (exp_op == 'L') {
6353 reinit_unicode_for_hush();
6354 debug_printf_expand("expand: length(%s)=", val);
6355 val = utoa(val ? unicode_strlen(val) : 0);
6356 debug_printf_expand("%s\n", val);
6357 } else if (exp_op) {
6358 if (exp_op == '%' || exp_op == '#') {
6359 /* Standard-mandated substring removal ops:
6360 * ${parameter%word} - remove smallest suffix pattern
6361 * ${parameter%%word} - remove largest suffix pattern
6362 * ${parameter#word} - remove smallest prefix pattern
6363 * ${parameter##word} - remove largest prefix pattern
6365 * Word is expanded to produce a glob pattern.
6366 * Then var's value is matched to it and matching part removed.
6368 //FIXME: ${x#...${...}...}
6369 //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6370 //inner ${...} may have side effects!
6371 if (val && val[0]) {
6375 unsigned scan_flags = pick_scan(exp_op, *exp_word);
6376 if (exp_op == *exp_word) /* ## or %% */
6378 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6379 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6381 exp_word = exp_exp_word;
6382 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6384 * HACK ALERT. We depend here on the fact that
6385 * G.global_argv and results of utoa and get_local_var_value
6386 * are actually in writable memory:
6387 * scan_and_match momentarily stores NULs there.
6390 loc = scan_and_match(t, exp_word, scan_flags);
6391 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
6393 if (loc) { /* match was found */
6394 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
6395 val = loc; /* take right part */
6397 val = to_be_freed = xstrndup(val, loc - val); /* left */
6401 #if BASH_PATTERN_SUBST
6402 else if (exp_op == '/' || exp_op == '\\') {
6403 /* It's ${var/[/]pattern[/repl]} thing.
6404 * Note that in encoded form it has TWO parts:
6405 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6406 * and if // is used, it is encoded as \:
6407 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6409 if (val && val[0]) {
6410 /* pattern uses non-standard expansion.
6411 * repl should be unbackslashed and globbed
6412 * by the usual expansion rules:
6414 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6415 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6416 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6417 * v='a bz'; echo ${v/a*z/\z} #prints "z"
6418 * (note that a*z _pattern_ is never globbed!)
6420 char *pattern, *repl, *t;
6421 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6423 pattern = xstrdup(exp_word);
6424 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6425 *p++ = SPECIAL_VAR_SYMBOL;
6427 p = strchr(p, SPECIAL_VAR_SYMBOL);
6429 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
6430 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
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 * replace_pattern momentarily stores NULs there. */
6436 to_be_freed = replace_pattern(t,
6438 (repl ? repl : exp_word),
6440 if (to_be_freed) /* at least one replace happened */
6445 /* Empty variable always gives nothing */
6446 // "v=''; echo ${v/*/w}" prints "", not "w"
6447 /* Just skip "replace" part */
6448 *p++ = SPECIAL_VAR_SYMBOL;
6449 p = strchr(p, SPECIAL_VAR_SYMBOL);
6453 #endif /* BASH_PATTERN_SUBST */
6454 else if (exp_op == ':') {
6455 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
6456 /* It's ${var:N[:M]} bashism.
6457 * Note that in encoded form it has TWO parts:
6458 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6463 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6466 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6467 *p++ = SPECIAL_VAR_SYMBOL;
6469 p = strchr(p, SPECIAL_VAR_SYMBOL);
6471 len = expand_and_evaluate_arith(exp_word, &errmsg);
6474 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
6476 /* negative beg counts from the end */
6477 beg = (arith_t)strlen(val) + beg;
6478 if (beg < 0) /* ${v: -999999} is "" */
6481 debug_printf_varexp("from val:'%s'\n", val);
6483 /* in bash, len=-n means strlen()-n */
6484 len = (arith_t)strlen(val) - beg + len;
6485 if (len < 0) /* bash compat */
6486 msg_and_die_if_script("%s: substring expression < 0", var);
6488 if (len <= 0 || !val || beg >= strlen(val)) {
6492 /* Paranoia. What if user entered 9999999999999
6493 * which fits in arith_t but not int? */
6496 val = to_be_freed = xstrndup(val + beg, len);
6498 debug_printf_varexp("val:'%s'\n", val);
6499 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
6500 msg_and_die_if_script("malformed ${%s:...}", var);
6503 } else { /* one of "-=+?" */
6504 /* Standard-mandated substitution ops:
6505 * ${var?word} - indicate error if unset
6506 * If var is unset, word (or a message indicating it is unset
6507 * if word is null) is written to standard error
6508 * and the shell exits with a non-zero exit status.
6509 * Otherwise, the value of var is substituted.
6510 * ${var-word} - use default value
6511 * If var is unset, word is substituted.
6512 * ${var=word} - assign and use default value
6513 * If var is unset, word is assigned to var.
6514 * In all cases, final value of var is substituted.
6515 * ${var+word} - use alternative value
6516 * If var is unset, null is substituted.
6517 * Otherwise, word is substituted.
6519 * Word is subjected to tilde expansion, parameter expansion,
6520 * command substitution, and arithmetic expansion.
6521 * If word is not needed, it is not expanded.
6523 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6524 * but also treat null var as if it is unset.
6526 * Word-splitting and single quote behavior:
6528 * $ f() { for i; do echo "|$i|"; done; };
6530 * $ x=; f ${x:?'x y' z}
6531 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6532 * $ x=; f "${x:?'x y' z}"
6533 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6535 * $ x=; f ${x:='x y' z}
6539 * $ x=; f "${x:='x y' z}"
6542 * $ x=x; f ${x:+'x y' z}
6545 * $ x=x; f "${x:+'x y' z}"
6548 * $ x=; f ${x:-'x y' z}
6551 * $ x=; f "${x:-'x y' z}"
6554 int use_word = (!val || ((exp_save == ':') && !val[0]));
6556 use_word = !use_word;
6557 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6558 (exp_save == ':') ? "true" : "false", use_word);
6560 if (exp_op == '+' || exp_op == '-') {
6561 /* ${var+word} - use alternative value */
6562 /* ${var-word} - use default value */
6563 n = encode_then_append_var_plusminus(output, n, exp_word,
6564 /*dquoted:*/ (arg0 & 0x80)
6568 /* ${var?word} - indicate error if unset */
6569 /* ${var=word} - assign and use default value */
6570 to_be_freed = encode_then_expand_vararg(exp_word,
6571 /*handle_squotes:*/ !(arg0 & 0x80),
6575 exp_word = to_be_freed;
6576 if (exp_op == '?') {
6577 /* mimic bash message */
6578 msg_and_die_if_script("%s: %s",
6582 : "parameter null or not set"
6583 /* ash has more specific messages, a-la: */
6584 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6586 //TODO: how interactive bash aborts expansion mid-command?
6587 //It aborts the entire line, returns to prompt:
6588 // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6591 // ("echo YO" is not executed, neither the f function call)
6595 if (exp_op == '=') {
6596 /* ${var=[word]} or ${var:=[word]} */
6597 if (isdigit(var[0]) || var[0] == '#') {
6598 /* mimic bash message */
6599 msg_and_die_if_script("$%s: cannot assign in this way", var);
6602 char *new_var = xasprintf("%s=%s", var, val);
6603 set_local_var(new_var, /*flag:*/ 0);
6608 } /* one of "-=+?" */
6610 *exp_saveptr = exp_save;
6616 n = append_str_maybe_ifs_split(output, n, first_ch, val);
6622 /* Expand all variable references in given string, adding words to list[]
6623 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6624 * to be filled). This routine is extremely tricky: has to deal with
6625 * variables/parameters with whitespace, $* and $@, and constructs like
6626 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
6627 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
6629 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
6630 * expansion of right-hand side of assignment == 1-element expand.
6632 char cant_be_null = 0; /* only bit 0x80 matters */
6635 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6636 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
6637 debug_print_list("expand_vars_to_list[0]", output, n);
6639 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6641 #if ENABLE_FEATURE_SH_MATH
6642 char arith_buf[sizeof(arith_t)*3 + 2];
6645 if (output->ended_in_ifs) {
6646 o_addchr(output, '\0');
6647 n = o_save_ptr(output, n);
6648 output->ended_in_ifs = 0;
6651 o_addblock(output, arg, p - arg);
6652 debug_print_list("expand_vars_to_list[1]", output, n);
6654 p = strchr(p, SPECIAL_VAR_SYMBOL);
6656 /* Fetch special var name (if it is indeed one of them)
6657 * and quote bit, force the bit on if singleword expansion -
6658 * important for not getting v=$@ expand to many words. */
6659 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6661 /* Is this variable quoted and thus expansion can't be null?
6662 * "$@" is special. Even if quoted, it can still
6663 * expand to nothing (not even an empty string),
6664 * thus it is excluded. */
6665 if ((first_ch & 0x7f) != '@')
6666 cant_be_null |= first_ch;
6668 switch (first_ch & 0x7f) {
6669 /* Highest bit in first_ch indicates that var is double-quoted */
6673 if (!G.global_argv[1])
6676 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6677 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6678 while (G.global_argv[i]) {
6679 n = expand_on_ifs(output, n, G.global_argv[i]);
6680 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6681 if (G.global_argv[i++][0] && G.global_argv[i]) {
6682 /* this argv[] is not empty and not last:
6683 * put terminating NUL, start new word */
6684 o_addchr(output, '\0');
6685 debug_print_list("expand_vars_to_list[2]", output, n);
6686 n = o_save_ptr(output, n);
6687 debug_print_list("expand_vars_to_list[3]", output, n);
6691 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6692 * and in this case should treat it like '$*' - see 'else...' below */
6693 if (first_ch == (char)('@'|0x80) /* quoted $@ */
6694 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6697 o_addQstr(output, G.global_argv[i]);
6698 if (++i >= G.global_argc)
6700 o_addchr(output, '\0');
6701 debug_print_list("expand_vars_to_list[4]", output, n);
6702 n = o_save_ptr(output, n);
6704 } else { /* quoted $* (or v="$@" case): add as one word */
6706 o_addQstr(output, G.global_argv[i]);
6707 if (!G.global_argv[++i])
6710 o_addchr(output, G.ifs[0]);
6712 output->has_quoted_part = 1;
6716 case SPECIAL_VAR_SYMBOL: {
6717 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6718 /* "Empty variable", used to make "" etc to not disappear */
6719 output->has_quoted_part = 1;
6720 cant_be_null = 0x80;
6724 case SPECIAL_VAR_QUOTED_SVS:
6725 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6726 /* "^C variable", represents literal ^C char (possible in scripts) */
6727 o_addchr(output, SPECIAL_VAR_SYMBOL);
6730 #if ENABLE_HUSH_TICK
6732 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6733 o_string subst_result = NULL_O_STRING;
6735 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6737 /* Can't just stuff it into output o_string,
6738 * expanded result may need to be globbed
6740 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6741 G.last_exitcode = process_command_subs(&subst_result, arg);
6742 G.expand_exitcode = G.last_exitcode;
6743 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6744 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
6745 o_free(&subst_result);
6749 #if ENABLE_FEATURE_SH_MATH
6751 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
6754 arg++; /* skip '+' */
6755 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6756 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6757 res = expand_and_evaluate_arith(arg, NULL);
6758 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6759 sprintf(arith_buf, ARITH_FMT, res);
6760 o_addstr(output, arith_buf);
6765 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
6766 n = expand_one_var(output, n, first_ch, arg, &p);
6768 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6770 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6771 * Do the check to avoid writing to a const string. */
6772 if (*p != SPECIAL_VAR_SYMBOL)
6773 *p = SPECIAL_VAR_SYMBOL;
6775 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6778 /* handle trailing string */
6779 if (output->ended_in_ifs) {
6780 o_addchr(output, '\0');
6781 n = o_save_ptr(output, n);
6783 debug_print_list("expand_vars_to_list[a]", output, n);
6784 /* this part is literal, and it was already pre-quoted
6785 * if needed (much earlier), do not use o_addQstr here!
6787 o_addstr(output, arg);
6788 debug_print_list("expand_vars_to_list[b]", output, n);
6790 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6791 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6792 && !output->has_quoted_part
6795 /* allow to reuse list[n] later without re-growth */
6796 output->has_empty_slot = 1;
6802 static char **expand_variables(char **argv, unsigned expflags)
6806 o_string output = NULL_O_STRING;
6808 output.o_expflags = expflags;
6812 /* go to next list[n] */
6813 output.ended_in_ifs = 0;
6814 n = o_save_ptr(&output, n);
6819 /* expand argv[i] */
6820 n = expand_vars_to_list(&output, n, *argv++);
6821 /* if (!output->has_empty_slot) -- need this?? */
6822 o_addchr(&output, '\0');
6824 debug_print_list("expand_variables", &output, n);
6826 /* output.data (malloced in one block) gets returned in "list" */
6827 list = o_finalize_list(&output, n);
6828 debug_print_strings("expand_variables[1]", list);
6832 static char **expand_strvec_to_strvec(char **argv)
6834 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6837 #if defined(CMD_SINGLEWORD_NOGLOB)
6838 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6840 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6844 /* Used for expansion of right hand of assignments,
6845 * $((...)), heredocs, variable expansion parts.
6847 * NB: should NOT do globbing!
6848 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6850 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
6852 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6853 const int do_unbackslash = 1;
6854 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
6856 char *argv[2], **list;
6858 debug_printf_expand("string_to_string<='%s'\n", str);
6859 /* This is generally an optimization, but it also
6860 * handles "", which otherwise trips over !list[0] check below.
6861 * (is this ever happens that we actually get str="" here?)
6863 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6864 //TODO: Can use on strings with \ too, just unbackslash() them?
6865 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6866 return xstrdup(str);
6869 argv[0] = (char*)str;
6871 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
6873 /* Example where it happens:
6874 * x=; echo ${x:-"$@"}
6876 ((char*)list)[0] = '\0';
6880 bb_error_msg_and_die("BUG in varexp2");
6881 /* actually, just move string 2*sizeof(char*) bytes back */
6882 overlapping_strcpy((char*)list, list[0]);
6884 unbackslash((char*)list);
6886 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6891 static char* expand_strvec_to_string(char **argv)
6895 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6896 /* Convert all NULs to spaces */
6901 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6902 bb_error_msg_and_die("BUG in varexp3");
6903 /* bash uses ' ' regardless of $IFS contents */
6908 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6909 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6914 static char **expand_assignments(char **argv, int count)
6919 G.expanded_assignments = p = NULL;
6920 /* Expand assignments into one string each */
6921 for (i = 0; i < count; i++) {
6922 p = add_string_to_strings(p,
6923 expand_string_to_string(argv[i],
6924 EXP_FLAG_ESC_GLOB_CHARS,
6928 G.expanded_assignments = p;
6930 G.expanded_assignments = NULL;
6935 static void switch_off_special_sigs(unsigned mask)
6938 while ((mask >>= 1) != 0) {
6942 #if ENABLE_HUSH_TRAP
6944 if (G_traps[sig] && !G_traps[sig][0])
6945 /* trap is '', has to remain SIG_IGN */
6948 G_traps[sig] = NULL;
6951 /* We are here only if no trap or trap was not '' */
6952 install_sighandler(sig, SIG_DFL);
6958 void re_execute_shell(char ***to_free, const char *s,
6959 char *g_argv0, char **g_argv,
6960 char **builtin_argv) NORETURN;
6962 static void reset_traps_to_defaults(void)
6964 /* This function is always called in a child shell
6965 * after fork (not vfork, NOMMU doesn't use this function).
6967 IF_HUSH_TRAP(unsigned sig;)
6970 /* Child shells are not interactive.
6971 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6972 * Testcase: (while :; do :; done) + ^Z should background.
6973 * Same goes for SIGTERM, SIGHUP, SIGINT.
6975 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6976 if (!G_traps && !mask)
6977 return; /* already no traps and no special sigs */
6979 /* Switch off special sigs */
6980 switch_off_special_sigs(mask);
6981 # if ENABLE_HUSH_JOB
6982 G_fatal_sig_mask = 0;
6984 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6985 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6986 * remain set in G.special_sig_mask */
6988 # if ENABLE_HUSH_TRAP
6992 /* Reset all sigs to default except ones with empty traps */
6993 for (sig = 0; sig < NSIG; sig++) {
6995 continue; /* no trap: nothing to do */
6996 if (!G_traps[sig][0])
6997 continue; /* empty trap: has to remain SIG_IGN */
6998 /* sig has non-empty trap, reset it: */
7000 G_traps[sig] = NULL;
7001 /* There is no signal for trap 0 (EXIT) */
7004 install_sighandler(sig, pick_sighandler(sig));
7011 static void re_execute_shell(char ***to_free, const char *s,
7012 char *g_argv0, char **g_argv,
7013 char **builtin_argv) NORETURN;
7014 static void re_execute_shell(char ***to_free, const char *s,
7015 char *g_argv0, char **g_argv,
7016 char **builtin_argv)
7018 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7019 /* delims + 2 * (number of bytes in printed hex numbers) */
7020 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7021 char *heredoc_argv[4];
7022 struct variable *cur;
7023 # if ENABLE_HUSH_FUNCTIONS
7024 struct function *funcp;
7028 unsigned long long empty_trap_mask;
7030 if (!g_argv0) { /* heredoc */
7031 argv = heredoc_argv;
7032 argv[0] = (char *) G.argv0_for_re_execing;
7033 argv[1] = (char *) "-<";
7034 argv[2] = (char *) s;
7036 pp = &argv[3]; /* used as pointer to empty environment */
7042 if (pp) while (*pp++)
7045 empty_trap_mask = 0;
7048 for (sig = 1; sig < NSIG; sig++) {
7049 if (G_traps[sig] && !G_traps[sig][0])
7050 empty_trap_mask |= 1LL << sig;
7054 sprintf(param_buf, NOMMU_HACK_FMT
7055 , (unsigned) G.root_pid
7056 , (unsigned) G.root_ppid
7057 , (unsigned) G.last_bg_pid
7058 , (unsigned) G.last_exitcode
7061 IF_HUSH_LOOPS(, G.depth_of_loop)
7063 # undef NOMMU_HACK_FMT
7064 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7065 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7068 for (cur = G.top_var; cur; cur = cur->next) {
7069 if (!cur->flg_export || cur->flg_read_only)
7072 # if ENABLE_HUSH_FUNCTIONS
7073 for (funcp = G.top_func; funcp; funcp = funcp->next)
7079 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7080 *pp++ = (char *) G.argv0_for_re_execing;
7082 for (cur = G.top_var; cur; cur = cur->next) {
7083 if (strcmp(cur->varstr, hush_version_str) == 0)
7085 if (cur->flg_read_only) {
7086 *pp++ = (char *) "-R";
7087 *pp++ = cur->varstr;
7088 } else if (!cur->flg_export) {
7089 *pp++ = (char *) "-V";
7090 *pp++ = cur->varstr;
7093 # if ENABLE_HUSH_FUNCTIONS
7094 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7095 *pp++ = (char *) "-F";
7096 *pp++ = funcp->name;
7097 *pp++ = funcp->body_as_string;
7100 /* We can pass activated traps here. Say, -Tnn:trap_string
7102 * However, POSIX says that subshells reset signals with traps
7104 * I tested bash-3.2 and it not only does that with true subshells
7105 * of the form ( list ), but with any forked children shells.
7106 * I set trap "echo W" WINCH; and then tried:
7108 * { echo 1; sleep 20; echo 2; } &
7109 * while true; do echo 1; sleep 20; echo 2; break; done &
7110 * true | { echo 1; sleep 20; echo 2; } | cat
7112 * In all these cases sending SIGWINCH to the child shell
7113 * did not run the trap. If I add trap "echo V" WINCH;
7114 * _inside_ group (just before echo 1), it works.
7116 * I conclude it means we don't need to pass active traps here.
7118 *pp++ = (char *) "-c";
7121 while (*++builtin_argv)
7122 *pp++ = *builtin_argv;
7123 *pp++ = (char *) "";
7128 /* *pp = NULL; - is already there */
7132 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
7133 /* Don't propagate SIG_IGN to the child */
7134 if (SPECIAL_JOBSTOP_SIGS != 0)
7135 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7136 execve(bb_busybox_exec_path, argv, pp);
7137 /* Fallback. Useful for init=/bin/hush usage etc */
7138 if (argv[0][0] == '/')
7139 execve(argv[0], argv, pp);
7140 xfunc_error_retval = 127;
7141 bb_error_msg_and_die("can't re-execute the shell");
7143 #endif /* !BB_MMU */
7146 static int run_and_free_list(struct pipe *pi);
7148 /* Executing from string: eval, sh -c '...'
7149 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7150 * end_trigger controls how often we stop parsing
7151 * NUL: parse all, execute, return
7152 * ';': parse till ';' or newline, execute, repeat till EOF
7154 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7156 /* Why we need empty flag?
7157 * An obscure corner case "false; ``; echo $?":
7158 * empty command in `` should still set $? to 0.
7159 * But we can't just set $? to 0 at the start,
7160 * this breaks "false; echo `echo $?`" case.
7164 struct pipe *pipe_list;
7166 #if ENABLE_HUSH_INTERACTIVE
7167 if (end_trigger == ';') {
7168 G.promptmode = 0; /* PS1 */
7169 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7172 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
7173 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7174 /* If we are in "big" script
7175 * (not in `cmd` or something similar)...
7177 if (pipe_list == ERR_PTR && end_trigger == ';') {
7178 /* Discard cached input (rest of line) */
7179 int ch = inp->last_char;
7180 while (ch != EOF && ch != '\n') {
7181 //bb_error_msg("Discarded:'%c'", ch);
7186 /* This stream isn't empty */
7190 if (!pipe_list && empty)
7191 G.last_exitcode = 0;
7194 debug_print_tree(pipe_list, 0);
7195 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7196 run_and_free_list(pipe_list);
7198 if (G_flag_return_in_progress == 1)
7203 static void parse_and_run_string(const char *s)
7205 struct in_str input;
7206 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7208 setup_string_in_str(&input, s);
7209 parse_and_run_stream(&input, '\0');
7210 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
7213 static void parse_and_run_file(HFILE *fp)
7215 struct in_str input;
7216 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7218 IF_HUSH_LINENO_VAR(G.lineno = 1;)
7219 setup_file_in_str(&input, fp);
7220 parse_and_run_stream(&input, ';');
7221 IF_HUSH_LINENO_VAR(G.lineno = sv;)
7224 #if ENABLE_HUSH_TICK
7225 static int generate_stream_from_string(const char *s, pid_t *pid_p)
7230 char **to_free = NULL;
7234 pid = BB_MMU ? xfork() : xvfork();
7235 if (pid == 0) { /* child */
7236 disable_restore_tty_pgrp_on_exit();
7237 /* Process substitution is not considered to be usual
7238 * 'command execution'.
7239 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7246 close(channel[0]); /* NB: close _first_, then move fd! */
7247 xmove_fd(channel[1], 1);
7248 # if ENABLE_HUSH_TRAP
7249 /* Awful hack for `trap` or $(trap).
7251 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7252 * contains an example where "trap" is executed in a subshell:
7254 * save_traps=$(trap)
7256 * eval "$save_traps"
7258 * Standard does not say that "trap" in subshell shall print
7259 * parent shell's traps. It only says that its output
7260 * must have suitable form, but then, in the above example
7261 * (which is not supposed to be normative), it implies that.
7263 * bash (and probably other shell) does implement it
7264 * (traps are reset to defaults, but "trap" still shows them),
7265 * but as a result, "trap" logic is hopelessly messed up:
7268 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7269 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7270 * # true | trap <--- trap is in subshell - no output (ditto)
7271 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7272 * trap -- 'echo Ho' SIGWINCH
7273 * # echo `(trap)` <--- in subshell in subshell - output
7274 * trap -- 'echo Ho' SIGWINCH
7275 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7276 * trap -- 'echo Ho' SIGWINCH
7278 * The rules when to forget and when to not forget traps
7279 * get really complex and nonsensical.
7281 * Our solution: ONLY bare $(trap) or `trap` is special.
7283 s = skip_whitespace(s);
7284 if (is_prefixed_with(s, "trap")
7285 && skip_whitespace(s + 4)[0] == '\0'
7287 static const char *const argv[] = { NULL, NULL };
7288 builtin_trap((char**)argv);
7289 fflush_all(); /* important */
7294 /* Prevent it from trying to handle ctrl-z etc */
7295 IF_HUSH_JOB(G.run_list_level = 1;)
7296 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7297 reset_traps_to_defaults();
7298 IF_HUSH_MODE_X(G.x_mode_depth++;)
7299 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
7300 parse_and_run_string(s);
7301 _exit(G.last_exitcode);
7303 /* We re-execute after vfork on NOMMU. This makes this script safe:
7304 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7305 * huge=`cat BIG` # was blocking here forever
7308 re_execute_shell(&to_free,
7318 # if ENABLE_HUSH_FAST
7320 //bb_error_msg("[%d] fork in generate_stream_from_string:"
7321 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7322 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7324 enable_restore_tty_pgrp_on_exit();
7332 /* Return code is exit status of the process that is run. */
7333 static int process_command_subs(o_string *dest, const char *s)
7337 int status, ch, eol_cnt;
7339 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
7341 /* Now send results of command back into original context */
7343 while ((ch = getc(fp)) != EOF) {
7351 o_addchr(dest, '\n');
7354 o_addQchr(dest, ch);
7357 debug_printf("done reading from `cmd` pipe, closing it\n");
7359 /* We need to extract exitcode. Test case
7360 * "true; echo `sleep 1; false` $?"
7362 safe_waitpid(pid, &status, 0);
7363 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7364 return WEXITSTATUS(status);
7366 #endif /* ENABLE_HUSH_TICK */
7369 static void setup_heredoc(struct redir_struct *redir)
7371 struct fd_pair pair;
7374 /* the _body_ of heredoc (misleading field name) */
7375 const char *heredoc = redir->rd_filename;
7382 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
7383 expanded = encode_then_expand_string(heredoc);
7387 len = strlen(heredoc);
7389 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7391 xmove_fd(pair.rd, redir->rd_fd);
7393 /* Try writing without forking. Newer kernels have
7394 * dynamically growing pipes. Must use non-blocking write! */
7397 written = write(pair.wr, heredoc, len);
7408 ndelay_off(pair.wr);
7410 /* Okay, pipe buffer was not big enough */
7411 /* Note: we must not create a stray child (bastard? :)
7412 * for the unsuspecting parent process. Child creates a grandchild
7413 * and exits before parent execs the process which consumes heredoc
7414 * (that exec happens after we return from this function) */
7421 disable_restore_tty_pgrp_on_exit();
7422 pid = BB_MMU ? xfork() : xvfork();
7426 close(redir->rd_fd); /* read side of the pipe */
7428 full_write(pair.wr, heredoc, len); /* may loop or block */
7431 /* Delegate blocking writes to another process */
7432 xmove_fd(pair.wr, STDOUT_FILENO);
7433 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7437 #if ENABLE_HUSH_FAST
7439 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7441 enable_restore_tty_pgrp_on_exit();
7447 wait(NULL); /* wait till child has died */
7453 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7454 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7457 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7459 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7460 sq[i].orig_fd = orig;
7461 sq[i].moved_to = moved;
7462 sq[i+1].orig_fd = -1; /* end marker */
7466 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7472 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7473 /* If we collide with an already moved fd... */
7474 if (fd == sq[i].moved_to) {
7475 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
7476 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7477 if (sq[i].moved_to < 0) /* what? */
7481 if (fd == sq[i].orig_fd) {
7482 /* Example: echo Hello >/dev/null 1>&2 */
7483 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7488 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
7489 moved_to = dup_CLOEXEC(fd, avoid_fd);
7490 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7491 if (moved_to < 0 && errno != EBADF)
7493 return append_squirrel(sq, i, fd, moved_to);
7496 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7501 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7502 /* If we collide with an already moved fd... */
7503 if (fd == sq[i].orig_fd) {
7505 * "echo 3>FILE 3>&- 3>FILE"
7506 * "echo 3>&- 3>FILE"
7507 * No need for last redirect to insert
7508 * another "need to close 3" indicator.
7510 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7515 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7516 return append_squirrel(sq, i, fd, -1);
7519 /* fd: redirect wants this fd to be used (e.g. 3>file).
7520 * Move all conflicting internally used fds,
7521 * and remember them so that we can restore them later.
7523 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
7525 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7528 #if ENABLE_HUSH_INTERACTIVE
7529 if (fd == G.interactive_fd) {
7530 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
7531 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
7532 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7533 return 1; /* "we closed fd" */
7536 /* Are we called from setup_redirects(squirrel==NULL)
7537 * in redirect in a [v]forked child?
7540 /* No need to move script fds.
7541 * For NOMMU case, it's actively wrong: we'd change ->fd
7542 * fields in memory for the parent, but parent's fds
7543 * aren't be moved, it would use wrong fd!
7544 * Reproducer: "cmd 3>FILE" in script.
7545 * If we would call move_HFILEs_on_redirect(), child would:
7546 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7548 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7550 //bb_error_msg("sqp == NULL: [v]forked child");
7554 /* If this one of script's fds? */
7555 if (move_HFILEs_on_redirect(fd, avoid_fd))
7556 return 1; /* yes. "we closed fd" (actually moved it) */
7558 /* Are we called for "exec 3>FILE"? Came through
7559 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7560 * This case used to fail for this script:
7563 * ...100000 more lines...
7566 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7567 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7569 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7571 * write(1, "Ok\n", 3) = 3
7573 * write(1, "Ok\n", 3) = 3
7574 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7575 * ^^^^^^^^ oops, wrong fd!!!
7576 * With this case separate from sqp == NULL and *after* move_HFILEs,
7579 if (sqp == ERR_PTR) {
7580 /* Don't preserve redirected fds: exec is _meant_ to change these */
7581 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
7585 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7586 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7587 return 0; /* "we did not close fd" */
7590 static void restore_redirects(struct squirrel *sq)
7594 for (i = 0; sq[i].orig_fd >= 0; i++) {
7595 if (sq[i].moved_to >= 0) {
7596 /* We simply die on error */
7597 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7598 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7600 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7601 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7602 close(sq[i].orig_fd);
7608 /* If moved, G.interactive_fd stays on new fd, not restoring it */
7611 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
7612 static void close_saved_fds_and_FILE_fds(void)
7614 if (G_interactive_fd)
7615 close(G_interactive_fd);
7616 close_all_HFILE_list();
7620 static int internally_opened_fd(int fd, struct squirrel *sq)
7624 #if ENABLE_HUSH_INTERACTIVE
7625 if (fd == G.interactive_fd)
7628 /* If this one of script's fds? */
7629 if (fd_in_HFILEs(fd))
7632 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7633 if (fd == sq[i].moved_to)
7639 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
7640 * and stderr if they are redirected. */
7641 static int setup_redirects(struct command *prog, struct squirrel **sqp)
7643 struct redir_struct *redir;
7645 for (redir = prog->redirects; redir; redir = redir->next) {
7649 if (redir->rd_type == REDIRECT_HEREDOC2) {
7650 /* "rd_fd<<HERE" case */
7651 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
7652 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7654 debug_printf_redir("set heredoc '%s'\n",
7655 redir->rd_filename);
7656 setup_heredoc(redir);
7660 if (redir->rd_dup == REDIRFD_TO_FILE) {
7661 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
7665 if (redir->rd_filename == NULL) {
7667 * "cmd >" (no filename)
7668 * "cmd > <file" (2nd redirect starts too early)
7670 syntax_error("invalid redirect");
7673 mode = redir_table[redir->rd_type].mode;
7674 p = expand_string_to_string(redir->rd_filename,
7675 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
7676 newfd = open_or_warn(p, mode);
7679 /* Error message from open_or_warn can be lost
7680 * if stderr has been redirected, but bash
7681 * and ash both lose it as well
7682 * (though zsh doesn't!)
7686 if (newfd == redir->rd_fd && sqp) {
7687 /* open() gave us precisely the fd we wanted.
7688 * This means that this fd was not busy
7689 * (not opened to anywhere).
7690 * Remember to close it on restore:
7692 *sqp = add_squirrel_closed(*sqp, newfd);
7693 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7696 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7697 newfd = redir->rd_dup;
7700 if (newfd == redir->rd_fd)
7703 /* if "N>FILE": move newfd to redir->rd_fd */
7704 /* if "N>&M": dup newfd to redir->rd_fd */
7705 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7707 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7708 if (newfd == REDIRFD_CLOSE) {
7709 /* "N>&-" means "close me" */
7711 /* ^^^ optimization: saving may already
7712 * have closed it. If not... */
7713 close(redir->rd_fd);
7715 /* Sometimes we do another close on restore, getting EBADF.
7716 * Consider "echo 3>FILE 3>&-"
7717 * first redirect remembers "need to close 3",
7718 * and second redirect closes 3! Restore code then closes 3 again.
7721 /* if newfd is a script fd or saved fd, simulate EBADF */
7722 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
7724 //bb_perror_msg_and_die("can't duplicate file descriptor");
7725 newfd = -1; /* same effect as code above */
7727 xdup2(newfd, redir->rd_fd);
7728 if (redir->rd_dup == REDIRFD_TO_FILE)
7729 /* "rd_fd > FILE" */
7731 /* else: "rd_fd > rd_dup" */
7737 static char *find_in_path(const char *arg)
7740 const char *PATH = get_local_var_value("PATH");
7746 const char *end = strchrnul(PATH, ':');
7747 int sz = end - PATH; /* must be int! */
7751 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7753 /* We have xxx::yyyy in $PATH,
7754 * it means "use current dir" */
7757 if (access(ret, F_OK) == 0)
7770 static const struct built_in_command *find_builtin_helper(const char *name,
7771 const struct built_in_command *x,
7772 const struct built_in_command *end)
7775 if (strcmp(name, x->b_cmd) != 0) {
7779 debug_printf_exec("found builtin '%s'\n", name);
7784 static const struct built_in_command *find_builtin1(const char *name)
7786 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7788 static const struct built_in_command *find_builtin(const char *name)
7790 const struct built_in_command *x = find_builtin1(name);
7793 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7796 static void remove_nested_vars(void)
7798 struct variable *cur;
7799 struct variable **cur_pp;
7801 cur_pp = &G.top_var;
7802 while ((cur = *cur_pp) != NULL) {
7803 if (cur->var_nest_level <= G.var_nest_level) {
7804 cur_pp = &cur->next;
7808 if (cur->flg_export) {
7809 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7810 bb_unsetenv(cur->varstr);
7812 /* Remove from global list */
7813 *cur_pp = cur->next;
7815 if (!cur->max_len) {
7816 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7823 static void enter_var_nest_level(void)
7826 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7828 /* Try: f() { echo -n .; f; }; f
7829 * struct variable::var_nest_level is uint16_t,
7830 * thus limiting recursion to < 2^16.
7831 * In any case, with 8 Mbyte stack SEGV happens
7832 * not too long after 2^16 recursions anyway.
7834 if (G.var_nest_level > 0xff00)
7835 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7838 static void leave_var_nest_level(void)
7841 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7842 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7843 bb_error_msg_and_die("BUG: nesting underflow");
7845 remove_nested_vars();
7848 #if ENABLE_HUSH_FUNCTIONS
7849 static struct function **find_function_slot(const char *name)
7851 struct function *funcp;
7852 struct function **funcpp = &G.top_func;
7854 while ((funcp = *funcpp) != NULL) {
7855 if (strcmp(name, funcp->name) == 0) {
7856 debug_printf_exec("found function '%s'\n", name);
7859 funcpp = &funcp->next;
7864 static ALWAYS_INLINE const struct function *find_function(const char *name)
7866 const struct function *funcp = *find_function_slot(name);
7870 /* Note: takes ownership on name ptr */
7871 static struct function *new_function(char *name)
7873 struct function **funcpp = find_function_slot(name);
7874 struct function *funcp = *funcpp;
7876 if (funcp != NULL) {
7877 struct command *cmd = funcp->parent_cmd;
7878 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7880 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7882 /* Note: if !funcp->body, do not free body_as_string!
7883 * This is a special case of "-F name body" function:
7884 * body_as_string was not malloced! */
7886 free_pipe_list(funcp->body);
7888 free(funcp->body_as_string);
7892 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7893 cmd->argv[0] = funcp->name;
7894 cmd->group = funcp->body;
7896 cmd->group_as_string = funcp->body_as_string;
7900 debug_printf_exec("remembering new function '%s'\n", name);
7901 funcp = *funcpp = xzalloc(sizeof(*funcp));
7902 /*funcp->next = NULL;*/
7909 # if ENABLE_HUSH_UNSET
7910 static void unset_func(const char *name)
7912 struct function **funcpp = find_function_slot(name);
7913 struct function *funcp = *funcpp;
7915 if (funcp != NULL) {
7916 debug_printf_exec("freeing function '%s'\n", funcp->name);
7917 *funcpp = funcp->next;
7918 /* funcp is unlinked now, deleting it.
7919 * Note: if !funcp->body, the function was created by
7920 * "-F name body", do not free ->body_as_string
7921 * and ->name as they were not malloced. */
7923 free_pipe_list(funcp->body);
7926 free(funcp->body_as_string);
7935 #define exec_function(to_free, funcp, argv) \
7936 exec_function(funcp, argv)
7938 static void exec_function(char ***to_free,
7939 const struct function *funcp,
7940 char **argv) NORETURN;
7941 static void exec_function(char ***to_free,
7942 const struct function *funcp,
7948 argv[0] = G.global_argv[0];
7949 G.global_argv = argv;
7950 G.global_argc = n = 1 + string_array_len(argv + 1);
7952 // Example when we are here: "cmd | func"
7953 // func will run with saved-redirect fds open.
7954 // $ f() { echo /proc/self/fd/*; }
7956 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7957 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7960 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7961 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7962 // They are CLOEXEC so external programs won't see them, but
7963 // for "more correctness" we might want to close those extra fds here:
7964 //? close_saved_fds_and_FILE_fds();
7966 /* "we are in a function, ok to use return" */
7967 G_flag_return_in_progress = -1;
7968 enter_var_nest_level();
7969 IF_HUSH_LOCAL(G.func_nest_level++;)
7971 /* On MMU, funcp->body is always non-NULL */
7972 n = run_list(funcp->body);
7976 //? close_saved_fds_and_FILE_fds();
7978 //TODO: check whether "true | func_with_return" works
7980 re_execute_shell(to_free,
7981 funcp->body_as_string,
7988 static int run_function(const struct function *funcp, char **argv)
7994 save_and_replace_G_args(&sv, argv);
7996 /* "We are in function, ok to use return" */
7997 sv_flg = G_flag_return_in_progress;
7998 G_flag_return_in_progress = -1;
8000 /* Make "local" variables properly shadow previous ones */
8001 IF_HUSH_LOCAL(enter_var_nest_level();)
8002 IF_HUSH_LOCAL(G.func_nest_level++;)
8004 /* On MMU, funcp->body is always non-NULL */
8007 /* Function defined by -F */
8008 parse_and_run_string(funcp->body_as_string);
8009 rc = G.last_exitcode;
8013 rc = run_list(funcp->body);
8016 IF_HUSH_LOCAL(G.func_nest_level--;)
8017 IF_HUSH_LOCAL(leave_var_nest_level();)
8019 G_flag_return_in_progress = sv_flg;
8021 restore_G_args(&sv, argv);
8025 #endif /* ENABLE_HUSH_FUNCTIONS */
8029 #define exec_builtin(to_free, x, argv) \
8030 exec_builtin(x, argv)
8032 #define exec_builtin(to_free, x, argv) \
8033 exec_builtin(to_free, argv)
8035 static void exec_builtin(char ***to_free,
8036 const struct built_in_command *x,
8037 char **argv) NORETURN;
8038 static void exec_builtin(char ***to_free,
8039 const struct built_in_command *x,
8045 //? close_saved_fds_and_FILE_fds();
8046 rcode = x->b_function(argv);
8051 /* On NOMMU, we must never block!
8052 * Example: { sleep 99 | read line; } & echo Ok
8054 re_execute_shell(to_free,
8063 static void execvp_or_die(char **argv) NORETURN;
8064 static void execvp_or_die(char **argv)
8067 debug_printf_exec("execing '%s'\n", argv[0]);
8068 /* Don't propagate SIG_IGN to the child */
8069 if (SPECIAL_JOBSTOP_SIGS != 0)
8070 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8071 execvp(argv[0], argv);
8073 if (errno == EACCES) e = 126;
8074 if (errno == ENOENT) e = 127;
8075 bb_perror_msg("can't execute '%s'", argv[0]);
8079 #if ENABLE_HUSH_MODE_X
8080 static void x_mode_print_optionally_squoted(const char *str)
8087 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8088 /* test a char with: bash -c 'set -x; echo "CH"' */
8089 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8090 " " "\001\002\003\004\005\006\007"
8091 "\010\011\012\013\014\015\016\017"
8092 "\020\021\022\023\024\025\026\027"
8093 "\030\031\032\033\034\035\036\037"
8097 /* string has no special chars */
8104 /* print '....' up to EOL or first squote */
8105 len = (int)(strchrnul(cp, '\'') - cp);
8107 x_mode_addchr('\'');
8108 x_mode_addblock(cp, len);
8109 x_mode_addchr('\'');
8114 /* string contains squote(s), print them as \' */
8115 x_mode_addchr('\\');
8116 x_mode_addchr('\'');
8120 static void dump_cmd_in_x_mode(char **argv)
8122 if (G_x_mode && argv) {
8125 /* "+[+++...][ cmd...]\n\0" */
8130 if (argv[n][0] == '\0') {
8131 x_mode_addchr('\'');
8132 x_mode_addchr('\'');
8134 x_mode_print_optionally_squoted(argv[n]);
8142 # define dump_cmd_in_x_mode(argv) ((void)0)
8145 #if ENABLE_HUSH_COMMAND
8146 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8155 char *path = getenv("PATH");
8156 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
8158 _exit(1); /* PROG was not found */
8160 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8162 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
8168 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
8172 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8173 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8174 #define pseudo_exec(nommu_save, command, argv_expanded) \
8175 pseudo_exec(command, argv_expanded)
8178 /* Called after [v]fork() in run_pipe, or from builtin_exec.
8180 * Don't exit() here. If you don't exec, use _exit instead.
8181 * The at_exit handlers apparently confuse the calling process,
8182 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
8184 static void pseudo_exec_argv(nommu_save_t *nommu_save,
8185 char **argv, int assignment_cnt,
8186 char **argv_expanded) NORETURN;
8187 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8188 char **argv, int assignment_cnt,
8189 char **argv_expanded)
8191 const struct built_in_command *x;
8192 struct variable **sv_shadowed;
8194 IF_HUSH_COMMAND(char opt_vV = 0;)
8195 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8197 new_env = expand_assignments(argv, assignment_cnt);
8198 dump_cmd_in_x_mode(new_env);
8200 if (!argv[assignment_cnt]) {
8201 /* Case when we are here: ... | var=val | ...
8202 * (note that we do not exit early, i.e., do not optimize out
8203 * expand_assignments(): think about ... | var=`sleep 1` | ...
8205 free_strings(new_env);
8206 _exit(EXIT_SUCCESS);
8209 sv_shadowed = G.shadowed_vars_pp;
8211 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
8213 G.shadowed_vars_pp = &nommu_save->old_vars;
8216 set_vars_and_save_old(new_env);
8217 G.shadowed_vars_pp = sv_shadowed;
8219 if (argv_expanded) {
8220 argv = argv_expanded;
8222 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8224 nommu_save->argv = argv;
8227 dump_cmd_in_x_mode(argv);
8229 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8230 if (strchr(argv[0], '/') != NULL)
8234 #if ENABLE_HUSH_FUNCTIONS
8235 /* Check if the command matches any functions (this goes before bltins) */
8236 funcp = find_function(argv[0]);
8238 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
8241 #if ENABLE_HUSH_COMMAND
8242 /* "command BAR": run BAR without looking it up among functions
8243 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8244 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8246 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8251 if (p[0] != '-' || !p[1])
8252 continue; /* bash allows "command command command [-OPT] BAR" */
8260 if (p[0] != '-' || !p[1])
8262 continue; /* next arg is also -opts, process it too */
8268 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8273 # if ENABLE_HUSH_FUNCTIONS
8274 if (opt_vV && find_function(argv[0]))
8275 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8279 /* Check if the command matches any of the builtins.
8280 * Depending on context, this might be redundant. But it's
8281 * easier to waste a few CPU cycles than it is to figure out
8282 * if this is one of those cases.
8284 /* Why "BB_MMU ? :" difference in logic? -
8285 * On NOMMU, it is more expensive to re-execute shell
8286 * just in order to run echo or test builtin.
8287 * It's better to skip it here and run corresponding
8288 * non-builtin later. */
8289 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8291 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8292 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
8295 #if ENABLE_FEATURE_SH_STANDALONE
8296 /* Check if the command matches any busybox applets */
8298 int a = find_applet_by_name(argv[0]);
8300 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
8301 # if BB_MMU /* see above why on NOMMU it is not allowed */
8302 if (APPLET_IS_NOEXEC(a)) {
8303 /* Do not leak open fds from opened script files etc.
8304 * Testcase: interactive "ls -l /proc/self/fd"
8305 * should not show tty fd open.
8307 close_saved_fds_and_FILE_fds();
8308 //FIXME: should also close saved redir fds
8309 //This casuses test failures in
8310 //redir_children_should_not_see_saved_fd_2.tests
8311 //redir_children_should_not_see_saved_fd_3.tests
8312 //if you replace "busybox find" with just "find" in them
8313 /* Without this, "rm -i FILE" can't be ^C'ed: */
8314 switch_off_special_sigs(G.special_sig_mask);
8315 debug_printf_exec("running applet '%s'\n", argv[0]);
8316 run_noexec_applet_and_exit(a, argv[0], argv);
8319 /* Re-exec ourselves */
8320 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
8321 /* Don't propagate SIG_IGN to the child */
8322 if (SPECIAL_JOBSTOP_SIGS != 0)
8323 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8324 execv(bb_busybox_exec_path, argv);
8325 /* If they called chroot or otherwise made the binary no longer
8326 * executable, fall through */
8331 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8334 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
8335 execvp_or_die(argv);
8338 /* Called after [v]fork() in run_pipe
8340 static void pseudo_exec(nommu_save_t *nommu_save,
8341 struct command *command,
8342 char **argv_expanded) NORETURN;
8343 static void pseudo_exec(nommu_save_t *nommu_save,
8344 struct command *command,
8345 char **argv_expanded)
8347 #if ENABLE_HUSH_FUNCTIONS
8348 if (command->cmd_type == CMD_FUNCDEF) {
8349 /* Ignore funcdefs in pipes:
8350 * true | f() { cmd }
8356 if (command->argv) {
8357 pseudo_exec_argv(nommu_save, command->argv,
8358 command->assignment_cnt, argv_expanded);
8361 if (command->group) {
8362 /* Cases when we are here:
8365 * ... | ( list ) | ...
8366 * ... | { list } | ...
8370 debug_printf_exec("pseudo_exec: run_list\n");
8371 reset_traps_to_defaults();
8372 rcode = run_list(command->group);
8373 /* OK to leak memory by not calling free_pipe_list,
8374 * since this process is about to exit */
8377 re_execute_shell(&nommu_save->argv_from_re_execing,
8378 command->group_as_string,
8385 /* Case when we are here: ... | >file */
8386 debug_printf_exec("pseudo_exec'ed null command\n");
8387 _exit(EXIT_SUCCESS);
8391 static const char *get_cmdtext(struct pipe *pi)
8397 /* This is subtle. ->cmdtext is created only on first backgrounding.
8398 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8399 * On subsequent bg argv is trashed, but we won't use it */
8403 argv = pi->cmds[0].argv;
8405 pi->cmdtext = xzalloc(1);
8410 len += strlen(*argv) + 1;
8414 argv = pi->cmds[0].argv;
8416 p = stpcpy(p, *argv);
8423 static void remove_job_from_table(struct pipe *pi)
8425 struct pipe *prev_pipe;
8427 if (pi == G.job_list) {
8428 G.job_list = pi->next;
8430 prev_pipe = G.job_list;
8431 while (prev_pipe->next != pi)
8432 prev_pipe = prev_pipe->next;
8433 prev_pipe->next = pi->next;
8437 G.last_jobid = G.job_list->jobid;
8440 static void delete_finished_job(struct pipe *pi)
8442 remove_job_from_table(pi);
8446 static void clean_up_last_dead_job(void)
8448 if (G.job_list && !G.job_list->alive_cmds)
8449 delete_finished_job(G.job_list);
8452 static void insert_job_into_table(struct pipe *pi)
8454 struct pipe *job, **jobp;
8457 clean_up_last_dead_job();
8459 /* Find the end of the list, and find next job ID to use */
8462 while ((job = *jobp) != NULL) {
8469 /* Create a new job struct at the end */
8470 job = *jobp = xmemdup(pi, sizeof(*pi));
8472 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8473 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8474 for (i = 0; i < pi->num_cmds; i++) {
8475 job->cmds[i].pid = pi->cmds[i].pid;
8476 /* all other fields are not used and stay zero */
8478 job->cmdtext = xstrdup(get_cmdtext(pi));
8480 if (G_interactive_fd)
8481 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
8482 G.last_jobid = job->jobid;
8486 static int job_exited_or_stopped(struct pipe *pi)
8490 if (pi->alive_cmds != pi->stopped_cmds)
8493 /* All processes in fg pipe have exited or stopped */
8497 rcode = pi->cmds[i].cmd_exitcode;
8498 /* usually last process gives overall exitstatus,
8499 * but with "set -o pipefail", last *failed* process does */
8500 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8503 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8507 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
8514 dead = WIFEXITED(status) || WIFSIGNALED(status);
8517 if (WIFSTOPPED(status))
8518 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8519 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8520 if (WIFSIGNALED(status))
8521 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8522 childpid, WTERMSIG(status), WEXITSTATUS(status));
8523 if (WIFEXITED(status))
8524 debug_printf_jobs("pid %d exited, exitcode %d\n",
8525 childpid, WEXITSTATUS(status));
8527 /* Were we asked to wait for a fg pipe? */
8529 i = fg_pipe->num_cmds;
8534 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8535 if (fg_pipe->cmds[i].pid != childpid)
8539 fg_pipe->cmds[i].pid = 0;
8540 fg_pipe->alive_cmds--;
8541 ex = WEXITSTATUS(status);
8542 /* bash prints killer signal's name for *last*
8543 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8544 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8546 if (WIFSIGNALED(status)) {
8547 int sig = WTERMSIG(status);
8548 if (i == fg_pipe->num_cmds-1)
8549 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8550 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8551 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8552 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8553 * Maybe we need to use sig | 128? */
8556 fg_pipe->cmds[i].cmd_exitcode = ex;
8558 fg_pipe->stopped_cmds++;
8560 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8561 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
8562 rcode = job_exited_or_stopped(fg_pipe);
8564 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
8565 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8566 * and "killall -STOP cat" */
8567 if (G_interactive_fd) {
8569 if (fg_pipe->alive_cmds != 0)
8570 insert_job_into_table(fg_pipe);
8574 if (fg_pipe->alive_cmds == 0)
8577 /* There are still running processes in the fg_pipe */
8580 /* It wasn't in fg_pipe, look for process in bg pipes */
8584 /* We were asked to wait for bg or orphaned children */
8585 /* No need to remember exitcode in this case */
8586 for (pi = G.job_list; pi; pi = pi->next) {
8587 for (i = 0; i < pi->num_cmds; i++) {
8588 if (pi->cmds[i].pid == childpid)
8589 goto found_pi_and_prognum;
8592 /* Happens when shell is used as init process (init=/bin/sh) */
8593 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8594 return -1; /* this wasn't a process from fg_pipe */
8596 found_pi_and_prognum:
8599 int rcode = WEXITSTATUS(status);
8600 if (WIFSIGNALED(status))
8601 rcode = 128 + WTERMSIG(status);
8602 pi->cmds[i].cmd_exitcode = rcode;
8603 if (G.last_bg_pid == pi->cmds[i].pid)
8604 G.last_bg_pid_exitcode = rcode;
8605 pi->cmds[i].pid = 0;
8607 if (!pi->alive_cmds) {
8608 if (G_interactive_fd) {
8609 printf(JOB_STATUS_FORMAT, pi->jobid,
8610 "Done", pi->cmdtext);
8611 delete_finished_job(pi);
8614 * bash deletes finished jobs from job table only in interactive mode,
8615 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8616 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8617 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8618 * We only retain one "dead" job, if it's the single job on the list.
8619 * This covers most of real-world scenarios where this is useful.
8621 if (pi != G.job_list)
8622 delete_finished_job(pi);
8630 return -1; /* this wasn't a process from fg_pipe */
8633 /* Check to see if any processes have exited -- if they have,
8634 * figure out why and see if a job has completed.
8636 * If non-NULL fg_pipe: wait for its completion or stop.
8637 * Return its exitcode or zero if stopped.
8639 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8640 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8641 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8642 * or 0 if no children changed status.
8644 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8645 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8646 * or 0 if no children changed status.
8648 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8654 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8656 attributes = WUNTRACED;
8657 if (fg_pipe == NULL)
8658 attributes |= WNOHANG;
8661 #if ENABLE_HUSH_FAST
8662 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8663 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8664 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8665 /* There was neither fork nor SIGCHLD since last waitpid */
8666 /* Avoid doing waitpid syscall if possible */
8667 if (!G.we_have_children) {
8671 if (fg_pipe == NULL) { /* is WNOHANG set? */
8672 /* We have children, but they did not exit
8673 * or stop yet (we saw no SIGCHLD) */
8676 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8680 /* Do we do this right?
8681 * bash-3.00# sleep 20 | false
8683 * [3]+ Stopped sleep 20 | false
8684 * bash-3.00# echo $?
8685 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8686 * [hush 1.14.0: yes we do it right]
8690 #if ENABLE_HUSH_FAST
8692 i = G.count_SIGCHLD;
8694 childpid = waitpid(-1, &status, attributes);
8695 if (childpid <= 0) {
8696 if (childpid && errno != ECHILD)
8697 bb_perror_msg("waitpid");
8698 #if ENABLE_HUSH_FAST
8699 else { /* Until next SIGCHLD, waitpid's are useless */
8700 G.we_have_children = (childpid == 0);
8701 G.handled_SIGCHLD = i;
8702 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8705 /* ECHILD (no children), or 0 (no change in children status) */
8709 rcode = process_wait_result(fg_pipe, childpid, status);
8711 /* fg_pipe exited or stopped */
8714 if (childpid == waitfor_pid) {
8715 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
8716 rcode = WEXITSTATUS(status);
8717 if (WIFSIGNALED(status))
8718 rcode = 128 + WTERMSIG(status);
8719 if (WIFSTOPPED(status))
8720 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8721 rcode = 128 + WSTOPSIG(status);
8723 break; /* "wait PID" called us, give it exitcode+1 */
8725 /* This wasn't one of our processes, or */
8726 /* fg_pipe still has running processes, do waitpid again */
8727 } /* while (waitpid succeeds)... */
8733 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
8736 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
8737 if (G_saved_tty_pgrp) {
8738 /* Job finished, move the shell to the foreground */
8739 p = getpgrp(); /* our process group id */
8740 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8741 tcsetpgrp(G_interactive_fd, p);
8747 /* Start all the jobs, but don't wait for anything to finish.
8750 * Return code is normally -1, when the caller has to wait for children
8751 * to finish to determine the exit status of the pipe. If the pipe
8752 * is a simple builtin command, however, the action is done by the
8753 * time run_pipe returns, and the exit code is provided as the
8756 * Returns -1 only if started some children. IOW: we have to
8757 * mask out retvals of builtins etc with 0xff!
8759 * The only case when we do not need to [v]fork is when the pipe
8760 * is single, non-backgrounded, non-subshell command. Examples:
8761 * cmd ; ... { list } ; ...
8762 * cmd && ... { list } && ...
8763 * cmd || ... { list } || ...
8764 * If it is, then we can run cmd as a builtin, NOFORK,
8765 * or (if SH_STANDALONE) an applet, and we can run the { list }
8766 * with run_list. If it isn't one of these, we fork and exec cmd.
8768 * Cases when we must fork:
8769 * non-single: cmd | cmd
8770 * backgrounded: cmd & { list } &
8771 * subshell: ( list ) [&]
8773 #if !ENABLE_HUSH_MODE_X
8774 #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8775 redirect_and_varexp_helper(command, sqp)
8777 static int redirect_and_varexp_helper(
8778 struct command *command,
8779 struct squirrel **sqp,
8780 char **argv_expanded)
8782 /* Assignments occur before redirects. Try:
8783 * a=`sleep 1` sleep 2 3>/qwe/rty
8786 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8787 dump_cmd_in_x_mode(new_env);
8788 dump_cmd_in_x_mode(argv_expanded);
8789 /* this takes ownership of new_env[i] elements, and frees new_env: */
8790 set_vars_and_save_old(new_env);
8792 return setup_redirects(command, sqp);
8794 static NOINLINE int run_pipe(struct pipe *pi)
8796 static const char *const null_ptr = NULL;
8800 struct command *command;
8801 char **argv_expanded;
8803 struct squirrel *squirrel = NULL;
8806 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8809 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8810 * Result should be 3 lines: q w e, qwe, q w e
8812 if (G.ifs_whitespace != G.ifs)
8813 free(G.ifs_whitespace);
8814 G.ifs = get_local_var_value("IFS");
8817 G.ifs_whitespace = (char*)G.ifs;
8818 p = skip_whitespace(G.ifs);
8820 /* Not all $IFS is whitespace */
8822 int len = p - G.ifs;
8823 p = skip_non_whitespace(p);
8824 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8825 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8835 G.ifs_whitespace = (char*)G.ifs;
8838 IF_HUSH_JOB(pi->pgrp = -1;)
8839 pi->stopped_cmds = 0;
8840 command = &pi->cmds[0];
8841 argv_expanded = NULL;
8843 if (pi->num_cmds != 1
8844 || pi->followup == PIPE_BG
8845 || command->cmd_type == CMD_SUBSHELL
8852 debug_printf_exec(": group:%p argv:'%s'\n",
8853 command->group, command->argv ? command->argv[0] : "NONE");
8855 if (command->group) {
8856 #if ENABLE_HUSH_FUNCTIONS
8857 if (command->cmd_type == CMD_FUNCDEF) {
8858 /* "executing" func () { list } */
8859 struct function *funcp;
8861 funcp = new_function(command->argv[0]);
8862 /* funcp->name is already set to argv[0] */
8863 funcp->body = command->group;
8865 funcp->body_as_string = command->group_as_string;
8866 command->group_as_string = NULL;
8868 command->group = NULL;
8869 command->argv[0] = NULL;
8870 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8871 funcp->parent_cmd = command;
8872 command->child_func = funcp;
8874 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8876 return EXIT_SUCCESS;
8880 debug_printf_exec("non-subshell group\n");
8881 rcode = 1; /* exitcode if redir failed */
8882 if (setup_redirects(command, &squirrel) == 0) {
8883 debug_printf_exec(": run_list\n");
8884 //FIXME: we need to pass squirrel down into run_list()
8885 //for SH_STANDALONE case, or else this construct:
8886 // { find /proc/self/fd; true; } >FILE; cmd2
8887 //has no way of closing saved fd#1 for "find",
8888 //and in SH_STANDALONE mode, "find" is not execed,
8889 //therefore CLOEXEC on saved fd does not help.
8890 rcode = run_list(command->group) & 0xff;
8892 restore_redirects(squirrel);
8893 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8895 debug_printf_exec("run_pipe: return %d\n", rcode);
8899 argv = command->argv ? command->argv : (char **) &null_ptr;
8901 const struct built_in_command *x;
8902 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8903 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
8904 struct variable **sv_shadowed;
8905 struct variable *old_vars;
8907 #if ENABLE_HUSH_LINENO_VAR
8909 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8912 if (argv[command->assignment_cnt] == NULL) {
8913 /* Assignments, but no command.
8914 * Ensure redirects take effect (that is, create files).
8918 G.expand_exitcode = 0;
8920 rcode = setup_redirects(command, &squirrel);
8921 restore_redirects(squirrel);
8923 /* Set shell variables */
8925 while (i < command->assignment_cnt) {
8926 char *p = expand_string_to_string(argv[i],
8927 EXP_FLAG_ESC_GLOB_CHARS,
8930 #if ENABLE_HUSH_MODE_X
8936 eq = strchrnul(p, '=');
8938 x_mode_addblock(p, (eq - p));
8939 x_mode_print_optionally_squoted(eq);
8943 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
8944 if (set_local_var(p, /*flag:*/ 0)) {
8945 /* assignment to readonly var / putenv error? */
8950 /* Redirect error sets $? to 1. Otherwise,
8951 * if evaluating assignment value set $?, retain it.
8953 * false; q=`exit 2`; echo $? - should print 2
8954 * false; x=1; echo $? - should print 0
8955 * Because of the 2nd case, we can't just use G.last_exitcode.
8958 rcode = G.expand_exitcode;
8959 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8961 debug_printf_exec("run_pipe: return %d\n", rcode);
8965 /* Expand the rest into (possibly) many strings each */
8966 #if defined(CMD_SINGLEWORD_NOGLOB)
8967 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
8968 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8971 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8973 /* If someone gives us an empty string: `cmd with empty output` */
8974 if (!argv_expanded[0]) {
8975 free(argv_expanded);
8976 /* `false` still has to set exitcode 1 */
8977 G.expand_exitcode = G.last_exitcode;
8978 goto only_assignments;
8982 sv_shadowed = G.shadowed_vars_pp;
8984 /* Check if argv[0] matches any functions (this goes before bltins) */
8985 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8986 IF_HUSH_FUNCTIONS(x = NULL;)
8987 IF_HUSH_FUNCTIONS(if (!funcp))
8988 x = find_builtin(argv_expanded[0]);
8990 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8991 debug_printf("exec with redirects only\n");
8993 * Variable assignments are executed, but then "forgotten":
8994 * a=`sleep 1;echo A` exec 3>&-; echo $a
8995 * sleeps, but prints nothing.
8997 enter_var_nest_level();
8998 G.shadowed_vars_pp = &old_vars;
8999 rcode = redirect_and_varexp_helper(command,
9000 /*squirrel:*/ ERR_PTR,
9003 G.shadowed_vars_pp = sv_shadowed;
9004 /* rcode=1 can be if redir file can't be opened */
9006 goto clean_up_and_ret1;
9009 /* Bump var nesting, or this will leak exported $a:
9010 * a=b true; env | grep ^a=
9012 enter_var_nest_level();
9013 /* Collect all variables "shadowed" by helper
9014 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9015 * into old_vars list:
9017 G.shadowed_vars_pp = &old_vars;
9018 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9021 /* Do not collect *to old_vars list* vars shadowed
9022 * by e.g. "local VAR" builtin (collect them
9023 * in the previously nested list instead):
9024 * don't want them to be restored immediately
9025 * after "local" completes.
9027 G.shadowed_vars_pp = sv_shadowed;
9029 debug_printf_exec(": builtin '%s' '%s'...\n",
9030 x->b_cmd, argv_expanded[1]);
9032 rcode = x->b_function(argv_expanded) & 0xff;
9035 #if ENABLE_HUSH_FUNCTIONS
9037 debug_printf_exec(": function '%s' '%s'...\n",
9038 funcp->name, argv_expanded[1]);
9039 rcode = run_function(funcp, argv_expanded) & 0xff;
9041 * But do collect *to old_vars list* vars shadowed
9042 * within function execution. To that end, restore
9043 * this pointer _after_ function run:
9045 G.shadowed_vars_pp = sv_shadowed;
9050 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
9051 int n = find_applet_by_name(argv_expanded[0]);
9052 if (n < 0 || !APPLET_IS_NOFORK(n))
9055 enter_var_nest_level();
9056 /* Collect all variables "shadowed" by helper into old_vars list */
9057 G.shadowed_vars_pp = &old_vars;
9058 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9059 G.shadowed_vars_pp = sv_shadowed;
9062 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9063 argv_expanded[0], argv_expanded[1]);
9065 * Note: signals (^C) can't interrupt here.
9066 * We remember them and they will be acted upon
9067 * after applet returns.
9068 * This makes applets which can run for a long time
9069 * and/or wait for user input ineligible for NOFORK:
9070 * for example, "yes" or "rm" (rm -i waits for input).
9072 rcode = run_nofork_applet(n, argv_expanded);
9077 restore_redirects(squirrel);
9079 leave_var_nest_level();
9083 * Try "usleep 99999999" + ^C + "echo $?"
9084 * with FEATURE_SH_NOFORK=y.
9087 /* It was builtin or nofork.
9088 * if this would be a real fork/execed program,
9089 * it should have died if a fatal sig was received.
9090 * But OTOH, there was no separate process,
9091 * the sig was sent to _shell_, not to non-existing
9093 * Let's just handle ^C only, this one is obvious:
9094 * we aren't ok with exitcode 0 when ^C was pressed
9095 * during builtin/nofork.
9097 if (sigismember(&G.pending_set, SIGINT))
9098 rcode = 128 + SIGINT;
9100 free(argv_expanded);
9101 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9103 debug_printf_exec("run_pipe return %d\n", rcode);
9108 /* NB: argv_expanded may already be created, and that
9109 * might include `cmd` runs! Do not rerun it! We *must*
9110 * use argv_expanded if it's non-NULL */
9112 /* Going to fork a child per each pipe member */
9117 while (cmd_no < pi->num_cmds) {
9118 struct fd_pair pipefds;
9120 int sv_var_nest_level = G.var_nest_level;
9121 volatile nommu_save_t nommu_save;
9122 nommu_save.old_vars = NULL;
9123 nommu_save.argv = NULL;
9124 nommu_save.argv_from_re_execing = NULL;
9126 command = &pi->cmds[cmd_no];
9128 if (command->argv) {
9129 debug_printf_exec(": pipe member '%s' '%s'...\n",
9130 command->argv[0], command->argv[1]);
9132 debug_printf_exec(": pipe member with no argv\n");
9135 /* pipes are inserted between pairs of commands */
9138 if (cmd_no < pi->num_cmds)
9139 xpiped_pair(pipefds);
9141 #if ENABLE_HUSH_LINENO_VAR
9143 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9146 command->pid = BB_MMU ? fork() : vfork();
9147 if (!command->pid) { /* child */
9149 disable_restore_tty_pgrp_on_exit();
9150 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9152 /* Every child adds itself to new process group
9153 * with pgid == pid_of_first_child_in_pipe */
9154 if (G.run_list_level == 1 && G_interactive_fd) {
9157 if (pgrp < 0) /* true for 1st process only */
9159 if (setpgid(0, pgrp) == 0
9160 && pi->followup != PIPE_BG
9161 && G_saved_tty_pgrp /* we have ctty */
9163 /* We do it in *every* child, not just first,
9165 tcsetpgrp(G_interactive_fd, pgrp);
9169 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9170 /* 1st cmd in backgrounded pipe
9171 * should have its stdin /dev/null'ed */
9173 if (open(bb_dev_null, O_RDONLY))
9174 xopen("/", O_RDONLY);
9176 xmove_fd(next_infd, 0);
9178 xmove_fd(pipefds.wr, 1);
9181 /* Like bash, explicit redirects override pipes,
9182 * and the pipe fd (fd#1) is available for dup'ing:
9183 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9184 * of cmd1 goes into pipe.
9186 if (setup_redirects(command, NULL)) {
9187 /* Happens when redir file can't be opened:
9188 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9190 * hush: can't open '/qwe/rty': No such file or directory
9192 * (echo BAR is not executed, it hits _exit(1) below)
9197 /* Stores to nommu_save list of env vars putenv'ed
9198 * (NOMMU, on MMU we don't need that) */
9199 /* cast away volatility... */
9200 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9201 /* pseudo_exec() does not return */
9204 /* parent or error */
9205 #if ENABLE_HUSH_FAST
9207 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9209 enable_restore_tty_pgrp_on_exit();
9211 /* Clean up after vforked child */
9212 free(nommu_save.argv);
9213 free(nommu_save.argv_from_re_execing);
9214 G.var_nest_level = sv_var_nest_level;
9215 remove_nested_vars();
9216 add_vars(nommu_save.old_vars);
9218 free(argv_expanded);
9219 argv_expanded = NULL;
9220 if (command->pid < 0) { /* [v]fork failed */
9221 /* Clearly indicate, was it fork or vfork */
9222 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9226 /* Second and next children need to know pid of first one */
9228 pi->pgrp = command->pid;
9234 if (cmd_no < pi->num_cmds)
9236 /* Pass read (output) pipe end to next iteration */
9237 next_infd = pipefds.rd;
9240 if (!pi->alive_cmds) {
9242 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9247 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9251 /* NB: called by pseudo_exec, and therefore must not modify any
9252 * global data until exec/_exit (we can be a child after vfork!) */
9253 static int run_list(struct pipe *pi)
9255 #if ENABLE_HUSH_CASE
9256 char *case_word = NULL;
9258 #if ENABLE_HUSH_LOOPS
9259 struct pipe *loop_top = NULL;
9260 char **for_lcur = NULL;
9261 char **for_list = NULL;
9263 smallint last_followup;
9265 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9266 smalluint cond_code = 0;
9268 enum { cond_code = 0 };
9271 smallint rword; /* RES_foo */
9272 smallint last_rword; /* ditto */
9275 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9278 #if ENABLE_HUSH_LOOPS
9279 /* Check syntax for "for" */
9282 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9283 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9285 /* current word is FOR or IN (BOLD in comments below) */
9286 if (cpipe->next == NULL) {
9287 syntax_error("malformed for");
9289 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9292 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9293 if (cpipe->next->res_word == RES_DO)
9295 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9296 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9297 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9299 syntax_error("malformed for");
9301 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9308 /* Past this point, all code paths should jump to ret: label
9309 * in order to return, no direct "return" statements please.
9310 * This helps to ensure that no memory is leaked. */
9318 last_rword = RES_XXXX;
9320 last_followup = PIPE_SEQ;
9321 rcode = G.last_exitcode;
9323 /* Go through list of pipes, (maybe) executing them. */
9324 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
9326 int sv_errexit_depth;
9330 if (G_flag_return_in_progress == 1)
9333 IF_HAS_KEYWORDS(rword = pi->res_word;)
9334 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9335 rword, cond_code, last_rword);
9337 sv_errexit_depth = G.errexit_depth;
9340 rword == RES_IF || rword == RES_ELIF ||
9342 pi->followup != PIPE_SEQ
9346 #if ENABLE_HUSH_LOOPS
9347 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9348 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9350 /* start of a loop: remember where loop starts */
9355 /* Still in the same "if...", "then..." or "do..." branch? */
9356 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9357 if ((rcode == 0 && last_followup == PIPE_OR)
9358 || (rcode != 0 && last_followup == PIPE_AND)
9360 /* It is "<true> || CMD" or "<false> && CMD"
9361 * and we should not execute CMD */
9362 debug_printf_exec("skipped cmd because of || or &&\n");
9363 last_followup = pi->followup;
9364 goto dont_check_jobs_but_continue;
9367 last_followup = pi->followup;
9368 IF_HAS_KEYWORDS(last_rword = rword;)
9371 if (rword == RES_THEN) {
9372 /* if false; then ... fi has exitcode 0! */
9373 G.last_exitcode = rcode = EXIT_SUCCESS;
9374 /* "if <false> THEN cmd": skip cmd */
9378 if (rword == RES_ELSE || rword == RES_ELIF) {
9379 /* "if <true> then ... ELSE/ELIF cmd":
9380 * skip cmd and all following ones */
9385 #if ENABLE_HUSH_LOOPS
9386 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9388 /* first loop through for */
9390 static const char encoded_dollar_at[] ALIGN1 = {
9391 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9392 }; /* encoded representation of "$@" */
9393 static const char *const encoded_dollar_at_argv[] = {
9394 encoded_dollar_at, NULL
9395 }; /* argv list with one element: "$@" */
9398 G.last_exitcode = rcode = EXIT_SUCCESS;
9399 vals = (char**)encoded_dollar_at_argv;
9400 if (pi->next->res_word == RES_IN) {
9401 /* if no variable values after "in" we skip "for" */
9402 if (!pi->next->cmds[0].argv) {
9403 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9406 vals = pi->next->cmds[0].argv;
9407 } /* else: "for var; do..." -> assume "$@" list */
9408 /* create list of variable values */
9409 debug_print_strings("for_list made from", vals);
9410 for_list = expand_strvec_to_strvec(vals);
9411 for_lcur = for_list;
9412 debug_print_strings("for_list", for_list);
9415 /* "for" loop is over, clean up */
9421 /* Insert next value from for_lcur */
9422 /* note: *for_lcur already has quotes removed, $var expanded, etc */
9423 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
9426 if (rword == RES_IN) {
9427 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9429 if (rword == RES_DONE) {
9430 continue; /* "done" has no cmds too */
9433 #if ENABLE_HUSH_CASE
9434 if (rword == RES_CASE) {
9435 debug_printf_exec("CASE cond_code:%d\n", cond_code);
9436 case_word = expand_string_to_string(pi->cmds->argv[0],
9437 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
9438 debug_printf_exec("CASE word1:'%s'\n", case_word);
9439 //unbackslash(case_word);
9440 //debug_printf_exec("CASE word2:'%s'\n", case_word);
9443 if (rword == RES_MATCH) {
9446 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
9447 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9449 /* all prev words didn't match, does this one match? */
9450 argv = pi->cmds->argv;
9453 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9454 pattern = expand_string_to_string(*argv,
9455 EXP_FLAG_ESC_GLOB_CHARS,
9458 /* TODO: which FNM_xxx flags to use? */
9459 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
9460 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9461 pattern, case_word, cond_code);
9463 if (cond_code == 0) {
9464 /* match! we will execute this branch */
9466 case_word = NULL; /* make future "word)" stop */
9473 if (rword == RES_CASE_BODY) { /* inside of a case branch */
9474 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
9476 continue; /* not matched yet, skip this pipe */
9478 if (rword == RES_ESAC) {
9479 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9481 /* "case" did not match anything: still set $? (to 0) */
9482 G.last_exitcode = rcode = EXIT_SUCCESS;
9486 /* Just pressing <enter> in shell should check for jobs.
9487 * OTOH, in non-interactive shell this is useless
9488 * and only leads to extra job checks */
9489 if (pi->num_cmds == 0) {
9490 if (G_interactive_fd)
9491 goto check_jobs_and_continue;
9495 /* After analyzing all keywords and conditions, we decided
9496 * to execute this pipe. NB: have to do checkjobs(NULL)
9497 * after run_pipe to collect any background children,
9498 * even if list execution is to be stopped. */
9499 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
9500 #if ENABLE_HUSH_LOOPS
9501 G.flag_break_continue = 0;
9503 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9505 /* We ran a builtin, function, or group.
9506 * rcode is already known
9507 * and we don't need to wait for anything. */
9508 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9509 G.last_exitcode = rcode;
9510 check_and_run_traps();
9511 #if ENABLE_HUSH_LOOPS
9512 /* Was it "break" or "continue"? */
9513 if (G.flag_break_continue) {
9514 smallint fbc = G.flag_break_continue;
9515 /* We might fall into outer *loop*,
9516 * don't want to break it too */
9518 G.depth_break_continue--;
9519 if (G.depth_break_continue == 0)
9520 G.flag_break_continue = 0;
9521 /* else: e.g. "continue 2" should *break* once, *then* continue */
9522 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9523 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
9524 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9527 /* "continue": simulate end of loop */
9532 if (G_flag_return_in_progress == 1) {
9533 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9536 } else if (pi->followup == PIPE_BG) {
9537 /* What does bash do with attempts to background builtins? */
9538 /* even bash 3.2 doesn't do that well with nested bg:
9539 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9540 * I'm NOT treating inner &'s as jobs */
9542 if (G.run_list_level == 1)
9543 insert_job_into_table(pi);
9545 /* Last command's pid goes to $! */
9546 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
9547 G.last_bg_pid_exitcode = 0;
9548 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
9549 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
9550 rcode = EXIT_SUCCESS;
9554 if (G.run_list_level == 1 && G_interactive_fd) {
9555 /* Waits for completion, then fg's main shell */
9556 rcode = checkjobs_and_fg_shell(pi);
9557 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
9561 /* This one just waits for completion */
9562 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9563 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9565 G.last_exitcode = rcode;
9566 check_and_run_traps();
9569 /* Handle "set -e" */
9570 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9571 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9572 if (G.errexit_depth == 0)
9575 G.errexit_depth = sv_errexit_depth;
9577 /* Analyze how result affects subsequent commands */
9579 if (rword == RES_IF || rword == RES_ELIF)
9582 check_jobs_and_continue:
9583 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9584 dont_check_jobs_but_continue: ;
9585 #if ENABLE_HUSH_LOOPS
9586 /* Beware of "while false; true; do ..."! */
9588 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
9589 /* check for RES_DONE is needed for "while ...; do \n done" case */
9591 if (rword == RES_WHILE) {
9593 /* "while false; do...done" - exitcode 0 */
9594 G.last_exitcode = rcode = EXIT_SUCCESS;
9595 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
9599 if (rword == RES_UNTIL) {
9601 debug_printf_exec(": until expr is true: breaking\n");
9612 #if ENABLE_HUSH_LOOPS
9617 #if ENABLE_HUSH_CASE
9621 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9625 /* Select which version we will use */
9626 static int run_and_free_list(struct pipe *pi)
9629 debug_printf_exec("run_and_free_list entered\n");
9630 if (!G.o_opt[OPT_O_NOEXEC]) {
9631 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9632 rcode = run_list(pi);
9634 /* free_pipe_list has the side effect of clearing memory.
9635 * In the long run that function can be merged with run_list,
9636 * but doing that now would hobble the debugging effort. */
9638 debug_printf_exec("run_and_free_list return %d\n", rcode);
9643 static void install_sighandlers(unsigned mask)
9645 sighandler_t old_handler;
9647 while ((mask >>= 1) != 0) {
9651 old_handler = install_sighandler(sig, pick_sighandler(sig));
9652 /* POSIX allows shell to re-enable SIGCHLD
9653 * even if it was SIG_IGN on entry.
9654 * Therefore we skip IGN check for it:
9658 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9659 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9661 //if (sig == SIGHUP) continue; - TODO?
9662 if (old_handler == SIG_IGN) {
9663 /* oops... restore back to IGN, and record this fact */
9664 install_sighandler(sig, old_handler);
9665 #if ENABLE_HUSH_TRAP
9667 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9669 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9675 /* Called a few times only (or even once if "sh -c") */
9676 static void install_special_sighandlers(void)
9680 /* Which signals are shell-special? */
9681 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
9682 if (G_interactive_fd) {
9683 mask |= SPECIAL_INTERACTIVE_SIGS;
9684 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
9685 mask |= SPECIAL_JOBSTOP_SIGS;
9687 /* Careful, do not re-install handlers we already installed */
9688 if (G.special_sig_mask != mask) {
9689 unsigned diff = mask & ~G.special_sig_mask;
9690 G.special_sig_mask = mask;
9691 install_sighandlers(diff);
9697 /* Set handlers to restore tty pgrp and exit */
9698 static void install_fatal_sighandlers(void)
9702 /* We will restore tty pgrp on these signals */
9704 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9705 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
9706 + (1 << SIGBUS ) * HUSH_DEBUG
9707 + (1 << SIGSEGV) * HUSH_DEBUG
9708 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
9710 /* bash 3.2 seems to handle these just like 'fatal' ones */
9713 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
9714 * if we aren't interactive... but in this case
9715 * we never want to restore pgrp on exit, and this fn is not called
9717 /*+ (1 << SIGHUP )*/
9718 /*+ (1 << SIGTERM)*/
9719 /*+ (1 << SIGINT )*/
9721 G_fatal_sig_mask = mask;
9723 install_sighandlers(mask);
9727 static int set_mode(int state, char mode, const char *o_opt)
9732 G.o_opt[OPT_O_NOEXEC] = state;
9735 IF_HUSH_MODE_X(G_x_mode = state;)
9736 IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
9740 /* "set -+o" without parameter.
9741 * in bash, set -o produces this output:
9745 * We always use the second form.
9747 const char *p = o_opt_strings;
9750 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9756 idx = index_in_strings(o_opt_strings, o_opt);
9758 G.o_opt[idx] = state;
9762 G.o_opt[OPT_O_ERREXIT] = state;
9765 return EXIT_FAILURE;
9767 return EXIT_SUCCESS;
9770 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
9771 int hush_main(int argc, char **argv)
9774 OPT_login = (1 << 0),
9778 unsigned builtin_argc;
9780 struct variable *cur_var;
9781 struct variable *shell_ver;
9784 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
9785 G.last_exitcode = EXIT_SUCCESS;
9787 #if ENABLE_HUSH_FAST
9788 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9791 G.argv0_for_re_execing = argv[0];
9794 /* Deal with HUSH_VERSION */
9795 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9796 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
9797 shell_ver = xzalloc(sizeof(*shell_ver));
9798 shell_ver->flg_export = 1;
9799 shell_ver->flg_read_only = 1;
9800 /* Code which handles ${var<op>...} needs writable values for all variables,
9801 * therefore we xstrdup: */
9802 shell_ver->varstr = xstrdup(hush_version_str);
9804 /* Create shell local variables from the values
9805 * currently living in the environment */
9806 G.top_var = shell_ver;
9807 cur_var = G.top_var;
9810 char *value = strchr(*e, '=');
9811 if (value) { /* paranoia */
9812 cur_var->next = xzalloc(sizeof(*cur_var));
9813 cur_var = cur_var->next;
9814 cur_var->varstr = *e;
9815 cur_var->max_len = strlen(*e);
9816 cur_var->flg_export = 1;
9820 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
9821 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9822 putenv(shell_ver->varstr);
9825 set_pwd_var(SETFLAG_EXPORT);
9827 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9828 /* Set (but not export) PS1/2 unless already set */
9829 if (!get_local_var_value("PS1"))
9830 set_local_var_from_halves("PS1", "\\w \\$ ");
9831 if (!get_local_var_value("PS2"))
9832 set_local_var_from_halves("PS2", "> ");
9835 #if BASH_HOSTNAME_VAR
9836 /* Set (but not export) HOSTNAME unless already set */
9837 if (!get_local_var_value("HOSTNAME")) {
9840 set_local_var_from_halves("HOSTNAME", uts.nodename);
9842 /* bash also exports SHLVL and _,
9843 * and sets (but doesn't export) the following variables:
9845 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9846 * BASH_VERSION='3.2.0(1)-release'
9848 * MACHTYPE=i386-pc-linux-gnu
9850 * PPID=<NNNNN> - we also do it elsewhere
9861 * PIPESTATUS=([0]="0")
9862 * HISTFILE=/<xxx>/.bash_history
9866 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9868 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9877 #if ENABLE_HUSH_LINENO_VAR
9878 if (ENABLE_HUSH_LINENO_VAR) {
9879 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9880 set_local_var(p, /*flags*/ 0);
9881 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9885 #if ENABLE_FEATURE_EDITING
9886 G.line_input_state = new_line_input_t(FOR_SHELL);
9889 /* Initialize some more globals to non-zero values */
9890 cmdedit_update_prompt();
9892 die_func = restore_ttypgrp_and__exit;
9894 /* Shell is non-interactive at first. We need to call
9895 * install_special_sighandlers() if we are going to execute "sh <script>",
9896 * "sh -c <cmds>" or login shell's /etc/profile and friends.
9897 * If we later decide that we are interactive, we run install_special_sighandlers()
9898 * in order to intercept (more) signals.
9902 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
9903 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
9906 int opt = getopt(argc, argv, "+c:exinsl"
9909 # if ENABLE_HUSH_FUNCTIONS
9919 * sh ... -c 'script'
9920 * sh ... -c 'script' ARG0 [ARG1...]
9921 * On NOMMU, if builtin_argc != 0,
9922 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
9923 * "" needs to be replaced with NULL
9924 * and BARGV vector fed to builtin function.
9925 * Note: the form without ARG0 never happens:
9926 * sh ... -c 'builtin' BARGV... ""
9929 G.root_pid = getpid();
9930 G.root_ppid = getppid();
9932 G.global_argv = argv + optind;
9933 G.global_argc = argc - optind;
9935 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9936 const struct built_in_command *x;
9938 install_special_sighandlers();
9939 x = find_builtin(optarg);
9940 if (x) { /* paranoia */
9941 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9942 G.global_argv += builtin_argc;
9943 G.global_argv[-1] = NULL; /* replace "" */
9945 G.last_exitcode = x->b_function(argv + optind - 1);
9949 if (!G.global_argv[0]) {
9950 /* -c 'script' (no params): prevent empty $0 */
9951 G.global_argv--; /* points to argv[i] of 'script' */
9952 G.global_argv[0] = argv[0];
9954 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
9955 install_special_sighandlers();
9956 parse_and_run_string(optarg);
9959 /* Well, we cannot just declare interactiveness,
9960 * we have to have some stuff (ctty, etc) */
9961 /* G_interactive_fd++; */
9970 case '<': /* "big heredoc" support */
9971 full_write1_str(optarg);
9974 unsigned long long empty_trap_mask;
9976 G.root_pid = bb_strtou(optarg, &optarg, 16);
9978 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9980 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9982 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
9984 builtin_argc = bb_strtou(optarg, &optarg, 16);
9986 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9987 if (empty_trap_mask != 0) {
9988 IF_HUSH_TRAP(int sig;)
9989 install_special_sighandlers();
9990 # if ENABLE_HUSH_TRAP
9991 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9992 for (sig = 1; sig < NSIG; sig++) {
9993 if (empty_trap_mask & (1LL << sig)) {
9994 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9995 install_sighandler(sig, SIG_IGN);
10000 # if ENABLE_HUSH_LOOPS
10002 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
10004 # if ENABLE_HUSH_FUNCTIONS
10005 /* nommu uses re-exec trick for "... | func | ...",
10006 * should allow "return".
10007 * This accidentally allows returns in subshells.
10009 G_flag_return_in_progress = -1;
10015 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
10017 # if ENABLE_HUSH_FUNCTIONS
10019 struct function *funcp = new_function(optarg);
10020 /* funcp->name is already set to optarg */
10021 /* funcp->body is set to NULL. It's a special case. */
10022 funcp->body_as_string = argv[optind];
10031 if (set_mode(1, opt, NULL) == 0) /* no error */
10035 fprintf(stderr, "Usage: sh [FILE]...\n"
10036 " or: sh -c command [args]...\n\n");
10037 exit(EXIT_FAILURE);
10042 } /* option parsing loop */
10044 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10045 G.global_argc = argc - (optind - 1);
10046 G.global_argv = argv + (optind - 1);
10047 G.global_argv[0] = argv[0];
10050 G.root_pid = getpid();
10051 G.root_ppid = getppid();
10054 /* If we are login shell... */
10055 if (flags & OPT_login) {
10057 debug_printf("sourcing /etc/profile\n");
10058 input = hfopen("/etc/profile");
10059 if (input != NULL) {
10060 install_special_sighandlers();
10061 parse_and_run_file(input);
10064 /* bash: after sourcing /etc/profile,
10065 * tries to source (in the given order):
10066 * ~/.bash_profile, ~/.bash_login, ~/.profile,
10067 * stopping on first found. --noprofile turns this off.
10068 * bash also sources ~/.bash_logout on exit.
10069 * If called as sh, skips .bash_XXX files.
10073 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10074 if (!(flags & OPT_s) && G.global_argv[1]) {
10077 * "bash <script>" (which is never interactive (unless -i?))
10078 * sources $BASH_ENV here (without scanning $PATH).
10079 * If called as sh, does the same but with $ENV.
10080 * Also NB, per POSIX, $ENV should undergo parameter expansion.
10084 debug_printf("running script '%s'\n", G.global_argv[0]);
10085 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
10086 input = hfopen(G.global_argv[0]);
10088 bb_simple_perror_msg_and_die(G.global_argv[0]);
10090 xfunc_error_retval = 1;
10091 install_special_sighandlers();
10092 parse_and_run_file(input);
10093 #if ENABLE_FEATURE_CLEAN_UP
10099 /* Up to here, shell was non-interactive. Now it may become one.
10100 * NB: don't forget to (re)run install_special_sighandlers() as needed.
10103 /* A shell is interactive if the '-i' flag was given,
10104 * or if all of the following conditions are met:
10106 * no arguments remaining or the -s flag given
10107 * standard input is a terminal
10108 * standard output is a terminal
10109 * Refer to Posix.2, the description of the 'sh' utility.
10111 #if ENABLE_HUSH_JOB
10112 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10113 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10114 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10115 if (G_saved_tty_pgrp < 0)
10116 G_saved_tty_pgrp = 0;
10118 /* try to dup stdin to high fd#, >= 255 */
10119 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10120 if (G_interactive_fd < 0) {
10121 /* try to dup to any fd */
10122 G_interactive_fd = dup(STDIN_FILENO);
10123 if (G_interactive_fd < 0) {
10125 G_interactive_fd = 0;
10126 G_saved_tty_pgrp = 0;
10129 // TODO: track & disallow any attempts of user
10130 // to (inadvertently) close/redirect G_interactive_fd
10132 debug_printf("interactive_fd:%d\n", G_interactive_fd);
10133 if (G_interactive_fd) {
10134 close_on_exec_on(G_interactive_fd);
10136 if (G_saved_tty_pgrp) {
10137 /* If we were run as 'hush &', sleep until we are
10138 * in the foreground (tty pgrp == our pgrp).
10139 * If we get started under a job aware app (like bash),
10140 * make sure we are now in charge so we don't fight over
10141 * who gets the foreground */
10143 pid_t shell_pgrp = getpgrp();
10144 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10145 if (G_saved_tty_pgrp == shell_pgrp)
10147 /* send TTIN to ourself (should stop us) */
10148 kill(- shell_pgrp, SIGTTIN);
10152 /* Install more signal handlers */
10153 install_special_sighandlers();
10155 if (G_saved_tty_pgrp) {
10156 /* Set other signals to restore saved_tty_pgrp */
10157 install_fatal_sighandlers();
10158 /* Put ourselves in our own process group
10159 * (bash, too, does this only if ctty is available) */
10160 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10161 /* Grab control of the terminal */
10162 tcsetpgrp(G_interactive_fd, getpid());
10164 enable_restore_tty_pgrp_on_exit();
10166 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10168 const char *hp = get_local_var_value("HISTFILE");
10170 hp = get_local_var_value("HOME");
10172 hp = concat_path_file(hp, ".hush_history");
10177 G.line_input_state->hist_file = hp;
10178 //set_local_var(xasprintf("HISTFILE=%s", ...));
10180 # if ENABLE_FEATURE_SH_HISTFILESIZE
10181 hp = get_local_var_value("HISTFILESIZE");
10182 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10187 install_special_sighandlers();
10189 #elif ENABLE_HUSH_INTERACTIVE
10190 /* No job control compiled in, only prompt/line editing */
10191 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10192 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10193 if (G_interactive_fd < 0) {
10194 /* try to dup to any fd */
10195 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
10196 if (G_interactive_fd < 0)
10198 G_interactive_fd = 0;
10201 if (G_interactive_fd) {
10202 close_on_exec_on(G_interactive_fd);
10204 install_special_sighandlers();
10206 /* We have interactiveness code disabled */
10207 install_special_sighandlers();
10210 * if interactive but not a login shell, sources ~/.bashrc
10211 * (--norc turns this off, --rcfile <file> overrides)
10214 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
10215 /* note: ash and hush share this string */
10216 printf("\n\n%s %s\n"
10217 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10220 "hush - the humble shell"
10224 parse_and_run_file(hfopen(NULL)); /* stdin */
10227 hush_exit(G.last_exitcode);
10234 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
10239 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
10240 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
10242 int argc = string_array_len(argv);
10243 return applet_main_func(argc, argv);
10246 #if ENABLE_HUSH_TEST || BASH_TEST2
10247 static int FAST_FUNC builtin_test(char **argv)
10249 return run_applet_main(argv, test_main);
10252 #if ENABLE_HUSH_ECHO
10253 static int FAST_FUNC builtin_echo(char **argv)
10255 return run_applet_main(argv, echo_main);
10258 #if ENABLE_HUSH_PRINTF
10259 static int FAST_FUNC builtin_printf(char **argv)
10261 return run_applet_main(argv, printf_main);
10265 #if ENABLE_HUSH_HELP
10266 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10268 const struct built_in_command *x;
10271 "Built-in commands:\n"
10272 "------------------\n");
10273 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10275 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10277 return EXIT_SUCCESS;
10281 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
10282 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10284 show_history(G.line_input_state);
10285 return EXIT_SUCCESS;
10289 static char **skip_dash_dash(char **argv)
10292 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10297 static int FAST_FUNC builtin_cd(char **argv)
10299 const char *newdir;
10301 argv = skip_dash_dash(argv);
10303 if (newdir == NULL) {
10304 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
10305 * bash says "bash: cd: HOME not set" and does nothing
10308 const char *home = get_local_var_value("HOME");
10309 newdir = home ? home : "/";
10311 if (chdir(newdir)) {
10312 /* Mimic bash message exactly */
10313 bb_perror_msg("cd: %s", newdir);
10314 return EXIT_FAILURE;
10316 /* Read current dir (get_cwd(1) is inside) and set PWD.
10317 * Note: do not enforce exporting. If PWD was unset or unexported,
10318 * set it again, but do not export. bash does the same.
10320 set_pwd_var(/*flag:*/ 0);
10321 return EXIT_SUCCESS;
10324 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10327 return EXIT_SUCCESS;
10330 static int FAST_FUNC builtin_eval(char **argv)
10332 argv = skip_dash_dash(argv);
10335 return EXIT_SUCCESS;
10337 IF_HUSH_MODE_X(G.x_mode_depth++;)
10338 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
10341 * eval "echo Hi; done" ("done" is syntax error):
10342 * "echo Hi" will not execute too.
10344 parse_and_run_string(argv[0]);
10346 /* "The eval utility shall construct a command by
10347 * concatenating arguments together, separating
10348 * each with a <space> character."
10354 len += strlen(*pp) + 1;
10356 str = p = xmalloc(len);
10359 p = stpcpy(p, *pp);
10365 parse_and_run_string(str);
10368 IF_HUSH_MODE_X(G.x_mode_depth--;)
10369 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
10370 return G.last_exitcode;
10373 static int FAST_FUNC builtin_exec(char **argv)
10375 argv = skip_dash_dash(argv);
10376 if (argv[0] == NULL)
10377 return EXIT_SUCCESS; /* bash does this */
10379 /* Careful: we can end up here after [v]fork. Do not restore
10380 * tty pgrp then, only top-level shell process does that */
10381 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10382 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10384 /* Saved-redirect fds, script fds and G_interactive_fd are still
10385 * open here. However, they are all CLOEXEC, and execv below
10386 * closes them. Try interactive "exec ls -l /proc/self/fd",
10387 * it should show no extra open fds in the "ls" process.
10388 * If we'd try to run builtins/NOEXECs, this would need improving.
10390 //close_saved_fds_and_FILE_fds();
10392 /* TODO: if exec fails, bash does NOT exit! We do.
10393 * We'll need to undo trap cleanup (it's inside execvp_or_die)
10394 * and tcsetpgrp, and this is inherently racy.
10396 execvp_or_die(argv);
10399 static int FAST_FUNC builtin_exit(char **argv)
10401 debug_printf_exec("%s()\n", __func__);
10403 /* interactive bash:
10404 * # trap "echo EEE" EXIT
10407 * There are stopped jobs.
10408 * (if there are _stopped_ jobs, running ones don't count)
10411 * EEE (then bash exits)
10413 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
10416 /* note: EXIT trap is run by hush_exit */
10417 argv = skip_dash_dash(argv);
10418 if (argv[0] == NULL)
10419 hush_exit(G.last_exitcode);
10420 /* mimic bash: exit 123abc == exit 255 + error msg */
10421 xfunc_error_retval = 255;
10422 /* bash: exit -2 == exit 254, no error msg */
10423 hush_exit(xatoi(argv[0]) & 0xff);
10426 #if ENABLE_HUSH_TYPE
10427 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10428 static int FAST_FUNC builtin_type(char **argv)
10430 int ret = EXIT_SUCCESS;
10436 if (0) {} /* make conditional compile easier below */
10437 /*else if (find_alias(*argv))
10438 type = "an alias";*/
10439 #if ENABLE_HUSH_FUNCTIONS
10440 else if (find_function(*argv))
10441 type = "a function";
10443 else if (find_builtin(*argv))
10444 type = "a shell builtin";
10445 else if ((path = find_in_path(*argv)) != NULL)
10448 bb_error_msg("type: %s: not found", *argv);
10449 ret = EXIT_FAILURE;
10453 printf("%s is %s\n", *argv, type);
10461 #if ENABLE_HUSH_READ
10462 /* Interruptibility of read builtin in bash
10463 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10465 * Empty trap makes read ignore corresponding signal, for any signal.
10468 * - terminates non-interactive shell;
10469 * - interrupts read in interactive shell;
10470 * if it has non-empty trap:
10471 * - executes trap and returns to command prompt in interactive shell;
10472 * - executes trap and returns to read in non-interactive shell;
10474 * - is ignored (does not interrupt) read in interactive shell;
10475 * - terminates non-interactive shell;
10476 * if it has non-empty trap:
10477 * - executes trap and returns to read;
10479 * - terminates shell (regardless of interactivity);
10480 * if it has non-empty trap:
10481 * - executes trap and returns to read;
10482 * SIGCHLD from children:
10483 * - does not interrupt read regardless of interactivity:
10484 * try: sleep 1 & read x; echo $x
10486 static int FAST_FUNC builtin_read(char **argv)
10489 char *opt_n = NULL;
10490 char *opt_p = NULL;
10491 char *opt_t = NULL;
10492 char *opt_u = NULL;
10493 char *opt_d = NULL; /* optimized out if !BASH */
10497 /* "!": do not abort on errors.
10498 * Option string must start with "sr" to match BUILTIN_READ_xxx
10500 read_flags = getopt32(argv,
10502 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10504 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10507 if (read_flags == (uint32_t)-1)
10508 return EXIT_FAILURE;
10510 ifs = get_local_var_value("IFS"); /* can be NULL */
10513 r = shell_builtin_read(set_local_var_from_halves,
10524 if ((uintptr_t)r == 1 && errno == EINTR) {
10525 unsigned sig = check_and_run_traps();
10530 if ((uintptr_t)r > 1) {
10531 bb_error_msg("%s", r);
10532 r = (char*)(uintptr_t)1;
10535 return (uintptr_t)r;
10539 #if ENABLE_HUSH_UMASK
10540 static int FAST_FUNC builtin_umask(char **argv)
10547 argv = skip_dash_dash(argv);
10549 mode_t old_mask = mask;
10551 /* numeric umasks are taken as-is */
10552 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10553 if (!isdigit(argv[0][0]))
10555 mask = bb_parse_mode(argv[0], mask);
10556 if (!isdigit(argv[0][0]))
10558 if ((unsigned)mask > 0777) {
10561 * bash: umask: 'q': invalid symbolic mode operator
10562 * bash: umask: 999: octal number out of range
10564 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10569 printf("%04o\n", (unsigned) mask);
10570 /* fall through and restore mask which we set to 0 */
10574 return !rc; /* rc != 0 - success */
10578 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
10579 static void print_escaped(const char *s)
10584 const char *p = strchrnul(s, '\'');
10585 /* print 'xxxx', possibly just '' */
10586 printf("'%.*s'", (int)(p - s), s);
10591 /* s points to '; print "'''...'''" */
10593 do putchar('\''); while (*++s == '\'');
10599 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
10600 static int helper_export_local(char **argv, unsigned flags)
10603 char *name = *argv;
10604 char *name_end = strchrnul(name, '=');
10606 /* So far we do not check that name is valid (TODO?) */
10608 if (*name_end == '\0') {
10609 struct variable *var, **vpp;
10611 vpp = get_ptr_to_local_var(name, name_end - name);
10612 var = vpp ? *vpp : NULL;
10614 if (flags & SETFLAG_UNEXPORT) {
10615 /* export -n NAME (without =VALUE) */
10617 var->flg_export = 0;
10618 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10620 } /* else: export -n NOT_EXISTING_VAR: no-op */
10623 if (flags & SETFLAG_EXPORT) {
10624 /* export NAME (without =VALUE) */
10626 var->flg_export = 1;
10627 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10628 putenv(var->varstr);
10632 if (flags & SETFLAG_MAKE_RO) {
10633 /* readonly NAME (without =VALUE) */
10635 var->flg_read_only = 1;
10639 # if ENABLE_HUSH_LOCAL
10640 /* Is this "local" bltin? */
10641 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
10642 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10643 if (var && var->var_nest_level == lvl) {
10644 /* "local x=abc; ...; local x" - ignore second local decl */
10649 /* Exporting non-existing variable.
10650 * bash does not put it in environment,
10651 * but remembers that it is exported,
10652 * and does put it in env when it is set later.
10653 * We just set it to "" and export.
10655 /* Or, it's "local NAME" (without =VALUE).
10656 * bash sets the value to "".
10658 /* Or, it's "readonly NAME" (without =VALUE).
10659 * bash remembers NAME and disallows its creation
10662 name = xasprintf("%s=", name);
10664 /* (Un)exporting/making local NAME=VALUE */
10665 name = xstrdup(name);
10667 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
10668 if (set_local_var(name, flags))
10669 return EXIT_FAILURE;
10671 return EXIT_SUCCESS;
10675 #if ENABLE_HUSH_EXPORT
10676 static int FAST_FUNC builtin_export(char **argv)
10678 unsigned opt_unexport;
10680 #if ENABLE_HUSH_EXPORT_N
10681 /* "!": do not abort on errors */
10682 opt_unexport = getopt32(argv, "!n");
10683 if (opt_unexport == (uint32_t)-1)
10684 return EXIT_FAILURE;
10691 if (argv[0] == NULL) {
10692 char **e = environ;
10698 /* ash emits: export VAR='VAL'
10699 * bash: declare -x VAR="VAL"
10700 * we follow ash example */
10701 const char *s = *e++;
10702 const char *p = strchr(s, '=');
10704 if (!p) /* wtf? take next variable */
10707 printf("export %.*s", (int)(p - s) + 1, s);
10708 print_escaped(p + 1);
10712 /*fflush_all(); - done after each builtin anyway */
10714 return EXIT_SUCCESS;
10717 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
10721 #if ENABLE_HUSH_LOCAL
10722 static int FAST_FUNC builtin_local(char **argv)
10724 if (G.func_nest_level == 0) {
10725 bb_error_msg("%s: not in a function", argv[0]);
10726 return EXIT_FAILURE; /* bash compat */
10729 /* Since all builtins run in a nested variable level,
10730 * need to use level - 1 here. Or else the variable will be removed at once
10731 * after builtin returns.
10733 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
10737 #if ENABLE_HUSH_READONLY
10738 static int FAST_FUNC builtin_readonly(char **argv)
10741 if (*argv == NULL) {
10742 /* bash: readonly [-p]: list all readonly VARs
10743 * (-p has no effect in bash)
10745 struct variable *e;
10746 for (e = G.top_var; e; e = e->next) {
10747 if (e->flg_read_only) {
10748 //TODO: quote value: readonly VAR='VAL'
10749 printf("readonly %s\n", e->varstr);
10752 return EXIT_SUCCESS;
10754 return helper_export_local(argv, SETFLAG_MAKE_RO);
10758 #if ENABLE_HUSH_UNSET
10759 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10760 static int FAST_FUNC builtin_unset(char **argv)
10765 /* "!": do not abort on errors */
10766 /* "+": stop at 1st non-option */
10767 opts = getopt32(argv, "!+vf");
10768 if (opts == (unsigned)-1)
10769 return EXIT_FAILURE;
10771 bb_error_msg("unset: -v and -f are exclusive");
10772 return EXIT_FAILURE;
10776 ret = EXIT_SUCCESS;
10778 if (!(opts & 2)) { /* not -f */
10779 if (unset_local_var(*argv)) {
10780 /* unset <nonexistent_var> doesn't fail.
10781 * Error is when one tries to unset RO var.
10782 * Message was printed by unset_local_var. */
10783 ret = EXIT_FAILURE;
10786 # if ENABLE_HUSH_FUNCTIONS
10797 #if ENABLE_HUSH_SET
10798 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10799 * built-in 'set' handler
10801 * set [-abCefhmnuvx] [-o option] [argument...]
10802 * set [+abCefhmnuvx] [+o option] [argument...]
10803 * set -- [argument...]
10806 * Implementations shall support the options in both their hyphen and
10807 * plus-sign forms. These options can also be specified as options to sh.
10809 * Write out all variables and their values: set
10810 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10811 * Turn on the -x and -v options: set -xv
10812 * Unset all positional parameters: set --
10813 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10814 * Set the positional parameters to the expansion of x, even if x expands
10815 * with a leading '-' or '+': set -- $x
10817 * So far, we only support "set -- [argument...]" and some of the short names.
10819 static int FAST_FUNC builtin_set(char **argv)
10822 char **pp, **g_argv;
10823 char *arg = *++argv;
10826 struct variable *e;
10827 for (e = G.top_var; e; e = e->next)
10829 return EXIT_SUCCESS;
10833 if (strcmp(arg, "--") == 0) {
10837 if (arg[0] != '+' && arg[0] != '-')
10839 for (n = 1; arg[n]; ++n) {
10840 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10842 if (arg[n] == 'o' && argv[1])
10845 } while ((arg = *++argv) != NULL);
10846 /* Now argv[0] is 1st argument */
10849 return EXIT_SUCCESS;
10852 /* NB: G.global_argv[0] ($0) is never freed/changed */
10853 g_argv = G.global_argv;
10854 if (G.global_args_malloced) {
10860 G.global_args_malloced = 1;
10861 pp = xzalloc(sizeof(pp[0]) * 2);
10862 pp[0] = g_argv[0]; /* retain $0 */
10865 /* This realloc's G.global_argv */
10866 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10868 G.global_argc = 1 + string_array_len(pp + 1);
10870 return EXIT_SUCCESS;
10872 /* Nothing known, so abort */
10874 bb_error_msg("%s: %s: invalid option", "set", arg);
10875 return EXIT_FAILURE;
10879 static int FAST_FUNC builtin_shift(char **argv)
10882 argv = skip_dash_dash(argv);
10884 n = bb_strtou(argv[0], NULL, 10);
10885 if (errno || n < 0) {
10886 /* shared string with ash.c */
10887 bb_error_msg("Illegal number: %s", argv[0]);
10889 * ash aborts in this case.
10890 * bash prints error message and set $? to 1.
10891 * Interestingly, for "shift 99999" bash does not
10892 * print error message, but does set $? to 1
10893 * (and does no shifting at all).
10897 if (n >= 0 && n < G.global_argc) {
10898 if (G_global_args_malloced) {
10901 free(G.global_argv[m++]);
10903 G.global_argc -= n;
10904 memmove(&G.global_argv[1], &G.global_argv[n+1],
10905 G.global_argc * sizeof(G.global_argv[0]));
10906 return EXIT_SUCCESS;
10908 return EXIT_FAILURE;
10911 #if ENABLE_HUSH_GETOPTS
10912 static int FAST_FUNC builtin_getopts(char **argv)
10914 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10917 If a required argument is not found, and getopts is not silent,
10918 a question mark (?) is placed in VAR, OPTARG is unset, and a
10919 diagnostic message is printed. If getopts is silent, then a
10920 colon (:) is placed in VAR and OPTARG is set to the option
10923 Test that VAR is a valid variable name?
10925 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
10928 const char *cp, *optstring, *var;
10929 int c, n, exitcode, my_opterr;
10932 optstring = *++argv;
10933 if (!optstring || !(var = *++argv)) {
10934 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10935 return EXIT_FAILURE;
10939 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10941 argv = G.global_argv;
10945 if (optstring[0] != ':') {
10946 cp = get_local_var_value("OPTERR");
10947 /* 0 if "OPTERR=0", 1 otherwise */
10948 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
10951 /* getopts stops on first non-option. Add "+" to force that */
10952 /*if (optstring[0] != '+')*/ {
10953 char *s = alloca(strlen(optstring) + 2);
10954 sprintf(s, "+%s", optstring);
10958 /* Naively, now we should just
10959 * cp = get_local_var_value("OPTIND");
10960 * optind = cp ? atoi(cp) : 0;
10962 * opterr = my_opterr;
10963 * c = getopt(string_array_len(argv), argv, optstring);
10964 * and be done? Not so fast...
10965 * Unlike normal getopt() usage in C programs, here
10966 * each successive call will (usually) have the same argv[] CONTENTS,
10967 * but not the ADDRESSES. Worse yet, it's possible that between
10968 * invocations of "getopts", there will be calls to shell builtins
10969 * which use getopt() internally. Example:
10970 * while getopts "abc" RES -a -bc -abc de; do
10973 * This would not work correctly: getopt() call inside "unset"
10974 * modifies internal libc state which is tracking position in
10975 * multi-option strings ("-abc"). At best, it can skip options
10976 * or return the same option infinitely. With glibc implementation
10977 * of getopt(), it would use outright invalid pointers and return
10978 * garbage even _without_ "unset" mangling internal state.
10980 * We resort to resetting getopt() state and calling it N times,
10981 * until we get Nth result (or failure).
10982 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10986 n = string_array_len(argv);
10989 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10990 c = getopt(n, argv, optstring);
10994 } while (count <= G.getopt_count);
10996 /* Set OPTIND. Prevent resetting of the magic counter! */
10997 set_local_var_from_halves("OPTIND", utoa(optind));
10998 G.getopt_count = count; /* "next time, give me N+1'th result" */
10999 GETOPT_RESET(); /* just in case */
11002 /* Always set or unset, never left as-is, even on exit/error:
11003 * "If no option was found, or if the option that was found
11004 * does not have an option-argument, OPTARG shall be unset."
11008 /* If ":optstring" and unknown option is seen,
11009 * it is stored to OPTARG.
11011 if (optstring[1] == ':') {
11017 set_local_var_from_halves("OPTARG", cp);
11019 unset_local_var("OPTARG");
11021 /* Convert -1 to "?" */
11022 exitcode = EXIT_SUCCESS;
11023 if (c < 0) { /* -1: end of options */
11024 exitcode = EXIT_FAILURE;
11030 set_local_var_from_halves(var, cbuf);
11036 static int FAST_FUNC builtin_source(char **argv)
11038 char *arg_path, *filename;
11041 char *args_need_save;
11042 #if ENABLE_HUSH_FUNCTIONS
11046 argv = skip_dash_dash(argv);
11047 filename = argv[0];
11049 /* bash says: "bash: .: filename argument required" */
11050 return 2; /* bash compat */
11053 if (!strchr(filename, '/')) {
11054 arg_path = find_in_path(filename);
11056 filename = arg_path;
11057 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
11059 bb_simple_perror_msg(filename);
11060 return EXIT_FAILURE;
11063 input = hfopen(filename);
11066 bb_perror_msg("%s", filename);
11067 /* POSIX: non-interactive shell should abort here,
11068 * not merely fail. So far no one complained :)
11070 return EXIT_FAILURE;
11073 #if ENABLE_HUSH_FUNCTIONS
11074 sv_flg = G_flag_return_in_progress;
11075 /* "we are inside sourced file, ok to use return" */
11076 G_flag_return_in_progress = -1;
11078 args_need_save = argv[1]; /* used as a boolean variable */
11079 if (args_need_save)
11080 save_and_replace_G_args(&sv, argv);
11082 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11083 G.last_exitcode = 0;
11084 parse_and_run_file(input);
11087 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11088 restore_G_args(&sv, argv);
11089 #if ENABLE_HUSH_FUNCTIONS
11090 G_flag_return_in_progress = sv_flg;
11093 return G.last_exitcode;
11096 #if ENABLE_HUSH_TRAP
11097 static int FAST_FUNC builtin_trap(char **argv)
11103 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
11108 /* No args: print all trapped */
11109 for (i = 0; i < NSIG; ++i) {
11111 printf("trap -- ");
11112 print_escaped(G_traps[i]);
11113 /* note: bash adds "SIG", but only if invoked
11114 * as "bash". If called as "sh", or if set -o posix,
11115 * then it prints short signal names.
11116 * We are printing short names: */
11117 printf(" %s\n", get_signame(i));
11120 /*fflush_all(); - done after each builtin anyway */
11121 return EXIT_SUCCESS;
11125 /* If first arg is a number: reset all specified signals */
11126 sig = bb_strtou(*argv, NULL, 10);
11130 ret = EXIT_SUCCESS;
11132 sighandler_t handler;
11134 sig = get_signum(*argv++);
11136 ret = EXIT_FAILURE;
11137 /* Mimic bash message exactly */
11138 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
11142 free(G_traps[sig]);
11143 G_traps[sig] = xstrdup(new_cmd);
11145 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
11146 get_signame(sig), sig, G_traps[sig]);
11148 /* There is no signal for 0 (EXIT) */
11153 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11155 /* We are removing trap handler */
11156 handler = pick_sighandler(sig);
11157 install_sighandler(sig, handler);
11162 if (!argv[1]) { /* no second arg */
11163 bb_error_msg("trap: invalid arguments");
11164 return EXIT_FAILURE;
11167 /* First arg is "-": reset all specified to default */
11168 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11169 /* Everything else: set arg as signal handler
11170 * (includes "" case, which ignores signal) */
11171 if (argv[0][0] == '-') {
11172 if (argv[0][1] == '\0') { /* "-" */
11173 /* new_cmd remains NULL: "reset these sigs" */
11176 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11179 /* else: "-something", no special meaning */
11184 goto process_sig_list;
11188 #if ENABLE_HUSH_JOB
11189 static struct pipe *parse_jobspec(const char *str)
11194 if (sscanf(str, "%%%u", &jobnum) != 1) {
11196 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11198 bb_error_msg("bad argument '%s'", str);
11201 /* It is "%%", "%+" or "%" - current job */
11202 jobnum = G.last_jobid;
11204 bb_error_msg("no current job");
11208 for (pi = G.job_list; pi; pi = pi->next) {
11209 if (pi->jobid == jobnum) {
11213 bb_error_msg("%u: no such job", jobnum);
11217 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11220 const char *status_string;
11222 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11223 for (job = G.job_list; job; job = job->next) {
11224 if (job->alive_cmds == job->stopped_cmds)
11225 status_string = "Stopped";
11227 status_string = "Running";
11229 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11232 clean_up_last_dead_job();
11234 return EXIT_SUCCESS;
11237 /* built-in 'fg' and 'bg' handler */
11238 static int FAST_FUNC builtin_fg_bg(char **argv)
11243 if (!G_interactive_fd)
11244 return EXIT_FAILURE;
11246 /* If they gave us no args, assume they want the last backgrounded task */
11248 for (pi = G.job_list; pi; pi = pi->next) {
11249 if (pi->jobid == G.last_jobid) {
11253 bb_error_msg("%s: no current job", argv[0]);
11254 return EXIT_FAILURE;
11257 pi = parse_jobspec(argv[1]);
11259 return EXIT_FAILURE;
11261 /* TODO: bash prints a string representation
11262 * of job being foregrounded (like "sleep 1 | cat") */
11263 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
11264 /* Put the job into the foreground. */
11265 tcsetpgrp(G_interactive_fd, pi->pgrp);
11268 /* Restart the processes in the job */
11269 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11270 for (i = 0; i < pi->num_cmds; i++) {
11271 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
11273 pi->stopped_cmds = 0;
11275 i = kill(- pi->pgrp, SIGCONT);
11277 if (errno == ESRCH) {
11278 delete_finished_job(pi);
11279 return EXIT_SUCCESS;
11281 bb_perror_msg("kill (SIGCONT)");
11284 if (argv[0][0] == 'f') {
11285 remove_job_from_table(pi); /* FG job shouldn't be in job table */
11286 return checkjobs_and_fg_shell(pi);
11288 return EXIT_SUCCESS;
11292 #if ENABLE_HUSH_KILL
11293 static int FAST_FUNC builtin_kill(char **argv)
11297 # if ENABLE_HUSH_JOB
11298 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11306 if (argv[i][0] != '%')
11309 * "kill %N" - job kill
11310 * Converting to pgrp / pid kill
11312 pi = parse_jobspec(argv[i]);
11314 /* Eat bad jobspec */
11318 argv[j - 1] = argv[j];
11325 * In jobs started under job control, we signal
11326 * entire process group by kill -PGRP_ID.
11327 * This happens, f.e., in interactive shell.
11329 * Otherwise, we signal each child via
11330 * kill PID1 PID2 PID3.
11332 * sh -c 'sleep 1|sleep 1 & kill %1'
11333 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11334 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11336 n = G_interactive_fd ? 1 : pi->num_cmds;
11337 dst = alloca(n * sizeof(int)*4);
11339 if (G_interactive_fd)
11340 dst += sprintf(dst, " -%u", (int)pi->pgrp);
11341 else for (j = 0; j < n; j++) {
11342 struct command *cmd = &pi->cmds[j];
11343 /* Skip exited members of the job */
11347 * kill_main has matching code to expect
11348 * leading space. Needed to not confuse
11349 * negative pids with "kill -SIGNAL_NO" syntax
11351 dst += sprintf(dst, " %u", (int)cmd->pid);
11354 } while (argv[++i]);
11358 if (argv[1] || ret == 0) {
11359 ret = run_applet_main(argv, kill_main);
11361 /* else: ret = 1, "kill %bad_jobspec" case */
11366 #if ENABLE_HUSH_WAIT
11367 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
11368 #if !ENABLE_HUSH_JOB
11369 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11371 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
11378 if (!sigisemptyset(&G.pending_set))
11381 /* waitpid is not interruptible by SA_RESTARTed
11382 * signals which we use. Thus, this ugly dance:
11385 /* Make sure possible SIGCHLD is stored in kernel's
11386 * pending signal mask before we call waitpid.
11387 * Or else we may race with SIGCHLD, lose it,
11388 * and get stuck in sigsuspend...
11390 sigfillset(&oldset); /* block all signals, remember old set */
11391 sigprocmask(SIG_SETMASK, &oldset, &oldset);
11393 if (!sigisemptyset(&G.pending_set)) {
11394 /* Crap! we raced with some signal! */
11398 /*errno = 0; - checkjobs does this */
11399 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
11400 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
11401 debug_printf_exec("checkjobs:%d\n", ret);
11402 #if ENABLE_HUSH_JOB
11403 if (waitfor_pipe) {
11404 int rcode = job_exited_or_stopped(waitfor_pipe);
11405 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11408 sigprocmask(SIG_SETMASK, &oldset, NULL);
11413 /* if ECHILD, there are no children (ret is -1 or 0) */
11414 /* if ret == 0, no children changed state */
11415 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
11416 if (errno == ECHILD || ret) {
11418 if (ret < 0) /* if ECHILD, may need to fix "ret" */
11420 sigprocmask(SIG_SETMASK, &oldset, NULL);
11423 /* Wait for SIGCHLD or any other signal */
11424 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11425 /* Note: sigsuspend invokes signal handler */
11426 sigsuspend(&oldset);
11428 sigprocmask(SIG_SETMASK, &oldset, NULL);
11430 /* So, did we get a signal? */
11431 sig = check_and_run_traps();
11432 if (sig /*&& sig != SIGCHLD - always true */) {
11433 /* Do this for any (non-ignored) signal, not only for ^C */
11437 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11442 static int FAST_FUNC builtin_wait(char **argv)
11447 argv = skip_dash_dash(argv);
11448 if (argv[0] == NULL) {
11449 /* Don't care about wait results */
11450 /* Note 1: must wait until there are no more children */
11451 /* Note 2: must be interruptible */
11453 * $ sleep 3 & sleep 6 & wait
11454 * [1] 30934 sleep 3
11455 * [2] 30935 sleep 6
11458 * $ sleep 3 & sleep 6 & wait
11459 * [1] 30936 sleep 3
11460 * [2] 30937 sleep 6
11462 * ^C <-- after ~4 sec from keyboard
11465 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
11469 pid_t pid = bb_strtou(*argv, NULL, 10);
11470 if (errno || pid <= 0) {
11471 #if ENABLE_HUSH_JOB
11472 if (argv[0][0] == '%') {
11473 struct pipe *wait_pipe;
11474 ret = 127; /* bash compat for bad jobspecs */
11475 wait_pipe = parse_jobspec(*argv);
11477 ret = job_exited_or_stopped(wait_pipe);
11479 ret = wait_for_child_or_signal(wait_pipe, 0);
11481 /* waiting on "last dead job" removes it */
11482 clean_up_last_dead_job();
11485 /* else: parse_jobspec() already emitted error msg */
11489 /* mimic bash message */
11490 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
11491 ret = EXIT_FAILURE;
11492 continue; /* bash checks all argv[] */
11495 /* Do we have such child? */
11496 ret = waitpid(pid, &status, WNOHANG);
11500 if (errno == ECHILD) {
11501 if (pid == G.last_bg_pid) {
11502 /* "wait $!" but last bg task has already exited. Try:
11503 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11504 * In bash it prints exitcode 0, then 3.
11505 * In dash, it is 127.
11507 ret = G.last_bg_pid_exitcode;
11509 /* Example: "wait 1". mimic bash message */
11510 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
11514 bb_perror_msg("wait %s", *argv);
11516 continue; /* bash checks all argv[] */
11519 /* Yes, and it still runs */
11520 ret = wait_for_child_or_signal(NULL, pid);
11522 /* Yes, and it just exited */
11523 process_wait_result(NULL, pid, status);
11524 ret = WEXITSTATUS(status);
11525 if (WIFSIGNALED(status))
11526 ret = 128 + WTERMSIG(status);
11534 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11535 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11538 def = bb_strtou(argv[1], NULL, 10);
11539 if (errno || def < def_min || argv[2]) {
11540 bb_error_msg("%s: bad arguments", argv[0]);
11548 #if ENABLE_HUSH_LOOPS
11549 static int FAST_FUNC builtin_break(char **argv)
11552 if (G.depth_of_loop == 0) {
11553 bb_error_msg("%s: only meaningful in a loop", argv[0]);
11554 /* if we came from builtin_continue(), need to undo "= 1" */
11555 G.flag_break_continue = 0;
11556 return EXIT_SUCCESS; /* bash compat */
11558 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
11560 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11561 if (depth == UINT_MAX)
11562 G.flag_break_continue = BC_BREAK;
11563 if (G.depth_of_loop < depth)
11564 G.depth_break_continue = G.depth_of_loop;
11566 return EXIT_SUCCESS;
11569 static int FAST_FUNC builtin_continue(char **argv)
11571 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11572 return builtin_break(argv);
11576 #if ENABLE_HUSH_FUNCTIONS
11577 static int FAST_FUNC builtin_return(char **argv)
11581 if (G_flag_return_in_progress != -1) {
11582 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11583 return EXIT_FAILURE; /* bash compat */
11586 G_flag_return_in_progress = 1;
11589 * out of range: wraps around at 256, does not error out
11590 * non-numeric param:
11591 * f() { false; return qwe; }; f; echo $?
11592 * bash: return: qwe: numeric argument required <== we do this
11593 * 255 <== we also do this
11595 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11600 #if ENABLE_HUSH_TIMES
11601 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11603 static const uint8_t times_tbl[] ALIGN1 = {
11604 ' ', offsetof(struct tms, tms_utime),
11605 '\n', offsetof(struct tms, tms_stime),
11606 ' ', offsetof(struct tms, tms_cutime),
11607 '\n', offsetof(struct tms, tms_cstime),
11614 clk_tck = bb_clk_tck();
11619 unsigned sec, frac;
11621 t = *(clock_t *)(((char *) &buf) + p[1]);
11623 frac = t % clk_tck;
11624 printf("%um%u.%03us%c",
11625 sec / 60, sec % 60,
11626 (frac * 1000) / clk_tck,
11631 return EXIT_SUCCESS;
11635 #if ENABLE_HUSH_MEMLEAK
11636 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11641 # ifdef M_TRIM_THRESHOLD
11642 /* Optional. Reduces probability of false positives */
11645 /* Crude attempt to find where "free memory" starts,
11646 * sans fragmentation. */
11648 l = (unsigned long)p;
11651 if (l < (unsigned long)p) l = (unsigned long)p;
11657 struct mallinfo mi = mallinfo();
11658 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11659 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11663 if (!G.memleak_value)
11664 G.memleak_value = l;
11666 l -= G.memleak_value;
11673 /* Exitcode is "how many kilobytes we leaked since 1st call" */