1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * make complex ${var%...} constructs support optional
45 * make here documents optional
46 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
50 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
53 * command BLTIN: disables special-ness (e.g. errors do not abort)
54 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
57 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
62 * redirection of stdout+stderr: &> and >&
63 * reserved words: function select
64 * advanced test: [[ ]]
65 * process substitution: <(list) and >(list)
68 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
72 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
74 * $[EXPR]: synonym for $((EXPR))
75 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
79 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
86 * [[ /bin/n* ]]; echo 0:$?
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
93 * add =~ regex match operator: STR =~ REGEX
96 //config: bool "hush (68 kb)"
99 //config: hush is a small shell. It handles the normal flow control
100 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101 //config: case/esac. Redirections, here documents, $((arithmetic))
102 //config: and functions are supported.
104 //config: It will compile and work on no-mmu systems.
106 //config: It does not handle select, aliases, tilde expansion,
107 //config: &>file and >&file redirection of stdout+stderr.
109 //config:config HUSH_BASH_COMPAT
110 //config: bool "bash-compatible extensions"
112 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
114 //config:config HUSH_BRACE_EXPANSION
115 //config: bool "Brace expansion"
117 //config: depends on HUSH_BASH_COMPAT
119 //config: Enable {abc,def} extension.
121 //config:config HUSH_LINENO_VAR
122 //config: bool "$LINENO variable"
124 //config: depends on HUSH_BASH_COMPAT
126 //config:config HUSH_BASH_SOURCE_CURDIR
127 //config: bool "'source' and '.' builtins search current directory after $PATH"
128 //config: default n # do not encourage non-standard behavior
129 //config: depends on HUSH_BASH_COMPAT
131 //config: This is not compliant with standards. Avoid if possible.
133 //config:config HUSH_INTERACTIVE
134 //config: bool "Interactive mode"
136 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
138 //config: Enable interactive mode (prompt and command editing).
139 //config: Without this, hush simply reads and executes commands
140 //config: from stdin just like a shell script from a file.
141 //config: No prompt, no PS1/PS2 magic shell variables.
143 //config:config HUSH_SAVEHISTORY
144 //config: bool "Save command history to .hush_history"
146 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
148 //config:config HUSH_JOB
149 //config: bool "Job control"
151 //config: depends on HUSH_INTERACTIVE
153 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154 //config: command (not entire shell), fg/bg builtins work. Without this option,
155 //config: "cmd &" still works by simply spawning a process and immediately
156 //config: prompting for next command (or executing next command in a script),
157 //config: but no separate process group is formed.
159 //config:config HUSH_TICK
160 //config: bool "Support command substitution"
162 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
164 //config: Enable `command` and $(command).
166 //config:config HUSH_IF
167 //config: bool "Support if/then/elif/else/fi"
169 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
171 //config:config HUSH_LOOPS
172 //config: bool "Support for, while and until loops"
174 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
176 //config:config HUSH_CASE
177 //config: bool "Support case ... esac statement"
179 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
181 //config: Enable case ... esac statement. +400 bytes.
183 //config:config HUSH_FUNCTIONS
184 //config: bool "Support funcname() { commands; } syntax"
186 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
188 //config: Enable support for shell functions. +800 bytes.
190 //config:config HUSH_LOCAL
191 //config: bool "local builtin"
193 //config: depends on HUSH_FUNCTIONS
195 //config: Enable support for local variables in functions.
197 //config:config HUSH_RANDOM_SUPPORT
198 //config: bool "Pseudorandom generator and $RANDOM variable"
200 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
202 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
205 //config:config HUSH_MODE_X
206 //config: bool "Support 'hush -x' option and 'set -x' command"
208 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
210 //config: This instructs hush to print commands before execution.
211 //config: Adds ~300 bytes.
213 //config:config HUSH_ECHO
214 //config: bool "echo builtin"
216 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
218 //config:config HUSH_PRINTF
219 //config: bool "printf builtin"
221 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
223 //config:config HUSH_TEST
224 //config: bool "test builtin"
226 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
228 //config:config HUSH_HELP
229 //config: bool "help builtin"
231 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
233 //config:config HUSH_EXPORT
234 //config: bool "export builtin"
236 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
238 //config:config HUSH_EXPORT_N
239 //config: bool "Support 'export -n' option"
241 //config: depends on HUSH_EXPORT
243 //config: export -n unexports variables. It is a bash extension.
245 //config:config HUSH_READONLY
246 //config: bool "readonly builtin"
248 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
250 //config: Enable support for read-only variables.
252 //config:config HUSH_KILL
253 //config: bool "kill builtin (supports kill %jobspec)"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_WAIT
258 //config: bool "wait builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_COMMAND
263 //config: bool "command builtin"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
267 //config:config HUSH_TRAP
268 //config: bool "trap builtin"
270 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272 //config:config HUSH_TYPE
273 //config: bool "type builtin"
275 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
277 //config:config HUSH_TIMES
278 //config: bool "times builtin"
280 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
282 //config:config HUSH_READ
283 //config: bool "read builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config:config HUSH_SET
288 //config: bool "set builtin"
290 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
292 //config:config HUSH_UNSET
293 //config: bool "unset builtin"
295 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
297 //config:config HUSH_ULIMIT
298 //config: bool "ulimit builtin"
300 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
302 //config:config HUSH_UMASK
303 //config: bool "umask builtin"
305 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
307 //config:config HUSH_GETOPTS
308 //config: bool "getopts builtin"
310 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
312 //config:config HUSH_MEMLEAK
313 //config: bool "memleak builtin (debugging)"
315 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
317 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
318 // APPLET_ODDNAME:name main location suid_type help
319 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
320 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
322 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
323 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
325 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
327 /* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
332 //usage:#define hush_trivial_usage
333 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
334 //usage:#define hush_full_usage "\n\n"
335 //usage: "Unix shell interpreter"
337 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
340 # include <malloc.h> /* for malloc_trim */
343 /* #include <dmalloc.h> */
345 # include <fnmatch.h>
347 #include <sys/times.h>
348 #include <sys/utsname.h> /* for setting $HOSTNAME */
350 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
352 #include "shell_common.h"
355 #if ENABLE_HUSH_RANDOM_SUPPORT
358 # define CLEAR_RANDOM_T(rnd) ((void)0)
363 #ifndef F_DUPFD_CLOEXEC
364 # define F_DUPFD_CLOEXEC F_DUPFD
367 #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
368 # include "embedded_scripts.h"
370 # define NUM_SCRIPTS 0
373 /* So far, all bash compat is controlled by one config option */
374 /* Separate defines document which part of code implements what */
375 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
376 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
377 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
378 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
379 #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
380 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
381 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
385 #define LEAK_HUNTING 0
386 #define BUILD_AS_NOMMU 0
387 /* Enable/disable sanity checks. Ok to enable in production,
388 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
389 * Keeping 1 for now even in released versions.
392 /* Slightly bigger (+200 bytes), but faster hush.
393 * So far it only enables a trick with counting SIGCHLDs and forks,
394 * which allows us to do fewer waitpid's.
395 * (we can detect a case where neither forks were done nor SIGCHLDs happened
396 * and therefore waitpid will return the same result as last time)
398 #define ENABLE_HUSH_FAST 0
399 /* TODO: implement simplified code for users which do not need ${var%...} ops
400 * So far ${var%...} ops are always enabled:
402 #define ENABLE_HUSH_DOLLAR_OPS 1
407 # undef USE_FOR_NOMMU
410 # define USE_FOR_NOMMU(...) __VA_ARGS__
411 # define USE_FOR_MMU(...)
414 #include "NUM_APPLETS.h"
416 /* STANDALONE does not make sense, and won't compile */
417 # undef CONFIG_FEATURE_SH_STANDALONE
418 # undef ENABLE_FEATURE_SH_STANDALONE
419 # undef IF_FEATURE_SH_STANDALONE
420 # undef IF_NOT_FEATURE_SH_STANDALONE
421 # define ENABLE_FEATURE_SH_STANDALONE 0
422 # define IF_FEATURE_SH_STANDALONE(...)
423 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
426 #if !ENABLE_HUSH_INTERACTIVE
427 # undef ENABLE_FEATURE_EDITING
428 # define ENABLE_FEATURE_EDITING 0
429 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
430 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
431 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
432 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
435 /* Do we support ANY keywords? */
436 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
437 # define HAS_KEYWORDS 1
438 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
439 # define IF_HAS_NO_KEYWORDS(...)
441 # define HAS_KEYWORDS 0
442 # define IF_HAS_KEYWORDS(...)
443 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
446 /* If you comment out one of these below, it will be #defined later
447 * to perform debug printfs to stderr: */
448 #define debug_printf(...) do {} while (0)
449 /* Finer-grained debug switches */
450 #define debug_printf_parse(...) do {} while (0)
451 #define debug_printf_heredoc(...) do {} while (0)
452 #define debug_print_tree(a, b) do {} while (0)
453 #define debug_printf_exec(...) do {} while (0)
454 #define debug_printf_env(...) do {} while (0)
455 #define debug_printf_jobs(...) do {} while (0)
456 #define debug_printf_expand(...) do {} while (0)
457 #define debug_printf_varexp(...) do {} while (0)
458 #define debug_printf_glob(...) do {} while (0)
459 #define debug_printf_redir(...) do {} while (0)
460 #define debug_printf_list(...) do {} while (0)
461 #define debug_printf_subst(...) do {} while (0)
462 #define debug_printf_prompt(...) do {} while (0)
463 #define debug_printf_clean(...) do {} while (0)
465 #define ERR_PTR ((void*)(long)1)
467 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
469 #define _SPECIAL_VARS_STR "_*@$!?#-"
470 #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
471 #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
472 #if BASH_PATTERN_SUBST
473 /* Support / and // replace ops */
474 /* Note that // is stored as \ in "encoded" string representation */
475 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
476 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
477 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
479 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
480 # define VAR_SUBST_OPS "%#:-=+?"
481 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
484 #define SPECIAL_VAR_SYMBOL_STR "\3"
485 #define SPECIAL_VAR_SYMBOL 3
486 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
487 #define SPECIAL_VAR_QUOTED_SVS 1
491 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
493 /* This supports saving pointers malloced in vfork child,
494 * to be freed in the parent.
497 typedef struct nommu_save_t {
498 struct variable *old_vars;
500 char **argv_from_re_execing;
513 #if ENABLE_HUSH_LOOPS
520 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
525 /* three pseudo-keywords support contrived "case" syntax: */
526 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
527 RES_MATCH , /* "word)" */
528 RES_CASE_BODY, /* "this command is inside CASE" */
535 typedef struct o_string {
537 int length; /* position where data is appended */
540 /* At least some part of the string was inside '' or "",
541 * possibly empty one: word"", wo''rd etc. */
542 smallint has_quoted_part;
543 smallint has_empty_slot;
544 smallint ended_in_ifs;
547 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
549 /* Protect newly added chars against globbing
550 * by prepending \ to *, ?, [, \ */
551 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
553 /* Used for initialization: o_string foo = NULL_O_STRING; */
554 #define NULL_O_STRING { NULL }
556 #ifndef debug_printf_parse
557 static const char *const assignment_flag[] = {
559 "DEFINITELY_ASSIGNMENT",
565 /* We almost can use standard FILE api, but we need an ability to move
566 * its fd when redirects coincide with it. No api exists for that
567 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
568 * HFILE is our internal alternative. Only supports reading.
569 * Since we now can, we incorporate linked list of all opened HFILEs
570 * into the struct (used to be a separate mini-list).
572 typedef struct HFILE {
575 struct HFILE *next_hfile;
580 typedef struct in_str {
587 /* The descrip member of this structure is only used to make
588 * debugging output pretty */
589 static const struct {
591 signed char default_fd;
594 { O_RDONLY, 0, "<" },
595 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
596 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
597 { O_CREAT|O_RDWR, 1, "<>" },
598 { O_RDONLY, 0, "<<" },
599 /* Should not be needed. Bogus default_fd helps in debugging */
600 /* { O_RDONLY, 77, "<<" }, */
603 struct redir_struct {
604 struct redir_struct *next;
605 char *rd_filename; /* filename */
606 int rd_fd; /* fd to redirect */
607 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
609 smallint rd_type; /* (enum redir_type) */
610 /* note: for heredocs, rd_filename contains heredoc delimiter,
611 * and subsequently heredoc itself; and rd_dup is a bitmask:
612 * bit 0: do we need to trim leading tabs?
613 * bit 1: is heredoc quoted (<<'delim' syntax) ?
616 typedef enum redir_type {
618 REDIRECT_OVERWRITE = 1,
621 REDIRECT_HEREDOC = 4,
622 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
625 REDIRFD_SYNTAX_ERR = -2,
626 REDIRFD_TO_FILE = -1,
627 /* otherwise, rd_fd is redirected to rd_dup */
629 HEREDOC_SKIPTABS = 1,
635 pid_t pid; /* 0 if exited */
636 unsigned assignment_cnt; /* how many argv[i] are assignments? */
637 #if ENABLE_HUSH_LINENO_VAR
640 smallint cmd_type; /* CMD_xxx */
642 #define CMD_SUBSHELL 1
643 #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
644 /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
647 # define CMD_SINGLEWORD_NOGLOB 2
649 #if ENABLE_HUSH_FUNCTIONS
650 # define CMD_FUNCDEF 3
653 smalluint cmd_exitcode;
654 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
657 char *group_as_string;
659 #if ENABLE_HUSH_FUNCTIONS
660 struct function *child_func;
661 /* This field is used to prevent a bug here:
662 * while...do f1() {a;}; f1; f1() {b;}; f1; done
663 * When we execute "f1() {a;}" cmd, we create new function and clear
664 * cmd->group, cmd->group_as_string, cmd->argv[0].
665 * When we execute "f1() {b;}", we notice that f1 exists,
666 * and that its "parent cmd" struct is still "alive",
667 * we put those fields back into cmd->xxx
668 * (struct function has ->parent_cmd ptr to facilitate that).
669 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
670 * Without this trick, loop would execute a;b;b;b;...
671 * instead of correct sequence a;b;a;b;...
672 * When command is freed, it severs the link
673 * (sets ->child_func->parent_cmd to NULL).
676 char **argv; /* command name and arguments */
677 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
678 * and on execution these are substituted with their values.
679 * Substitution can make _several_ words out of one argv[n]!
680 * Example: argv[0]=='.^C*^C.' here: echo .$*.
681 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
683 struct redir_struct *redirects; /* I/O redirections */
685 /* Is there anything in this command at all? */
686 #define IS_NULL_CMD(cmd) \
687 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
691 int num_cmds; /* total number of commands in pipe */
692 int alive_cmds; /* number of commands running (not exited) */
693 int stopped_cmds; /* number of commands alive, but stopped */
695 unsigned jobid; /* job number */
696 pid_t pgrp; /* process group ID for the job */
697 char *cmdtext; /* name of job */
699 struct command *cmds; /* array of commands in pipe */
700 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
701 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
702 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
704 typedef enum pipe_style {
710 /* Is there anything in this pipe at all? */
711 #define IS_NULL_PIPE(pi) \
712 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
714 /* This holds pointers to the various results of parsing */
715 struct parse_context {
716 /* linked list of pipes */
717 struct pipe *list_head;
718 /* last pipe (being constructed right now) */
720 /* last command in pipe (being constructed right now) */
721 struct command *command;
722 /* last redirect in command->redirects list */
723 struct redir_struct *pending_redirect;
728 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
731 smallint ctx_inverted; /* "! cmd | cmd" */
733 smallint ctx_dsemicolon; /* ";;" seen */
735 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
737 /* group we are enclosed in:
738 * example: "if pipe1; pipe2; then pipe3; fi"
739 * when we see "if" or "then", we malloc and copy current context,
740 * and make ->stack point to it. then we parse pipeN.
741 * when closing "then" / fi" / whatever is found,
742 * we move list_head into ->stack->command->group,
743 * copy ->stack into current context, and delete ->stack.
744 * (parsing of { list } and ( list ) doesn't use this method)
746 struct parse_context *stack;
750 MAYBE_ASSIGNMENT = 0,
751 DEFINITELY_ASSIGNMENT = 1,
753 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
757 /* On program start, environ points to initial environment.
758 * putenv adds new pointers into it, unsetenv removes them.
759 * Neither of these (de)allocates the strings.
760 * setenv allocates new strings in malloc space and does putenv,
761 * and thus setenv is unusable (leaky) for shell's purposes */
762 #define setenv(...) setenv_is_leaky_dont_use()
764 struct variable *next;
765 char *varstr; /* points to "name=" portion */
766 int max_len; /* if > 0, name is part of initial env; else name is malloced */
767 uint16_t var_nest_level;
768 smallint flg_export; /* putenv should be done on this var */
769 smallint flg_read_only;
777 #if ENABLE_HUSH_FUNCTIONS
779 struct function *next;
781 struct command *parent_cmd;
784 char *body_as_string;
790 /* set -/+o OPT support. (TODO: make it optional)
791 * bash supports the following opts:
802 * interactive-comments on
820 static const char o_opt_strings[] ALIGN1 =
824 #if ENABLE_HUSH_MODE_X
832 #if ENABLE_HUSH_MODE_X
838 /* "Globals" within this file */
839 /* Sorted roughly by size (smaller offsets == smaller code) */
841 /* interactive_fd != 0 means we are an interactive shell.
842 * If we are, then saved_tty_pgrp can also be != 0, meaning
843 * that controlling tty is available. With saved_tty_pgrp == 0,
844 * job control still works, but terminal signals
845 * (^C, ^Z, ^Y, ^\) won't work at all, and background
846 * process groups can only be created with "cmd &".
847 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
848 * to give tty to the foreground process group,
849 * and will take it back when the group is stopped (^Z)
852 #if ENABLE_HUSH_INTERACTIVE
853 /* 'interactive_fd' is a fd# open to ctty, if we have one
854 * _AND_ if we decided to act interactively */
856 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
857 # define G_interactive_fd (G.interactive_fd)
859 # define G_interactive_fd 0
861 #if ENABLE_FEATURE_EDITING
862 line_input_t *line_input_state;
867 #if ENABLE_HUSH_RANDOM_SUPPORT
873 pid_t saved_tty_pgrp;
874 struct pipe *job_list;
875 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
877 # define G_saved_tty_pgrp 0
879 /* How deeply are we in context where "set -e" is ignored */
881 /* "set -e" rules (do we follow them correctly?):
882 * Exit if pipe, list, or compound command exits with a non-zero status.
883 * Shell does not exit if failed command is part of condition in
884 * if/while, part of && or || list except the last command, any command
885 * in a pipe but the last, or if the command's return value is being
886 * inverted with !. If a compound command other than a subshell returns a
887 * non-zero status because a command failed while -e was being ignored, the
888 * shell does not exit. A trap on ERR, if set, is executed before the shell
889 * exits [ERR is a bashism].
891 * If a compound command or function executes in a context where -e is
892 * ignored, none of the commands executed within are affected by the -e
893 * setting. If a compound command or function sets -e while executing in a
894 * context where -e is ignored, that setting does not have any effect until
895 * the compound command or the command containing the function call completes.
898 char o_opt[NUM_OPT_O];
899 #if ENABLE_HUSH_MODE_X
900 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
906 #if ENABLE_HUSH_INTERACTIVE
907 smallint promptmode; /* 0: PS1, 1: PS2 */
909 smallint flag_SIGINT;
910 #if ENABLE_HUSH_LOOPS
911 smallint flag_break_continue;
913 #if ENABLE_HUSH_FUNCTIONS
914 /* 0: outside of a function (or sourced file)
915 * -1: inside of a function, ok to use return builtin
916 * 1: return is invoked, skip all till end of func
918 smallint flag_return_in_progress;
919 # define G_flag_return_in_progress (G.flag_return_in_progress)
921 # define G_flag_return_in_progress 0
923 smallint exiting; /* used to prevent EXIT trap recursion */
924 /* These support $? */
925 smalluint last_exitcode;
926 smalluint expand_exitcode;
927 smalluint last_bg_pid_exitcode;
929 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
930 smalluint global_args_malloced;
931 # define G_global_args_malloced (G.global_args_malloced)
933 # define G_global_args_malloced 0
935 #if ENABLE_HUSH_BASH_COMPAT
936 int dead_job_exitcode; /* for "wait -n" */
938 /* how many non-NULL argv's we have. NB: $# + 1 */
942 char *argv0_for_re_execing;
944 #if ENABLE_HUSH_LOOPS
945 unsigned depth_break_continue;
946 unsigned depth_of_loop;
948 #if ENABLE_HUSH_GETOPTS
949 unsigned getopt_count;
952 char *ifs_whitespace; /* = G.ifs or malloced */
954 struct variable *top_var;
955 char **expanded_assignments;
956 struct variable **shadowed_vars_pp;
957 unsigned var_nest_level;
958 #if ENABLE_HUSH_FUNCTIONS
959 # if ENABLE_HUSH_LOCAL
960 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
962 struct function *top_func;
964 /* Signal and trap handling */
966 unsigned count_SIGCHLD;
967 unsigned handled_SIGCHLD;
968 smallint we_have_children;
970 #if ENABLE_HUSH_LINENO_VAR
971 unsigned parse_lineno;
972 unsigned execute_lineno;
976 /* Which signals have non-DFL handler (even with no traps set)?
977 * Set at the start to:
978 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
979 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
980 * The rest is cleared right before execv syscalls.
981 * Other than these two times, never modified.
983 unsigned special_sig_mask;
985 unsigned fatal_sig_mask;
986 # define G_fatal_sig_mask (G.fatal_sig_mask)
988 # define G_fatal_sig_mask 0
991 char **traps; /* char *traps[NSIG] */
992 # define G_traps G.traps
994 # define G_traps ((char**)NULL)
996 sigset_t pending_set;
997 #if ENABLE_HUSH_MEMLEAK
998 unsigned long memleak_value;
1000 #if ENABLE_HUSH_MODE_X
1001 unsigned x_mode_depth;
1002 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1003 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1004 * for all subsequent output.
1007 o_string x_mode_buf;
1012 struct sigaction sa;
1013 char optstring_buf[sizeof("eixcs")];
1015 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1017 #if ENABLE_FEATURE_EDITING
1018 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1021 #define G (*ptr_to_globals)
1022 /* Not #defining name to G.name - this quickly gets unwieldy
1023 * (too many defines). Also, I actually prefer to see when a variable
1024 * is global, thus "G." prefix is a useful hint */
1025 #define INIT_G() do { \
1026 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
1027 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1028 sigfillset(&G.sa.sa_mask); \
1029 G.sa.sa_flags = SA_RESTART; \
1033 /* Function prototypes for builtins */
1034 static int builtin_cd(char **argv) FAST_FUNC;
1035 #if ENABLE_HUSH_ECHO
1036 static int builtin_echo(char **argv) FAST_FUNC;
1038 static int builtin_eval(char **argv) FAST_FUNC;
1039 static int builtin_exec(char **argv) FAST_FUNC;
1040 static int builtin_exit(char **argv) FAST_FUNC;
1041 #if ENABLE_HUSH_EXPORT
1042 static int builtin_export(char **argv) FAST_FUNC;
1044 #if ENABLE_HUSH_READONLY
1045 static int builtin_readonly(char **argv) FAST_FUNC;
1048 static int builtin_fg_bg(char **argv) FAST_FUNC;
1049 static int builtin_jobs(char **argv) FAST_FUNC;
1051 #if ENABLE_HUSH_GETOPTS
1052 static int builtin_getopts(char **argv) FAST_FUNC;
1054 #if ENABLE_HUSH_HELP
1055 static int builtin_help(char **argv) FAST_FUNC;
1057 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1058 static int builtin_history(char **argv) FAST_FUNC;
1060 #if ENABLE_HUSH_LOCAL
1061 static int builtin_local(char **argv) FAST_FUNC;
1063 #if ENABLE_HUSH_MEMLEAK
1064 static int builtin_memleak(char **argv) FAST_FUNC;
1066 #if ENABLE_HUSH_PRINTF
1067 static int builtin_printf(char **argv) FAST_FUNC;
1069 static int builtin_pwd(char **argv) FAST_FUNC;
1070 #if ENABLE_HUSH_READ
1071 static int builtin_read(char **argv) FAST_FUNC;
1074 static int builtin_set(char **argv) FAST_FUNC;
1076 static int builtin_shift(char **argv) FAST_FUNC;
1077 static int builtin_source(char **argv) FAST_FUNC;
1078 #if ENABLE_HUSH_TEST || BASH_TEST2
1079 static int builtin_test(char **argv) FAST_FUNC;
1081 #if ENABLE_HUSH_TRAP
1082 static int builtin_trap(char **argv) FAST_FUNC;
1084 #if ENABLE_HUSH_TYPE
1085 static int builtin_type(char **argv) FAST_FUNC;
1087 #if ENABLE_HUSH_TIMES
1088 static int builtin_times(char **argv) FAST_FUNC;
1090 static int builtin_true(char **argv) FAST_FUNC;
1091 #if ENABLE_HUSH_UMASK
1092 static int builtin_umask(char **argv) FAST_FUNC;
1094 #if ENABLE_HUSH_UNSET
1095 static int builtin_unset(char **argv) FAST_FUNC;
1097 #if ENABLE_HUSH_KILL
1098 static int builtin_kill(char **argv) FAST_FUNC;
1100 #if ENABLE_HUSH_WAIT
1101 static int builtin_wait(char **argv) FAST_FUNC;
1103 #if ENABLE_HUSH_LOOPS
1104 static int builtin_break(char **argv) FAST_FUNC;
1105 static int builtin_continue(char **argv) FAST_FUNC;
1107 #if ENABLE_HUSH_FUNCTIONS
1108 static int builtin_return(char **argv) FAST_FUNC;
1111 /* Table of built-in functions. They can be forked or not, depending on
1112 * context: within pipes, they fork. As simple commands, they do not.
1113 * When used in non-forking context, they can change global variables
1114 * in the parent shell process. If forked, of course they cannot.
1115 * For example, 'unset foo | whatever' will parse and run, but foo will
1116 * still be set at the end. */
1117 struct built_in_command {
1119 int (*b_function)(char **argv) FAST_FUNC;
1120 #if ENABLE_HUSH_HELP
1121 const char *b_descr;
1122 # define BLTIN(cmd, func, help) { cmd, func, help }
1124 # define BLTIN(cmd, func, help) { cmd, func }
1128 static const struct built_in_command bltins1[] = {
1129 BLTIN("." , builtin_source , "Run commands in file"),
1130 BLTIN(":" , builtin_true , NULL),
1132 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1134 #if ENABLE_HUSH_LOOPS
1135 BLTIN("break" , builtin_break , "Exit loop"),
1137 BLTIN("cd" , builtin_cd , "Change directory"),
1138 #if ENABLE_HUSH_LOOPS
1139 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1141 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1142 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1143 BLTIN("exit" , builtin_exit , NULL),
1144 #if ENABLE_HUSH_EXPORT
1145 BLTIN("export" , builtin_export , "Set environment variables"),
1148 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1150 #if ENABLE_HUSH_GETOPTS
1151 BLTIN("getopts" , builtin_getopts , NULL),
1153 #if ENABLE_HUSH_HELP
1154 BLTIN("help" , builtin_help , NULL),
1156 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1157 BLTIN("history" , builtin_history , "Show history"),
1160 BLTIN("jobs" , builtin_jobs , "List jobs"),
1162 #if ENABLE_HUSH_KILL
1163 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1165 #if ENABLE_HUSH_LOCAL
1166 BLTIN("local" , builtin_local , "Set local variables"),
1168 #if ENABLE_HUSH_MEMLEAK
1169 BLTIN("memleak" , builtin_memleak , NULL),
1171 #if ENABLE_HUSH_READ
1172 BLTIN("read" , builtin_read , "Input into variable"),
1174 #if ENABLE_HUSH_READONLY
1175 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1177 #if ENABLE_HUSH_FUNCTIONS
1178 BLTIN("return" , builtin_return , "Return from function"),
1181 BLTIN("set" , builtin_set , "Set positional parameters"),
1183 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1185 BLTIN("source" , builtin_source , NULL),
1187 #if ENABLE_HUSH_TIMES
1188 BLTIN("times" , builtin_times , NULL),
1190 #if ENABLE_HUSH_TRAP
1191 BLTIN("trap" , builtin_trap , "Trap signals"),
1193 BLTIN("true" , builtin_true , NULL),
1194 #if ENABLE_HUSH_TYPE
1195 BLTIN("type" , builtin_type , "Show command type"),
1197 #if ENABLE_HUSH_ULIMIT
1198 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1200 #if ENABLE_HUSH_UMASK
1201 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1203 #if ENABLE_HUSH_UNSET
1204 BLTIN("unset" , builtin_unset , "Unset variables"),
1206 #if ENABLE_HUSH_WAIT
1207 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1210 /* These builtins won't be used if we are on NOMMU and need to re-exec
1211 * (it's cheaper to run an external program in this case):
1213 static const struct built_in_command bltins2[] = {
1214 #if ENABLE_HUSH_TEST
1215 BLTIN("[" , builtin_test , NULL),
1218 BLTIN("[[" , builtin_test , NULL),
1220 #if ENABLE_HUSH_ECHO
1221 BLTIN("echo" , builtin_echo , NULL),
1223 #if ENABLE_HUSH_PRINTF
1224 BLTIN("printf" , builtin_printf , NULL),
1226 BLTIN("pwd" , builtin_pwd , NULL),
1227 #if ENABLE_HUSH_TEST
1228 BLTIN("test" , builtin_test , NULL),
1236 /* prevent disasters with G.debug_indent < 0 */
1237 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1238 # define debug_enter() (G.debug_indent++)
1239 # define debug_leave() (G.debug_indent--)
1241 # define indent() ((void)0)
1242 # define debug_enter() ((void)0)
1243 # define debug_leave() ((void)0)
1246 #ifndef debug_printf
1247 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1250 #ifndef debug_printf_parse
1251 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1254 #ifndef debug_printf_heredoc
1255 # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1258 #ifndef debug_printf_exec
1259 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1262 #ifndef debug_printf_env
1263 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1266 #ifndef debug_printf_jobs
1267 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1268 # define DEBUG_JOBS 1
1270 # define DEBUG_JOBS 0
1273 #ifndef debug_printf_expand
1274 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1275 # define DEBUG_EXPAND 1
1277 # define DEBUG_EXPAND 0
1280 #ifndef debug_printf_varexp
1281 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1284 #ifndef debug_printf_glob
1285 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1286 # define DEBUG_GLOB 1
1288 # define DEBUG_GLOB 0
1291 #ifndef debug_printf_redir
1292 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1295 #ifndef debug_printf_list
1296 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1299 #ifndef debug_printf_subst
1300 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1303 #ifndef debug_printf_prompt
1304 # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1307 #ifndef debug_printf_clean
1308 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1309 # define DEBUG_CLEAN 1
1311 # define DEBUG_CLEAN 0
1315 static void debug_print_strings(const char *prefix, char **vv)
1318 fdprintf(2, "%s:\n", prefix);
1320 fdprintf(2, " '%s'\n", *vv++);
1323 # define debug_print_strings(prefix, vv) ((void)0)
1327 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1330 static void *xxmalloc(int lineno, size_t size)
1332 void *ptr = xmalloc((size + 0xff) & ~0xff);
1333 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1336 static void *xxrealloc(int lineno, void *ptr, size_t size)
1338 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1339 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1342 static char *xxstrdup(int lineno, const char *str)
1344 char *ptr = xstrdup(str);
1345 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1348 static void xxfree(void *ptr)
1350 fdprintf(2, "free %p\n", ptr);
1353 # define xmalloc(s) xxmalloc(__LINE__, s)
1354 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1355 # define xstrdup(s) xxstrdup(__LINE__, s)
1356 # define free(p) xxfree(p)
1360 /* Syntax and runtime errors. They always abort scripts.
1361 * In interactive use they usually discard unparsed and/or unexecuted commands
1362 * and return to the prompt.
1363 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1366 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1367 # define syntax_error(lineno, msg) syntax_error(msg)
1368 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1369 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1370 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1371 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1374 static void die_if_script(void)
1376 if (!G_interactive_fd) {
1377 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1378 xfunc_error_retval = G.last_exitcode;
1383 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1388 bb_error_msg("hush.c:%u", lineno);
1391 bb_verror_msg(fmt, p, NULL);
1396 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1399 bb_error_msg("syntax error: %s", msg);
1401 bb_simple_error_msg("syntax error");
1405 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1407 bb_error_msg("syntax error at '%s'", msg);
1411 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1413 bb_error_msg("syntax error: unterminated %s", s);
1414 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1418 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1420 char msg[2] = { ch, '\0' };
1421 syntax_error_unterm_str(lineno, msg);
1424 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1430 bb_error_msg("hush.c:%u", lineno);
1432 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1437 # undef msg_and_die_if_script
1438 # undef syntax_error
1439 # undef syntax_error_at
1440 # undef syntax_error_unterm_ch
1441 # undef syntax_error_unterm_str
1442 # undef syntax_error_unexpected_ch
1444 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1445 # define syntax_error(msg) syntax_error(__LINE__, msg)
1446 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1447 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1448 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1449 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1453 /* Utility functions
1455 /* Replace each \x with x in place, return ptr past NUL. */
1456 static char *unbackslash(char *src)
1458 char *dst = src = strchrnul(src, '\\');
1467 /* else: "\<nul>". Do not delete this backslash.
1468 * Testcase: eval 'echo ok\'
1473 if ((*dst++ = *src++) == '\0')
1479 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1500 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1501 v[count1 + count2] = NULL;
1504 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1508 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1510 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1511 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1514 #define add_strings_to_strings(strings, add, need_to_dup) \
1515 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1518 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1519 static char **add_string_to_strings(char **strings, char *add)
1524 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1527 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1529 char **ptr = add_string_to_strings(strings, add);
1530 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1533 #define add_string_to_strings(strings, add) \
1534 xx_add_string_to_strings(__LINE__, strings, add)
1537 static void free_strings(char **strings)
1551 static int dup_CLOEXEC(int fd, int avoid_fd)
1555 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1557 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1558 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1559 } else { /* newfd < 0 */
1568 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1572 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1578 /* fd was not open? */
1583 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1584 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1590 /* Manipulating HFILEs */
1591 static HFILE *hfopen(const char *name)
1598 fd = open(name, O_RDONLY | O_CLOEXEC);
1601 if (O_CLOEXEC == 0) /* ancient libc */
1602 close_on_exec_on(fd);
1605 fp = xmalloc(sizeof(*fp));
1609 fp->cur = fp->end = fp->buf;
1610 fp->next_hfile = G.HFILE_list;
1614 static void hfclose(HFILE *fp)
1616 HFILE **pp = &G.HFILE_list;
1620 *pp = cur->next_hfile;
1623 pp = &cur->next_hfile;
1629 static int refill_HFILE_and_getc(HFILE *fp)
1634 /* Already saw EOF */
1637 /* Try to buffer more input */
1639 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1641 bb_simple_perror_msg("read error");
1644 fp->end = fp->buf + n;
1651 return (unsigned char)(*fp->cur++);
1653 /* Inlined for common case of non-empty buffer.
1655 static ALWAYS_INLINE int hfgetc(HFILE *fp)
1657 if (fp->cur < fp->end)
1658 return (unsigned char)(*fp->cur++);
1660 return refill_HFILE_and_getc(fp);
1662 static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1664 HFILE *fl = G.HFILE_list;
1667 /* We use it only on script files, they are all CLOEXEC */
1668 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1669 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1670 return 1; /* "found and moved" */
1672 fl = fl->next_hfile;
1674 #if ENABLE_HUSH_MODE_X
1675 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1676 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1677 return 1; /* "found and moved" */
1680 return 0; /* "not in the list" */
1682 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1683 static void close_all_HFILE_list(void)
1685 HFILE *fl = G.HFILE_list;
1687 /* hfclose would also free HFILE object.
1688 * It is disastrous if we share memory with a vforked parent.
1689 * I'm not sure we never come here after vfork.
1690 * Therefore just close fd, nothing more.
1692 * ">" instead of ">=": we don't close fd#0,
1693 * interactive shell uses hfopen(NULL) as stdin input
1694 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1695 * If we'd close it here, then e.g. interactive "set | sort"
1696 * with NOFORKed sort, would have sort's input fd closed.
1699 /*hfclose(fl); - unsafe */
1701 fl = fl->next_hfile;
1705 static int fd_in_HFILEs(int fd)
1707 HFILE *fl = G.HFILE_list;
1711 fl = fl->next_hfile;
1717 /* Helpers for setting new $n and restoring them back
1719 typedef struct save_arg_t {
1723 IF_HUSH_SET(smallint sv_g_malloced;)
1726 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1728 sv->sv_argv0 = argv[0];
1729 sv->sv_g_argv = G.global_argv;
1730 sv->sv_g_argc = G.global_argc;
1731 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1733 argv[0] = G.global_argv[0]; /* retain $0 */
1734 G.global_argv = argv;
1735 IF_HUSH_SET(G.global_args_malloced = 0;)
1737 G.global_argc = 1 + string_array_len(argv + 1);
1740 static void restore_G_args(save_arg_t *sv, char **argv)
1743 if (G.global_args_malloced) {
1744 /* someone ran "set -- arg1 arg2 ...", undo */
1745 char **pp = G.global_argv;
1746 while (*++pp) /* note: does not free $0 */
1748 free(G.global_argv);
1751 argv[0] = sv->sv_argv0;
1752 G.global_argv = sv->sv_g_argv;
1753 G.global_argc = sv->sv_g_argc;
1754 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1758 /* Basic theory of signal handling in shell
1759 * ========================================
1760 * This does not describe what hush does, rather, it is current understanding
1761 * what it _should_ do. If it doesn't, it's a bug.
1762 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1764 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1765 * is finished or backgrounded. It is the same in interactive and
1766 * non-interactive shells, and is the same regardless of whether
1767 * a user trap handler is installed or a shell special one is in effect.
1768 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1769 * backgrounds (i.e. stops) or kills all members of currently running
1772 * Wait builtin is interruptible by signals for which user trap is set
1773 * or by SIGINT in interactive shell.
1775 * Trap handlers will execute even within trap handlers. (right?)
1777 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1778 * except for handlers set to '' (empty string).
1780 * If job control is off, backgrounded commands ("cmd &")
1781 * have SIGINT, SIGQUIT set to SIG_IGN.
1783 * Commands which are run in command substitution ("`cmd`")
1784 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1786 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1787 * by the shell from its parent.
1789 * Signals which differ from SIG_DFL action
1790 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1793 * SIGTERM (interactive): ignore
1794 * SIGHUP (interactive):
1795 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1796 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1797 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1798 * that all pipe members are stopped. Try this in bash:
1799 * while :; do :; done - ^Z does not background it
1800 * (while :; do :; done) - ^Z backgrounds it
1801 * SIGINT (interactive): wait for last pipe, ignore the rest
1802 * of the command line, show prompt. NB: ^C does not send SIGINT
1803 * to interactive shell while shell is waiting for a pipe,
1804 * since shell is bg'ed (is not in foreground process group).
1805 * Example 1: this waits 5 sec, but does not execute ls:
1806 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1807 * Example 2: this does not wait and does not execute ls:
1808 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1809 * Example 3: this does not wait 5 sec, but executes ls:
1810 * "sleep 5; ls -l" + press ^C
1811 * Example 4: this does not wait and does not execute ls:
1812 * "sleep 5 & wait; ls -l" + press ^C
1814 * (What happens to signals which are IGN on shell start?)
1815 * (What happens with signal mask on shell start?)
1817 * Old implementation
1818 * ==================
1819 * We use in-kernel pending signal mask to determine which signals were sent.
1820 * We block all signals which we don't want to take action immediately,
1821 * i.e. we block all signals which need to have special handling as described
1822 * above, and all signals which have traps set.
1823 * After each pipe execution, we extract any pending signals via sigtimedwait()
1826 * unsigned special_sig_mask: a mask of such "special" signals
1827 * sigset_t blocked_set: current blocked signal set
1830 * clear bit in blocked_set unless it is also in special_sig_mask
1831 * "trap 'cmd' SIGxxx":
1832 * set bit in blocked_set (even if 'cmd' is '')
1833 * after [v]fork, if we plan to be a shell:
1834 * unblock signals with special interactive handling
1835 * (child shell is not interactive),
1836 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1837 * after [v]fork, if we plan to exec:
1838 * POSIX says fork clears pending signal mask in child - no need to clear it.
1839 * Restore blocked signal set to one inherited by shell just prior to exec.
1841 * Note: as a result, we do not use signal handlers much. The only uses
1842 * are to count SIGCHLDs
1843 * and to restore tty pgrp on signal-induced exit.
1846 * Standard says "When a subshell is entered, traps that are not being ignored
1847 * are set to the default actions". bash interprets it so that traps which
1848 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1850 * Problem: the above approach makes it unwieldy to catch signals while
1851 * we are in read builtin, or while we read commands from stdin:
1852 * masked signals are not visible!
1854 * New implementation
1855 * ==================
1856 * We record each signal we are interested in by installing signal handler
1857 * for them - a bit like emulating kernel pending signal mask in userspace.
1858 * We are interested in: signals which need to have special handling
1859 * as described above, and all signals which have traps set.
1860 * Signals are recorded in pending_set.
1861 * After each pipe execution, we extract any pending signals
1864 * unsigned special_sig_mask: a mask of shell-special signals.
1865 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1866 * char *traps[sig] if trap for sig is set (even if it's '').
1867 * sigset_t pending_set: set of sigs we received.
1870 * if sig is in special_sig_mask, set handler back to:
1871 * record_pending_signo, or to IGN if it's a tty stop signal
1872 * if sig is in fatal_sig_mask, set handler back to sigexit.
1873 * else: set handler back to SIG_DFL
1874 * "trap 'cmd' SIGxxx":
1875 * set handler to record_pending_signo.
1877 * set handler to SIG_IGN.
1878 * after [v]fork, if we plan to be a shell:
1879 * set signals with special interactive handling to SIG_DFL
1880 * (because child shell is not interactive),
1881 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1882 * after [v]fork, if we plan to exec:
1883 * POSIX says fork clears pending signal mask in child - no need to clear it.
1885 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1886 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1889 * Standard says "When a subshell is entered, traps that are not being ignored
1890 * are set to the default actions". bash interprets it so that traps which
1891 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1894 SPECIAL_INTERACTIVE_SIGS = 0
1899 SPECIAL_JOBSTOP_SIGS = 0
1908 static void record_pending_signo(int sig)
1910 sigaddset(&G.pending_set, sig);
1911 #if ENABLE_HUSH_FAST
1912 if (sig == SIGCHLD) {
1914 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1919 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1921 struct sigaction old_sa;
1923 /* We could use signal() to install handlers... almost:
1924 * except that we need to mask ALL signals while handlers run.
1925 * I saw signal nesting in strace, race window isn't small.
1926 * SA_RESTART is also needed, but in Linux, signal()
1927 * sets SA_RESTART too.
1929 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1930 /* sigfillset(&G.sa.sa_mask); - already done */
1931 /* G.sa.sa_flags = SA_RESTART; - already done */
1932 G.sa.sa_handler = handler;
1933 sigaction(sig, &G.sa, &old_sa);
1934 return old_sa.sa_handler;
1937 static void hush_exit(int exitcode) NORETURN;
1939 static void restore_ttypgrp_and__exit(void) NORETURN;
1940 static void restore_ttypgrp_and__exit(void)
1942 /* xfunc has failed! die die die */
1943 /* no EXIT traps, this is an escape hatch! */
1945 hush_exit(xfunc_error_retval);
1950 /* Needed only on some libc:
1951 * It was observed that on exit(), fgetc'ed buffered data
1952 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1953 * With the net effect that even after fork(), not vfork(),
1954 * exit() in NOEXECed applet in "sh SCRIPT":
1955 * noexec_applet_here
1956 * echo END_OF_SCRIPT
1957 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1958 * This makes "echo END_OF_SCRIPT" executed twice.
1959 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1960 * and in `cmd` handling.
1961 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1963 static void fflush_and__exit(void) NORETURN;
1964 static void fflush_and__exit(void)
1967 _exit(xfunc_error_retval);
1970 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1971 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1972 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1973 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1975 /* Restores tty foreground process group, and exits.
1976 * May be called as signal handler for fatal signal
1977 * (will resend signal to itself, producing correct exit state)
1978 * or called directly with -EXITCODE.
1979 * We also call it if xfunc is exiting.
1981 static void sigexit(int sig) NORETURN;
1982 static void sigexit(int sig)
1984 /* Careful: we can end up here after [v]fork. Do not restore
1985 * tty pgrp then, only top-level shell process does that */
1986 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1987 /* Disable all signals: job control, SIGPIPE, etc.
1988 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1990 sigprocmask_allsigs(SIG_BLOCK);
1991 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1994 /* Not a signal, just exit */
1998 kill_myself_with_sig(sig); /* does not return */
2002 # define disable_restore_tty_pgrp_on_exit() ((void)0)
2003 # define enable_restore_tty_pgrp_on_exit() ((void)0)
2007 static sighandler_t pick_sighandler(unsigned sig)
2009 sighandler_t handler = SIG_DFL;
2010 if (sig < sizeof(unsigned)*8) {
2011 unsigned sigmask = (1 << sig);
2015 if (G_fatal_sig_mask & sigmask)
2019 /* sig has special handling? */
2020 if (G.special_sig_mask & sigmask) {
2021 handler = record_pending_signo;
2022 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
2023 * in order to ignore them: they will be raised
2024 * in an endless loop when we try to do some
2025 * terminal ioctls! We do have to _ignore_ these.
2027 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2034 /* Restores tty foreground process group, and exits. */
2035 static void hush_exit(int exitcode)
2037 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2038 if (G.line_input_state)
2039 save_history(G.line_input_state);
2043 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
2045 /* argv[0] is unused */
2046 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
2048 G.exiting = 1; /* prevent EXIT trap recursion */
2049 /* Note: G_traps[0] is not cleared!
2050 * "trap" will still show it, if executed
2055 #if ENABLE_FEATURE_CLEAN_UP
2057 struct variable *cur_var;
2058 if (G.cwd != bb_msg_unknown)
2060 cur_var = G.top_var;
2062 struct variable *tmp = cur_var;
2063 if (!cur_var->max_len)
2064 free(cur_var->varstr);
2065 cur_var = cur_var->next;
2073 sigexit(- (exitcode & 0xff));
2080 //TODO: return a mask of ALL handled sigs?
2081 static int check_and_run_traps(void)
2088 if (sigisemptyset(&G.pending_set))
2093 if (sigismember(&G.pending_set, sig)) {
2094 sigdelset(&G.pending_set, sig);
2097 } while (sig < NSIG);
2100 if (G_traps && G_traps[sig]) {
2101 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
2102 if (G_traps[sig][0]) {
2103 /* We have user-defined handler */
2104 smalluint save_rcode;
2106 /* argv[0] is unused */
2107 argv[1] = xstrdup(G_traps[sig]);
2108 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
2110 save_rcode = G.last_exitcode;
2113 //FIXME: shouldn't it be set to 128 + sig instead?
2114 G.last_exitcode = save_rcode;
2116 } /* else: "" trap, ignoring signal */
2119 /* not a trap: special action */
2122 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2128 //TODO: why are we doing this? ash and dash don't do this,
2129 //they have no handler for SIGHUP at all,
2130 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2132 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2133 /* bash is observed to signal whole process groups,
2134 * not individual processes */
2135 for (job = G.job_list; job; job = job->next) {
2138 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2139 if (kill(- job->pgrp, SIGHUP) == 0)
2140 kill(- job->pgrp, SIGCONT);
2145 #if ENABLE_HUSH_FAST
2147 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2149 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2151 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2152 * This simplifies wait builtin a bit.
2156 default: /* ignored: */
2157 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2158 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2160 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2161 * Example: wait is not interrupted by TERM
2162 * in interactive shell, because TERM is ignored.
2171 static const char *get_cwd(int force)
2173 if (force || G.cwd == NULL) {
2174 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2175 * we must not try to free(bb_msg_unknown) */
2176 if (G.cwd == bb_msg_unknown)
2178 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2180 G.cwd = bb_msg_unknown;
2187 * Shell and environment variable support
2189 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2191 struct variable **pp;
2192 struct variable *cur;
2195 while ((cur = *pp) != NULL) {
2196 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2203 static const char* FAST_FUNC get_local_var_value(const char *name)
2205 struct variable **vpp;
2206 unsigned len = strlen(name);
2208 if (G.expanded_assignments) {
2209 char **cpp = G.expanded_assignments;
2212 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2213 return cp + len + 1;
2218 vpp = get_ptr_to_local_var(name, len);
2220 return (*vpp)->varstr + len + 1;
2222 if (strcmp(name, "PPID") == 0)
2223 return utoa(G.root_ppid);
2224 // bash compat: UID? EUID?
2225 #if ENABLE_HUSH_RANDOM_SUPPORT
2226 if (strcmp(name, "RANDOM") == 0)
2227 return utoa(next_random(&G.random_gen));
2229 #if ENABLE_HUSH_LINENO_VAR
2230 if (strcmp(name, "LINENO") == 0)
2231 return utoa(G.execute_lineno);
2235 const char *fmt = NULL;
2236 if (strcmp(name, "EPOCHSECONDS") == 0)
2238 else if (strcmp(name, "EPOCHREALTIME") == 0)
2242 gettimeofday(&tv, NULL);
2243 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2244 (unsigned)tv.tv_usec);
2252 #if ENABLE_HUSH_GETOPTS
2253 static void handle_changed_special_names(const char *name, unsigned name_len)
2255 if (name_len == 6) {
2256 if (strncmp(name, "OPTIND", 6) == 0) {
2263 /* Do not even bother evaluating arguments */
2264 # define handle_changed_special_names(...) ((void)0)
2267 /* str holds "NAME=VAL" and is expected to be malloced.
2268 * We take ownership of it.
2270 #define SETFLAG_EXPORT (1 << 0)
2271 #define SETFLAG_UNEXPORT (1 << 1)
2272 #define SETFLAG_MAKE_RO (1 << 2)
2273 #define SETFLAG_VARLVL_SHIFT 3
2274 static int set_local_var(char *str, unsigned flags)
2276 struct variable **cur_pp;
2277 struct variable *cur;
2278 char *free_me = NULL;
2282 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
2284 eq_sign = strchr(str, '=');
2285 if (HUSH_DEBUG && !eq_sign)
2286 bb_simple_error_msg_and_die("BUG in setvar");
2288 name_len = eq_sign - str + 1; /* including '=' */
2289 cur_pp = &G.top_var;
2290 while ((cur = *cur_pp) != NULL) {
2291 if (strncmp(cur->varstr, str, name_len) != 0) {
2292 cur_pp = &cur->next;
2296 /* We found an existing var with this name */
2297 if (cur->flg_read_only) {
2298 bb_error_msg("%s: readonly variable", str);
2300 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2301 //but export per se succeeds (does put the var in env). We don't mimic that.
2304 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2305 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2310 if (cur->var_nest_level < local_lvl) {
2311 /* bash 3.2.33(1) and exported vars:
2313 * # f() { local z=a; env | grep ^z; }
2319 if (cur->flg_export)
2320 flags |= SETFLAG_EXPORT;
2321 /* New variable is local ("local VAR=VAL" or
2323 * and existing one is global, or local
2324 * on a lower level that new one.
2325 * Remove it from global variable list:
2327 *cur_pp = cur->next;
2328 if (G.shadowed_vars_pp) {
2329 /* Save in "shadowed" list */
2330 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2331 cur->flg_export ? "exported " : "",
2332 cur->varstr, cur->var_nest_level, str, local_lvl
2334 cur->next = *G.shadowed_vars_pp;
2335 *G.shadowed_vars_pp = cur;
2337 /* Came from pseudo_exec_argv(), no need to save: delete it */
2338 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2339 cur->flg_export ? "exported " : "",
2340 cur->varstr, cur->var_nest_level, str, local_lvl
2342 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2343 free_me = cur->varstr; /* then free it later */
2349 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2350 debug_printf_env("assignement '%s' does not change anything\n", str);
2356 /* Replace the value in the found "struct variable" */
2357 if (cur->max_len != 0) {
2358 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
2359 /* This one is from startup env, reuse space */
2360 debug_printf_env("reusing startup env for '%s'\n", str);
2361 strcpy(cur->varstr, str);
2366 goto set_str_and_exp;
2368 /* max_len == 0 signifies "malloced" var, which we can
2369 * (and have to) free. But we can't free(cur->varstr) here:
2370 * if cur->flg_export is 1, it is in the environment.
2371 * We should either unsetenv+free, or wait until putenv,
2372 * then putenv(new)+free(old).
2374 free_me = cur->varstr;
2375 goto set_str_and_exp;
2378 /* Not found or shadowed - create new variable struct */
2379 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
2380 cur = xzalloc(sizeof(*cur));
2381 cur->var_nest_level = local_lvl;
2382 cur->next = *cur_pp;
2388 #if !BB_MMU || ENABLE_HUSH_READONLY
2389 if (flags & SETFLAG_MAKE_RO) {
2390 cur->flg_read_only = 1;
2393 if (flags & SETFLAG_EXPORT)
2394 cur->flg_export = 1;
2396 if (cur->flg_export) {
2397 if (flags & SETFLAG_UNEXPORT) {
2398 cur->flg_export = 0;
2399 /* unsetenv was already done */
2401 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
2402 retval = putenv(cur->varstr);
2403 /* fall through to "free(free_me)" -
2404 * only now we can free old exported malloced string
2410 handle_changed_special_names(cur->varstr, name_len - 1);
2415 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2417 char *var = xasprintf("%s=%s", name, val);
2418 set_local_var(var, /*flag:*/ 0);
2421 /* Used at startup and after each cd */
2422 static void set_pwd_var(unsigned flag)
2424 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2427 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2428 static int unset_local_var_len(const char *name, int name_len)
2430 struct variable *cur;
2431 struct variable **cur_pp;
2433 cur_pp = &G.top_var;
2434 while ((cur = *cur_pp) != NULL) {
2435 if (strncmp(cur->varstr, name, name_len) == 0
2436 && cur->varstr[name_len] == '='
2438 if (cur->flg_read_only) {
2439 bb_error_msg("%s: readonly variable", name);
2440 return EXIT_FAILURE;
2443 *cur_pp = cur->next;
2444 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2445 bb_unsetenv(cur->varstr);
2452 cur_pp = &cur->next;
2455 /* Handle "unset LINENO" et al even if did not find the variable to unset */
2456 handle_changed_special_names(name, name_len);
2458 return EXIT_SUCCESS;
2461 static int unset_local_var(const char *name)
2463 return unset_local_var_len(name, strlen(name));
2469 * Helpers for "var1=val1 var2=val2 cmd" feature
2471 static void add_vars(struct variable *var)
2473 struct variable *next;
2477 var->next = G.top_var;
2479 if (var->flg_export) {
2480 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2481 putenv(var->varstr);
2483 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
2489 /* We put strings[i] into variable table and possibly putenv them.
2490 * If variable is read only, we can free the strings[i]
2491 * which attempts to overwrite it.
2492 * The strings[] vector itself is freed.
2494 static void set_vars_and_save_old(char **strings)
2503 struct variable *var_p;
2504 struct variable **var_pp;
2507 eq = strchr(*s, '=');
2508 if (HUSH_DEBUG && !eq)
2509 bb_simple_error_msg_and_die("BUG in varexp4");
2510 var_pp = get_ptr_to_local_var(*s, eq - *s);
2513 if (var_p->flg_read_only) {
2515 bb_error_msg("%s: readonly variable", *s);
2517 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2518 * If VAR is readonly, leaving it in the list
2519 * after asssignment error (msg above)
2520 * causes doubled error message later, on unset.
2522 debug_printf_env("removing/freeing '%s' element\n", *s);
2525 do { *p = p[1]; p++; } while (*p);
2528 /* below, set_local_var() with nest level will
2529 * "shadow" (remove) this variable from
2530 * global linked list.
2533 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2534 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2545 static void reinit_unicode_for_hush(void)
2547 /* Unicode support should be activated even if LANG is set
2548 * _during_ shell execution, not only if it was set when
2549 * shell was started. Therefore, re-check LANG every time:
2551 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2552 || ENABLE_UNICODE_USING_LOCALE
2554 const char *s = get_local_var_value("LC_ALL");
2555 if (!s) s = get_local_var_value("LC_CTYPE");
2556 if (!s) s = get_local_var_value("LANG");
2562 * in_str support (strings, and "strings" read from files).
2565 #if ENABLE_HUSH_INTERACTIVE
2566 /* To test correct lineedit/interactive behavior, type from command line:
2572 * It exercises a lot of corner cases.
2574 static const char *setup_prompt_string(void)
2576 const char *prompt_str;
2578 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
2580 # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2581 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2585 prompt_str = "> "; /* if PS2, else... */
2586 if (G.promptmode == 0) { /* PS1 */
2587 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2589 /* bash uses $PWD value, even if it is set by user.
2590 * It uses current dir only if PWD is unset.
2591 * We always use current dir. */
2592 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2595 debug_printf("prompt_str '%s'\n", prompt_str);
2598 static int get_user_input(struct in_str *i)
2601 const char *prompt_str;
2603 prompt_str = setup_prompt_string();
2604 # if ENABLE_FEATURE_EDITING
2606 reinit_unicode_for_hush();
2607 if (G.flag_SIGINT) {
2608 /* There was ^C'ed, make it look prettier: */
2612 /* buglet: SIGINT will not make new prompt to appear _at once_,
2613 * only after <Enter>. (^C works immediately) */
2614 r = read_line_input(G.line_input_state, prompt_str,
2615 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2617 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2620 check_and_run_traps();
2621 if (r != 0 && !G.flag_SIGINT)
2623 /* ^C or SIGINT: repeat */
2624 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2625 write(STDOUT_FILENO, "^C", 2);
2626 G.last_exitcode = 128 + SIGINT;
2629 /* EOF/error detected */
2631 i->peek_buf[0] = r = EOF;
2634 i->p = G.user_input_buf;
2635 return (unsigned char)*i->p++;
2639 if (i->last_char == '\0' || i->last_char == '\n') {
2640 /* Why check_and_run_traps here? Try this interactively:
2641 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2642 * $ <[enter], repeatedly...>
2643 * Without check_and_run_traps, handler never runs.
2645 check_and_run_traps();
2646 fputs(prompt_str, stdout);
2649 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2650 r = hfgetc(i->file);
2651 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2652 * no ^C masking happens during fgetc, no special code for ^C:
2653 * it generates SIGINT as usual.
2655 check_and_run_traps();
2657 G.last_exitcode = 128 + SIGINT;
2664 /* This is the magic location that prints prompts
2665 * and gets data back from the user */
2666 static int fgetc_interactive(struct in_str *i)
2669 /* If it's interactive stdin, get new line. */
2670 if (G_interactive_fd && i->file == G.HFILE_stdin) {
2671 /* Returns first char (or EOF), the rest is in i->p[] */
2672 ch = get_user_input(i);
2673 G.promptmode = 1; /* PS2 */
2674 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
2676 /* Not stdin: script file, sourced file, etc */
2677 do ch = hfgetc(i->file); while (ch == '\0');
2682 static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
2685 do ch = hfgetc(i->file); while (ch == '\0');
2688 #endif /* INTERACTIVE */
2690 static int i_getch(struct in_str *i)
2695 /* string-based in_str */
2696 ch = (unsigned char)*i->p;
2705 /* FILE-based in_str */
2707 #if ENABLE_FEATURE_EDITING
2708 /* This can be stdin, check line editing char[] buffer */
2709 if (i->p && *i->p != '\0') {
2710 ch = (unsigned char)*i->p++;
2714 /* peek_buf[] is an int array, not char. Can contain EOF. */
2715 ch = i->peek_buf[0];
2717 int ch2 = i->peek_buf[1];
2718 i->peek_buf[0] = ch2;
2719 if (ch2 == 0) /* very likely, avoid redundant write */
2725 ch = fgetc_interactive(i);
2727 debug_printf("file_get: got '%c' %d\n", ch, ch);
2729 #if ENABLE_HUSH_LINENO_VAR
2732 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
2738 static int i_peek(struct in_str *i)
2743 /* string-based in_str */
2744 /* Doesn't report EOF on NUL. None of the callers care. */
2745 return (unsigned char)*i->p;
2748 /* FILE-based in_str */
2750 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2751 /* This can be stdin, check line editing char[] buffer */
2752 if (i->p && *i->p != '\0')
2753 return (unsigned char)*i->p;
2755 /* peek_buf[] is an int array, not char. Can contain EOF. */
2756 ch = i->peek_buf[0];
2760 /* Need to get a new char */
2761 ch = fgetc_interactive(i);
2762 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2764 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2765 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2771 i->peek_buf[0] = ch;
2772 /*i->peek_buf[1] = 0; - already is */
2776 /* Only ever called if i_peek() was called, and did not return EOF.
2777 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2778 * not end-of-line. Therefore we never need to read a new editing line here.
2780 static int i_peek2(struct in_str *i)
2784 /* There are two cases when i->p[] buffer exists.
2785 * (1) it's a string in_str.
2786 * (2) It's a file, and we have a saved line editing buffer.
2787 * In both cases, we know that i->p[0] exists and not NUL, and
2788 * the peek2 result is in i->p[1].
2791 return (unsigned char)i->p[1];
2793 /* Now we know it is a file-based in_str. */
2795 /* peek_buf[] is an int array, not char. Can contain EOF. */
2796 /* Is there 2nd char? */
2797 ch = i->peek_buf[1];
2799 /* We did not read it yet, get it now */
2800 do ch = hfgetc(i->file); while (ch == '\0');
2801 i->peek_buf[1] = ch;
2804 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2808 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2813 ch = i_getch(input);
2816 ch2 = i_peek(input);
2819 /* backslash+newline, skip it */
2824 /* Note: this function _eats_ \<newline> pairs, safe to use plain
2825 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2827 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2835 ch2 = i_peek2(input);
2838 /* backslash+newline, skip it */
2844 static void setup_file_in_str(struct in_str *i, HFILE *fp)
2846 memset(i, 0, sizeof(*i));
2851 static void setup_string_in_str(struct in_str *i, const char *s)
2853 memset(i, 0, sizeof(*i));
2854 /*i->file = NULL */;
2862 #define B_CHUNK (32 * sizeof(char*))
2864 static void o_reset_to_empty_unquoted(o_string *o)
2867 o->has_quoted_part = 0;
2872 static void o_free_and_set_NULL(o_string *o)
2875 memset(o, 0, sizeof(*o));
2878 static ALWAYS_INLINE void o_free(o_string *o)
2883 static void o_grow_by(o_string *o, int len)
2885 if (o->length + len > o->maxlen) {
2886 o->maxlen += (2 * len) | (B_CHUNK-1);
2887 o->data = xrealloc(o->data, 1 + o->maxlen);
2891 static void o_addchr(o_string *o, int ch)
2893 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2894 if (o->length < o->maxlen) {
2895 /* likely. avoid o_grow_by() call */
2897 o->data[o->length] = ch;
2899 o->data[o->length] = '\0';
2907 /* Valid only if we know o_string is not empty */
2908 static void o_delchr(o_string *o)
2911 o->data[o->length] = '\0';
2915 static void o_addblock(o_string *o, const char *str, int len)
2918 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2922 static void o_addstr(o_string *o, const char *str)
2924 o_addblock(o, str, strlen(str));
2927 static void o_addstr_with_NUL(o_string *o, const char *str)
2929 o_addblock(o, str, strlen(str) + 1);
2933 static void nommu_addchr(o_string *o, int ch)
2939 # define nommu_addchr(o, str) ((void)0)
2942 #if ENABLE_HUSH_MODE_X
2943 static void x_mode_addchr(int ch)
2945 o_addchr(&G.x_mode_buf, ch);
2947 static void x_mode_addstr(const char *str)
2949 o_addstr(&G.x_mode_buf, str);
2951 static void x_mode_addblock(const char *str, int len)
2953 o_addblock(&G.x_mode_buf, str, len);
2955 static void x_mode_prefix(void)
2957 int n = G.x_mode_depth;
2958 do x_mode_addchr('+'); while (--n >= 0);
2960 static void x_mode_flush(void)
2962 int len = G.x_mode_buf.length;
2965 if (G.x_mode_fd > 0) {
2966 G.x_mode_buf.data[len] = '\n';
2967 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2969 G.x_mode_buf.length = 0;
2974 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2975 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2976 * Apparently, on unquoted $v bash still does globbing
2977 * ("v='*.txt'; echo $v" prints all .txt files),
2978 * but NOT brace expansion! Thus, there should be TWO independent
2979 * quoting mechanisms on $v expansion side: one protects
2980 * $v from brace expansion, and other additionally protects "$v" against globbing.
2981 * We have only second one.
2984 #if ENABLE_HUSH_BRACE_EXPANSION
2985 # define MAYBE_BRACES "{}"
2987 # define MAYBE_BRACES ""
2990 /* My analysis of quoting semantics tells me that state information
2991 * is associated with a destination, not a source.
2993 static void o_addqchr(o_string *o, int ch)
2996 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
3001 o->data[o->length] = '\\';
3004 o->data[o->length] = ch;
3006 o->data[o->length] = '\0';
3009 static void o_addQchr(o_string *o, int ch)
3012 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3013 && strchr("*?[\\" MAYBE_BRACES, ch)
3016 o->data[o->length] = '\\';
3020 o->data[o->length] = ch;
3022 o->data[o->length] = '\0';
3025 static void o_addqblock(o_string *o, const char *str, int len)
3030 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
3031 if (ordinary_cnt > len) /* paranoia */
3033 o_addblock(o, str, ordinary_cnt);
3034 if (ordinary_cnt == len)
3035 return; /* NUL is already added by o_addblock */
3036 str += ordinary_cnt;
3037 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
3041 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
3043 o->data[o->length] = '\\';
3047 o->data[o->length] = ch;
3050 o->data[o->length] = '\0';
3053 static void o_addQblock(o_string *o, const char *str, int len)
3055 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
3056 o_addblock(o, str, len);
3059 o_addqblock(o, str, len);
3062 static void o_addQstr(o_string *o, const char *str)
3064 o_addQblock(o, str, strlen(str));
3067 /* A special kind of o_string for $VAR and `cmd` expansion.
3068 * It contains char* list[] at the beginning, which is grown in 16 element
3069 * increments. Actual string data starts at the next multiple of 16 * (char*).
3070 * list[i] contains an INDEX (int!) into this string data.
3071 * It means that if list[] needs to grow, data needs to be moved higher up
3072 * but list[i]'s need not be modified.
3073 * NB: remembering how many list[i]'s you have there is crucial.
3074 * o_finalize_list() operation post-processes this structure - calculates
3075 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3077 #if DEBUG_EXPAND || DEBUG_GLOB
3078 static void debug_print_list(const char *prefix, o_string *o, int n)
3080 char **list = (char**)o->data;
3081 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3085 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
3086 prefix, list, n, string_start, o->length, o->maxlen,
3087 !!(o->o_expflags & EXP_FLAG_GLOB),
3089 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3092 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3093 o->data + (int)(uintptr_t)list[i] + string_start,
3094 o->data + (int)(uintptr_t)list[i] + string_start);
3098 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
3100 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
3104 # define debug_print_list(prefix, o, n) ((void)0)
3107 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3108 * in list[n] so that it points past last stored byte so far.
3109 * It returns n+1. */
3110 static int o_save_ptr_helper(o_string *o, int n)
3112 char **list = (char**)o->data;
3116 if (!o->has_empty_slot) {
3117 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3118 string_len = o->length - string_start;
3119 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
3120 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
3121 /* list[n] points to string_start, make space for 16 more pointers */
3122 o->maxlen += 0x10 * sizeof(list[0]);
3123 o->data = xrealloc(o->data, o->maxlen + 1);
3124 list = (char**)o->data;
3125 memmove(list + n + 0x10, list + n, string_len);
3127 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3128 * check. (grep for -prev-ifs-check-).
3129 * Ensure that argv[-1][last] is not garbage
3130 * but zero bytes, to save index check there.
3132 list[n + 0x10 - 1] = 0;
3133 o->length += 0x10 * sizeof(list[0]);
3135 debug_printf_list("list[%d]=%d string_start=%d\n",
3136 n, string_len, string_start);
3139 /* We have empty slot at list[n], reuse without growth */
3140 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3141 string_len = o->length - string_start;
3142 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3143 n, string_len, string_start);
3144 o->has_empty_slot = 0;
3146 o->has_quoted_part = 0;
3147 list[n] = (char*)(uintptr_t)string_len;
3151 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
3152 static int o_get_last_ptr(o_string *o, int n)
3154 char **list = (char**)o->data;
3155 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3157 return ((int)(uintptr_t)list[n-1]) + string_start;
3161 * Globbing routines.
3163 * Most words in commands need to be globbed, even ones which are
3164 * (single or double) quoted. This stems from the possiblity of
3165 * constructs like "abc"* and 'abc'* - these should be globbed.
3166 * Having a different code path for fully-quoted strings ("abc",
3167 * 'abc') would only help performance-wise, but we still need
3168 * code for partially-quoted strings.
3170 * Unfortunately, if we want to match bash and ash behavior in all cases,
3171 * the logic can't be "shell-syntax argument is first transformed
3172 * to a string, then globbed, and if globbing does not match anything,
3173 * it is used verbatim". Here are two examples where it fails:
3177 * The globbing can't be avoided (because of '?' at the end).
3178 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3179 * and are glob-escaped. If this does not match, bash/ash print b\*?
3180 * - IOW: they "unbackslash" the glob pattern.
3181 * Now, look at this:
3183 * v='\\\*'; echo b$v?
3185 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
3186 * should be used as glob pattern with no changes. However, if glob
3187 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
3189 * ash implements this by having an encoded representation of the word
3190 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3191 * Glob pattern is derived from it. If glob fails, the decision what result
3192 * should be is made using that encoded representation. Not glob pattern.
3195 #if ENABLE_HUSH_BRACE_EXPANSION
3196 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
3197 * first, it processes even {a} (no commas), second,
3198 * I didn't manage to make it return strings when they don't match
3199 * existing files. Need to re-implement it.
3203 static int glob_needed(const char *s)
3212 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3218 /* Return pointer to next closing brace or to comma */
3219 static const char *next_brace_sub(const char *cp)
3223 while (*cp != '\0') {
3230 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
3236 return *cp != '\0' ? cp : NULL;
3238 /* Recursive brace globber. Note: may garble pattern[]. */
3239 static int glob_brace(char *pattern, o_string *o, int n)
3241 char *new_pattern_buf;
3248 debug_printf_glob("glob_brace('%s')\n", pattern);
3254 if (*begin == '{') {
3255 /* Find the first sub-pattern and at the same time
3256 * find the rest after the closing brace */
3257 next = next_brace_sub(begin);
3259 /* An illegal expression */
3263 /* "{abc}" with no commas - illegal
3264 * brace expr, disregard and skip it */
3270 if (*begin == '\\' && begin[1] != '\0')
3274 debug_printf_glob("begin:%s\n", begin);
3275 debug_printf_glob("next:%s\n", next);
3277 /* Now find the end of the whole brace expression */
3279 while (*rest != '}') {
3280 rest = next_brace_sub(rest);
3282 /* An illegal expression */
3285 debug_printf_glob("rest:%s\n", rest);
3287 rest_len = strlen(++rest) + 1;
3289 /* We are sure the brace expression is well-formed */
3291 /* Allocate working buffer large enough for our work */
3292 new_pattern_buf = xmalloc(strlen(pattern));
3294 /* We have a brace expression. BEGIN points to the opening {,
3295 * NEXT points past the terminator of the first element, and REST
3296 * points past the final }. We will accumulate result names from
3297 * recursive runs for each brace alternative in the buffer using
3302 /* Construct the new glob expression */
3305 mempcpy(new_pattern_buf,
3306 /* We know the prefix for all sub-patterns */
3307 pattern, begin - pattern),
3311 /* Note: glob_brace() may garble new_pattern_buf[].
3312 * That's why we re-copy prefix every time (1st memcpy above).
3314 n = glob_brace(new_pattern_buf, o, n);
3316 /* We saw the last entry */
3320 next = next_brace_sub(next);
3322 free(new_pattern_buf);
3330 memset(&globdata, 0, sizeof(globdata));
3331 gr = glob(pattern, 0, NULL, &globdata);
3332 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3334 if (gr == GLOB_NOMATCH) {
3335 globfree(&globdata);
3336 /* NB: garbles parameter */
3337 unbackslash(pattern);
3338 o_addstr_with_NUL(o, pattern);
3339 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3340 return o_save_ptr_helper(o, n);
3342 if (gr == GLOB_NOSPACE)
3343 bb_die_memory_exhausted();
3344 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3345 * but we didn't specify it. Paranoia again. */
3346 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3348 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3349 char **argv = globdata.gl_pathv;
3351 o_addstr_with_NUL(o, *argv);
3352 n = o_save_ptr_helper(o, n);
3358 globfree(&globdata);
3362 /* Performs globbing on last list[],
3363 * saving each result as a new list[].
3365 static int perform_glob(o_string *o, int n)
3367 char *pattern, *copy;
3369 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3371 return o_save_ptr_helper(o, n);
3372 pattern = o->data + o_get_last_ptr(o, n);
3373 debug_printf_glob("glob pattern '%s'\n", pattern);
3374 if (!glob_needed(pattern)) {
3375 /* unbackslash last string in o in place, fix length */
3376 o->length = unbackslash(pattern) - o->data;
3377 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3378 return o_save_ptr_helper(o, n);
3381 copy = xstrdup(pattern);
3382 /* "forget" pattern in o */
3383 o->length = pattern - o->data;
3384 n = glob_brace(copy, o, n);
3387 debug_print_list("perform_glob returning", o, n);
3391 #else /* !HUSH_BRACE_EXPANSION */
3394 static int glob_needed(const char *s)
3403 if (*s == '*' || *s == '[' || *s == '?')
3409 /* Performs globbing on last list[],
3410 * saving each result as a new list[].
3412 static int perform_glob(o_string *o, int n)
3418 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3420 return o_save_ptr_helper(o, n);
3421 pattern = o->data + o_get_last_ptr(o, n);
3422 debug_printf_glob("glob pattern '%s'\n", pattern);
3423 if (!glob_needed(pattern)) {
3425 /* unbackslash last string in o in place, fix length */
3426 o->length = unbackslash(pattern) - o->data;
3427 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3428 return o_save_ptr_helper(o, n);
3431 memset(&globdata, 0, sizeof(globdata));
3432 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3433 * If we glob "*.\*" and don't find anything, we need
3434 * to fall back to using literal "*.*", but GLOB_NOCHECK
3435 * will return "*.\*"!
3437 gr = glob(pattern, 0, NULL, &globdata);
3438 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3440 if (gr == GLOB_NOMATCH) {
3441 globfree(&globdata);
3444 if (gr == GLOB_NOSPACE)
3445 bb_die_memory_exhausted();
3446 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3447 * but we didn't specify it. Paranoia again. */
3448 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3450 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3451 char **argv = globdata.gl_pathv;
3452 /* "forget" pattern in o */
3453 o->length = pattern - o->data;
3455 o_addstr_with_NUL(o, *argv);
3456 n = o_save_ptr_helper(o, n);
3462 globfree(&globdata);
3464 debug_print_list("perform_glob returning", o, n);
3468 #endif /* !HUSH_BRACE_EXPANSION */
3470 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3471 * Otherwise, just finish current list[] and start new */
3472 static int o_save_ptr(o_string *o, int n)
3474 if (o->o_expflags & EXP_FLAG_GLOB) {
3475 /* If o->has_empty_slot, list[n] was already globbed
3476 * (if it was requested back then when it was filled)
3477 * so don't do that again! */
3478 if (!o->has_empty_slot)
3479 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3481 return o_save_ptr_helper(o, n);
3484 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3485 static char **o_finalize_list(o_string *o, int n)
3491 debug_print_list("finalized", o, n);
3492 debug_printf_expand("finalized n:%d\n", n);
3493 list = (char**)o->data;
3494 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3498 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3503 static void free_pipe_list(struct pipe *pi);
3505 /* Returns pi->next - next pipe in the list */
3506 static struct pipe *free_pipe(struct pipe *pi)
3511 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3512 for (i = 0; i < pi->num_cmds; i++) {
3513 struct command *command;
3514 struct redir_struct *r, *rnext;
3516 command = &pi->cmds[i];
3517 debug_printf_clean(" command %d:\n", i);
3518 if (command->argv) {
3522 for (a = 0, p = command->argv; *p; a++, p++) {
3523 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3526 free_strings(command->argv);
3527 //command->argv = NULL;
3529 /* not "else if": on syntax error, we may have both! */
3530 if (command->group) {
3531 debug_printf_clean(" begin group (cmd_type:%d)\n",
3533 free_pipe_list(command->group);
3534 debug_printf_clean(" end group\n");
3535 //command->group = NULL;
3537 /* else is crucial here.
3538 * If group != NULL, child_func is meaningless */
3539 #if ENABLE_HUSH_FUNCTIONS
3540 else if (command->child_func) {
3541 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3542 command->child_func->parent_cmd = NULL;
3546 free(command->group_as_string);
3547 //command->group_as_string = NULL;
3549 for (r = command->redirects; r; r = rnext) {
3550 debug_printf_clean(" redirect %d%s",
3551 r->rd_fd, redir_table[r->rd_type].descrip);
3552 /* guard against the case >$FOO, where foo is unset or blank */
3553 if (r->rd_filename) {
3554 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3555 free(r->rd_filename);
3556 //r->rd_filename = NULL;
3558 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3562 //command->redirects = NULL;
3564 free(pi->cmds); /* children are an array, they get freed all at once */
3568 //pi->cmdtext = NULL;
3576 static void free_pipe_list(struct pipe *pi)
3580 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3582 debug_printf_clean("pipe followup code %d\n", pi->followup);
3588 /*** Parsing routines ***/
3590 #ifndef debug_print_tree
3591 static void debug_print_tree(struct pipe *pi, int lvl)
3593 static const char *const PIPE[] = {
3599 static const char *RES[] = {
3600 [RES_NONE ] = "NONE" ,
3603 [RES_THEN ] = "THEN" ,
3604 [RES_ELIF ] = "ELIF" ,
3605 [RES_ELSE ] = "ELSE" ,
3608 # if ENABLE_HUSH_LOOPS
3609 [RES_FOR ] = "FOR" ,
3610 [RES_WHILE] = "WHILE",
3611 [RES_UNTIL] = "UNTIL",
3613 [RES_DONE ] = "DONE" ,
3615 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3618 # if ENABLE_HUSH_CASE
3619 [RES_CASE ] = "CASE" ,
3620 [RES_CASE_IN ] = "CASE_IN" ,
3621 [RES_MATCH] = "MATCH",
3622 [RES_CASE_BODY] = "CASE_BODY",
3623 [RES_ESAC ] = "ESAC" ,
3625 [RES_XXXX ] = "XXXX" ,
3626 [RES_SNTX ] = "SNTX" ,
3628 static const char *const CMDTYPE[] = {
3632 # if ENABLE_HUSH_FUNCTIONS
3641 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3644 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3646 pi->followup, PIPE[pi->followup]
3649 while (prn < pi->num_cmds) {
3650 struct command *command = &pi->cmds[prn];
3651 char **argv = command->argv;
3653 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3655 command->assignment_cnt);
3656 # if ENABLE_HUSH_LINENO_VAR
3657 fdprintf(2, " LINENO:%u", command->lineno);
3659 if (command->group) {
3660 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3661 CMDTYPE[command->cmd_type],
3664 , " group_as_string:", command->group_as_string
3669 debug_print_tree(command->group, lvl+1);
3673 if (argv) while (*argv) {
3674 fdprintf(2, " '%s'", *argv);
3677 if (command->redirects)
3678 fdprintf(2, " {redir}");
3686 #endif /* debug_print_tree */
3688 static struct pipe *new_pipe(void)
3691 pi = xzalloc(sizeof(struct pipe));
3692 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3696 /* Command (member of a pipe) is complete, or we start a new pipe
3697 * if ctx->command is NULL.
3698 * No errors possible here.
3700 static int done_command(struct parse_context *ctx)
3702 /* The command is really already in the pipe structure, so
3703 * advance the pipe counter and make a new, null command. */
3704 struct pipe *pi = ctx->pipe;
3705 struct command *command = ctx->command;
3707 #if 0 /* Instead we emit error message at run time */
3708 if (ctx->pending_redirect) {
3709 /* For example, "cmd >" (no filename to redirect to) */
3710 syntax_error("invalid redirect");
3711 ctx->pending_redirect = NULL;
3716 if (IS_NULL_CMD(command)) {
3717 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3721 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3722 //debug_print_tree(ctx->list_head, 20);
3724 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3727 /* Only real trickiness here is that the uncommitted
3728 * command structure is not counted in pi->num_cmds. */
3729 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3730 ctx->command = command = &pi->cmds[pi->num_cmds];
3732 memset(command, 0, sizeof(*command));
3733 #if ENABLE_HUSH_LINENO_VAR
3734 command->lineno = G.parse_lineno;
3735 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
3737 return pi->num_cmds; /* used only for 0/nonzero check */
3740 static void done_pipe(struct parse_context *ctx, pipe_style type)
3744 debug_printf_parse("done_pipe entered, followup %d\n", type);
3745 /* Close previous command */
3746 not_null = done_command(ctx);
3748 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3749 ctx->ctx_inverted = 0;
3750 ctx->pipe->res_word = ctx->ctx_res_w;
3752 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3753 /* Necessary since && and || have precedence over &:
3754 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3755 * in a backgrounded subshell.
3758 struct command *command;
3760 /* Is this actually this construct, all pipes end with && or ||? */
3761 pi = ctx->list_head;
3762 while (pi != ctx->pipe) {
3763 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3768 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3769 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3770 pi = xzalloc(sizeof(*pi));
3771 pi->followup = PIPE_BG;
3773 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3774 command = &pi->cmds[0];
3775 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3776 command->cmd_type = CMD_NORMAL;
3777 command->group = ctx->list_head;
3779 command->group_as_string = xstrndup(
3780 ctx->as_string.data,
3781 ctx->as_string.length - 1 /* do not copy last char, "&" */
3784 /* Replace all pipes in ctx with one newly created */
3785 ctx->list_head = ctx->pipe = pi;
3788 ctx->pipe->followup = type;
3791 /* Without this check, even just <enter> on command line generates
3792 * tree of three NOPs (!). Which is harmless but annoying.
3793 * IOW: it is safe to do it unconditionally. */
3796 || ctx->ctx_res_w == RES_FI
3798 #if ENABLE_HUSH_LOOPS
3799 || ctx->ctx_res_w == RES_DONE
3800 || ctx->ctx_res_w == RES_FOR
3801 || ctx->ctx_res_w == RES_IN
3803 #if ENABLE_HUSH_CASE
3804 || ctx->ctx_res_w == RES_ESAC
3808 debug_printf_parse("done_pipe: adding new pipe: "
3809 "not_null:%d ctx->ctx_res_w:%d\n",
3810 not_null, ctx->ctx_res_w);
3812 ctx->pipe->next = new_p;
3814 /* RES_THEN, RES_DO etc are "sticky" -
3815 * they remain set for pipes inside if/while.
3816 * This is used to control execution.
3817 * RES_FOR and RES_IN are NOT sticky (needed to support
3818 * cases where variable or value happens to match a keyword):
3820 #if ENABLE_HUSH_LOOPS
3821 if (ctx->ctx_res_w == RES_FOR
3822 || ctx->ctx_res_w == RES_IN)
3823 ctx->ctx_res_w = RES_NONE;
3825 #if ENABLE_HUSH_CASE
3826 if (ctx->ctx_res_w == RES_MATCH)
3827 ctx->ctx_res_w = RES_CASE_BODY;
3828 if (ctx->ctx_res_w == RES_CASE)
3829 ctx->ctx_res_w = RES_CASE_IN;
3831 ctx->command = NULL; /* trick done_command below */
3832 /* Create the memory for command, roughly:
3833 * ctx->pipe->cmds = new struct command;
3834 * ctx->command = &ctx->pipe->cmds[0];
3837 //debug_print_tree(ctx->list_head, 10);
3839 debug_printf_parse("done_pipe return\n");
3842 static void initialize_context(struct parse_context *ctx)
3844 memset(ctx, 0, sizeof(*ctx));
3845 if (MAYBE_ASSIGNMENT != 0)
3846 ctx->is_assignment = MAYBE_ASSIGNMENT;
3847 ctx->pipe = ctx->list_head = new_pipe();
3848 /* Create the memory for command, roughly:
3849 * ctx->pipe->cmds = new struct command;
3850 * ctx->command = &ctx->pipe->cmds[0];
3855 /* If a reserved word is found and processed, parse context is modified
3856 * and 1 is returned.
3859 struct reserved_combo {
3862 unsigned char assignment_flag;
3866 FLAG_END = (1 << RES_NONE ),
3868 FLAG_IF = (1 << RES_IF ),
3869 FLAG_THEN = (1 << RES_THEN ),
3870 FLAG_ELIF = (1 << RES_ELIF ),
3871 FLAG_ELSE = (1 << RES_ELSE ),
3872 FLAG_FI = (1 << RES_FI ),
3874 # if ENABLE_HUSH_LOOPS
3875 FLAG_FOR = (1 << RES_FOR ),
3876 FLAG_WHILE = (1 << RES_WHILE),
3877 FLAG_UNTIL = (1 << RES_UNTIL),
3878 FLAG_DO = (1 << RES_DO ),
3879 FLAG_DONE = (1 << RES_DONE ),
3880 FLAG_IN = (1 << RES_IN ),
3882 # if ENABLE_HUSH_CASE
3883 FLAG_MATCH = (1 << RES_MATCH),
3884 FLAG_ESAC = (1 << RES_ESAC ),
3886 FLAG_START = (1 << RES_XXXX ),
3889 static const struct reserved_combo* match_reserved_word(o_string *word)
3891 /* Mostly a list of accepted follow-up reserved words.
3892 * FLAG_END means we are done with the sequence, and are ready
3893 * to turn the compound list into a command.
3894 * FLAG_START means the word must start a new compound list.
3896 static const struct reserved_combo reserved_list[] = {
3898 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3899 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3900 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3901 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3902 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3903 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3905 # if ENABLE_HUSH_LOOPS
3906 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3907 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3908 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3909 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3910 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3911 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3913 # if ENABLE_HUSH_CASE
3914 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3915 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3918 const struct reserved_combo *r;
3920 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3921 if (strcmp(word->data, r->literal) == 0)
3926 /* Return NULL: not a keyword, else: keyword
3928 static const struct reserved_combo* reserved_word(struct parse_context *ctx)
3930 # if ENABLE_HUSH_CASE
3931 static const struct reserved_combo reserved_match = {
3932 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3935 const struct reserved_combo *r;
3937 if (ctx->word.has_quoted_part)
3939 r = match_reserved_word(&ctx->word);
3941 return r; /* NULL */
3943 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3944 # if ENABLE_HUSH_CASE
3945 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3946 /* "case word IN ..." - IN part starts first MATCH part */
3947 r = &reserved_match;
3950 if (r->flag == 0) { /* '!' */
3951 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3952 syntax_error("! ! command");
3953 ctx->ctx_res_w = RES_SNTX;
3955 ctx->ctx_inverted = 1;
3958 if (r->flag & FLAG_START) {
3959 struct parse_context *old;
3961 old = xmemdup(ctx, sizeof(*ctx));
3962 debug_printf_parse("push stack %p\n", old);
3963 initialize_context(ctx);
3965 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3966 syntax_error_at(ctx->word.data);
3967 ctx->ctx_res_w = RES_SNTX;
3970 /* "{...} fi" is ok. "{...} if" is not
3972 * if { echo foo; } then { echo bar; } fi */
3973 if (ctx->command->group)
3974 done_pipe(ctx, PIPE_SEQ);
3977 ctx->ctx_res_w = r->res;
3978 ctx->old_flag = r->flag;
3979 ctx->is_assignment = r->assignment_flag;
3980 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
3982 if (ctx->old_flag & FLAG_END) {
3983 struct parse_context *old;
3985 done_pipe(ctx, PIPE_SEQ);
3986 debug_printf_parse("pop stack %p\n", ctx->stack);
3988 old->command->group = ctx->list_head;
3989 old->command->cmd_type = CMD_NORMAL;
3991 /* At this point, the compound command's string is in
3992 * ctx->as_string... except for the leading keyword!
3993 * Consider this example: "echo a | if true; then echo a; fi"
3994 * ctx->as_string will contain "true; then echo a; fi",
3995 * with "if " remaining in old->as_string!
3999 int len = old->as_string.length;
4000 /* Concatenate halves */
4001 o_addstr(&old->as_string, ctx->as_string.data);
4002 o_free(&ctx->as_string);
4003 /* Find where leading keyword starts in first half */
4004 str = old->as_string.data + len;
4005 if (str > old->as_string.data)
4006 str--; /* skip whitespace after keyword */
4007 while (str > old->as_string.data && isalpha(str[-1]))
4009 /* Ugh, we're done with this horrid hack */
4010 old->command->group_as_string = xstrdup(str);
4011 debug_printf_parse("pop, remembering as:'%s'\n",
4012 old->command->group_as_string);
4015 *ctx = *old; /* physical copy */
4020 #endif /* HAS_KEYWORDS */
4022 /* Word is complete, look at it and update parsing context.
4023 * Normal return is 0. Syntax errors return 1.
4024 * Note: on return, word is reset, but not o_free'd!
4026 static int done_word(struct parse_context *ctx)
4028 struct command *command = ctx->command;
4030 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4031 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
4032 debug_printf_parse("done_word return 0: true null, ignored\n");
4036 if (ctx->pending_redirect) {
4037 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4038 * only if run as "bash", not "sh" */
4039 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
4041 * If the redirection operator is "<<" or "<<-", the word
4042 * that follows the redirection operator shall be
4043 * subjected to quote removal; it is unspecified whether
4044 * any of the other expansions occur. For the other
4045 * redirection operators, the word that follows the
4046 * redirection operator shall be subjected to tilde
4047 * expansion, parameter expansion, command substitution,
4048 * arithmetic expansion, and quote removal.
4049 * Pathname expansion shall not be performed
4050 * on the word by a non-interactive shell; an interactive
4051 * shell may perform it, but shall do so only when
4052 * the expansion would result in one word."
4054 //bash does not do parameter/command substitution or arithmetic expansion
4055 //for _heredoc_ redirection word: these constructs look for exact eof marker
4059 // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4061 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
4062 /* Cater for >\file case:
4063 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4064 * Same with heredocs:
4065 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4067 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4068 unbackslash(ctx->pending_redirect->rd_filename);
4069 /* Is it <<"HEREDOC"? */
4070 if (ctx->word.has_quoted_part) {
4071 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4074 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
4075 ctx->pending_redirect = NULL;
4078 # if ENABLE_HUSH_CASE
4079 if (ctx->ctx_dsemicolon
4080 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4082 /* already done when ctx_dsemicolon was set to 1: */
4083 /* ctx->ctx_res_w = RES_MATCH; */
4084 ctx->ctx_dsemicolon = 0;
4087 if (!command->argv /* if it's the first word... */
4088 # if ENABLE_HUSH_LOOPS
4089 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4090 && ctx->ctx_res_w != RES_IN
4092 # if ENABLE_HUSH_CASE
4093 && ctx->ctx_res_w != RES_CASE
4096 const struct reserved_combo *reserved;
4097 reserved = reserved_word(ctx);
4098 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
4100 # if ENABLE_HUSH_LINENO_VAR
4104 * If we don't close the pipe _now_, immediately after "do", lineno logic
4105 * sees "cmd" as starting at "do" - i.e., at the previous line.
4108 IF_HUSH_IF(|| reserved->res == RES_THEN)
4109 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4110 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4111 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4113 done_pipe(ctx, PIPE_SEQ);
4116 o_reset_to_empty_unquoted(&ctx->word);
4117 debug_printf_parse("done_word return %d\n",
4118 (ctx->ctx_res_w == RES_SNTX));
4119 return (ctx->ctx_res_w == RES_SNTX);
4121 # if defined(CMD_SINGLEWORD_NOGLOB)
4124 || strcmp(ctx->word.data, "[[") == 0
4126 /* In bash, local/export/readonly are special, args
4127 * are assignments and therefore expansion of them
4128 * should be "one-word" expansion:
4129 * $ export i=`echo 'a b'` # one arg: "i=a b"
4131 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4132 * ls: cannot access i=a: No such file or directory
4133 * ls: cannot access b: No such file or directory
4134 * Note: bash 3.2.33(1) does this only if export word
4135 * itself is not quoted:
4136 * $ export i=`echo 'aaa bbb'`; echo "$i"
4138 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4141 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4142 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4143 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
4145 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4150 #endif /* HAS_KEYWORDS */
4152 if (command->group) {
4153 /* "{ echo foo; } echo bar" - bad */
4154 syntax_error_at(ctx->word.data);
4155 debug_printf_parse("done_word return 1: syntax error, "
4156 "groups and arglists don't mix\n");
4160 /* If this word wasn't an assignment, next ones definitely
4161 * can't be assignments. Even if they look like ones. */
4162 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4163 && ctx->is_assignment != WORD_IS_KEYWORD
4165 ctx->is_assignment = NOT_ASSIGNMENT;
4167 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
4168 command->assignment_cnt++;
4169 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4171 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4172 ctx->is_assignment = MAYBE_ASSIGNMENT;
4174 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4175 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
4176 debug_print_strings("word appended to argv", command->argv);
4179 #if ENABLE_HUSH_LOOPS
4180 if (ctx->ctx_res_w == RES_FOR) {
4181 if (ctx->word.has_quoted_part
4182 || endofname(command->argv[0])[0] != '\0'
4184 /* bash says just "not a valid identifier" */
4185 syntax_error("not a valid identifier in for");
4188 /* Force FOR to have just one word (variable name) */
4189 /* NB: basically, this makes hush see "for v in ..."
4190 * syntax as if it is "for v; in ...". FOR and IN become
4191 * two pipe structs in parse tree. */
4192 done_pipe(ctx, PIPE_SEQ);
4195 #if ENABLE_HUSH_CASE
4196 /* Force CASE to have just one word */
4197 if (ctx->ctx_res_w == RES_CASE) {
4198 done_pipe(ctx, PIPE_SEQ);
4202 o_reset_to_empty_unquoted(&ctx->word);
4204 debug_printf_parse("done_word return 0\n");
4209 /* Peek ahead in the input to find out if we have a "&n" construct,
4210 * as in "2>&1", that represents duplicating a file descriptor.
4212 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4213 * REDIRFD_SYNTAX_ERR if syntax error,
4214 * REDIRFD_TO_FILE if no & was seen,
4215 * or the number found.
4218 #define parse_redir_right_fd(as_string, input) \
4219 parse_redir_right_fd(input)
4221 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4227 return REDIRFD_TO_FILE;
4229 ch = i_getch(input); /* get the & */
4230 nommu_addchr(as_string, ch);
4233 ch = i_getch(input);
4234 nommu_addchr(as_string, ch);
4235 return REDIRFD_CLOSE;
4239 while (ch != EOF && isdigit(ch)) {
4240 d = d*10 + (ch-'0');
4242 ch = i_getch(input);
4243 nommu_addchr(as_string, ch);
4248 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4250 bb_simple_error_msg("ambiguous redirect");
4251 return REDIRFD_SYNTAX_ERR;
4254 /* Return code is 0 normal, 1 if a syntax error is detected
4256 static int parse_redirect(struct parse_context *ctx,
4259 struct in_str *input)
4261 struct command *command = ctx->command;
4262 struct redir_struct *redir;
4263 struct redir_struct **redirp;
4266 dup_num = REDIRFD_TO_FILE;
4267 if (style != REDIRECT_HEREDOC) {
4268 /* Check for a '>&1' type redirect */
4269 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4270 if (dup_num == REDIRFD_SYNTAX_ERR)
4273 int ch = i_peek_and_eat_bkslash_nl(input);
4274 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4275 if (dup_num) { /* <<-... */
4276 ch = i_getch(input);
4277 nommu_addchr(&ctx->as_string, ch);
4282 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4283 int ch = i_peek_and_eat_bkslash_nl(input);
4285 /* >|FILE redirect ("clobbering" >).
4286 * Since we do not support "set -o noclobber" yet,
4287 * >| and > are the same for now. Just eat |.
4289 ch = i_getch(input);
4290 nommu_addchr(&ctx->as_string, ch);
4294 /* Create a new redir_struct and append it to the linked list */
4295 redirp = &command->redirects;
4296 while ((redir = *redirp) != NULL) {
4297 redirp = &(redir->next);
4299 *redirp = redir = xzalloc(sizeof(*redir));
4300 /* redir->next = NULL; */
4301 /* redir->rd_filename = NULL; */
4302 redir->rd_type = style;
4303 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4305 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4306 redir_table[style].descrip);
4308 redir->rd_dup = dup_num;
4309 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4310 /* Erik had a check here that the file descriptor in question
4311 * is legit; I postpone that to "run time"
4312 * A "-" representation of "close me" shows up as a -3 here */
4313 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4314 redir->rd_fd, redir->rd_dup);
4316 #if 0 /* Instead we emit error message at run time */
4317 if (ctx->pending_redirect) {
4318 /* For example, "cmd > <file" */
4319 syntax_error("invalid redirect");
4322 /* Set ctx->pending_redirect, so we know what to do at the
4323 * end of the next parsed word. */
4324 ctx->pending_redirect = redir;
4329 /* If a redirect is immediately preceded by a number, that number is
4330 * supposed to tell which file descriptor to redirect. This routine
4331 * looks for such preceding numbers. In an ideal world this routine
4332 * needs to handle all the following classes of redirects...
4333 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4334 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4335 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4336 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4338 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4340 * ... If n is quoted, the number shall not be recognized as part of
4341 * the redirection expression. For example:
4343 * writes the character 2 into file a"
4344 * We are getting it right by setting ->has_quoted_part on any \<char>
4346 * A -1 return means no valid number was found,
4347 * the caller should use the appropriate default for this redirection.
4349 static int redirect_opt_num(o_string *o)
4353 if (o->data == NULL)
4355 num = bb_strtou(o->data, NULL, 10);
4356 if (errno || num < 0)
4358 o_reset_to_empty_unquoted(o);
4363 #define fetch_till_str(as_string, input, word, skip_tabs) \
4364 fetch_till_str(input, word, skip_tabs)
4366 static char *fetch_till_str(o_string *as_string,
4367 struct in_str *input,
4371 o_string heredoc = NULL_O_STRING;
4373 int prev = 0; /* not \ */
4376 /* Starting with "" is necessary for this case:
4382 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4387 ch = i_getch(input);
4389 nommu_addchr(as_string, ch);
4390 if (ch == '\n' || ch == EOF) {
4392 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4393 /* End-of-line, and not a line continuation */
4394 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4395 heredoc.data[past_EOL] = '\0';
4396 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
4397 return heredoc.data;
4400 /* This is a new line.
4401 * Remember position and backslash-escaping status.
4403 o_addchr(&heredoc, ch);
4406 past_EOL = heredoc.length;
4407 /* Get 1st char of next line, possibly skipping leading tabs */
4409 ch = i_getch(input);
4411 nommu_addchr(as_string, ch);
4412 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4413 /* If this immediately ended the line,
4414 * go back to end-of-line checks.
4417 goto check_heredoc_end;
4420 /* Backslash-line continuation in an unquoted
4421 * heredoc. This does not need special handling
4422 * for heredoc body (unquoted heredocs are
4423 * expanded on "execution" and that would take
4424 * care of this case too), but not the case
4425 * of line continuation *in terminator*:
4431 heredoc.data[--heredoc.length] = '\0';
4432 prev = 0; /* not '\' */
4438 return NULL; /* error */
4440 o_addchr(&heredoc, ch);
4441 nommu_addchr(as_string, ch);
4442 if (prev == '\\' && ch == '\\')
4443 /* Correctly handle foo\\<eol> (not a line cont.) */
4444 prev = 0; /* not '\' */
4450 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4451 * and load them all. There should be exactly heredoc_cnt of them.
4454 #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4455 fetch_heredocs(pi, heredoc_cnt, input)
4457 static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
4459 while (pi && heredoc_cnt) {
4461 struct command *cmd = pi->cmds;
4463 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4465 cmd->argv ? cmd->argv[0] : "NONE"
4467 for (i = 0; i < pi->num_cmds; i++) {
4468 struct redir_struct *redir = cmd->redirects;
4470 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
4471 i, cmd->argv ? cmd->argv[0] : "NONE");
4473 if (redir->rd_type == REDIRECT_HEREDOC) {
4476 redir->rd_type = REDIRECT_HEREDOC2;
4477 /* redir->rd_dup is (ab)used to indicate <<- */
4478 p = fetch_till_str(as_string, input,
4479 redir->rd_filename, redir->rd_dup);
4481 syntax_error("unexpected EOF in here document");
4484 free(redir->rd_filename);
4485 redir->rd_filename = p;
4488 redir = redir->next;
4491 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4492 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4493 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4494 if (heredoc_cnt < 0)
4495 return heredoc_cnt; /* error */
4505 static int run_list(struct pipe *pi);
4507 #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4508 parse_stream(heredoc_cnt_ptr, input, end_trigger)
4510 static struct pipe *parse_stream(char **pstring,
4511 int *heredoc_cnt_ptr,
4512 struct in_str *input,
4515 /* Returns number of heredocs not yet consumed,
4518 static int parse_group(struct parse_context *ctx,
4519 struct in_str *input, int ch)
4521 /* ctx->word contains characters seen prior to ( or {.
4522 * Typically it's empty, but for function defs,
4523 * it contains function name (without '()'). */
4525 # define as_string NULL
4527 char *as_string = NULL;
4529 struct pipe *pipe_list;
4530 int heredoc_cnt = 0;
4532 struct command *command = ctx->command;
4534 debug_printf_parse("parse_group entered\n");
4535 #if ENABLE_HUSH_FUNCTIONS
4536 if (ch == '(' && !ctx->word.has_quoted_part) {
4537 if (ctx->word.length)
4541 goto skip; /* (... */
4542 if (command->argv[1]) { /* word word ... (... */
4543 syntax_error_unexpected_ch('(');
4546 /* it is "word(..." or "word (..." */
4548 ch = i_getch(input);
4549 while (ch == ' ' || ch == '\t');
4551 syntax_error_unexpected_ch(ch);
4554 nommu_addchr(&ctx->as_string, ch);
4556 ch = i_getch(input);
4557 while (ch == ' ' || ch == '\t' || ch == '\n');
4558 if (ch != '{' && ch != '(') {
4559 syntax_error_unexpected_ch(ch);
4562 nommu_addchr(&ctx->as_string, ch);
4563 command->cmd_type = CMD_FUNCDEF;
4568 #if 0 /* Prevented by caller */
4569 if (command->argv /* word [word]{... */
4570 || ctx->word.length /* word{... */
4571 || ctx->word.has_quoted_part /* ""{... */
4574 debug_printf_parse("parse_group return -1: "
4575 "syntax error, groups and arglists don't mix\n");
4580 IF_HUSH_FUNCTIONS(skip:)
4585 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4586 command->cmd_type = CMD_SUBSHELL;
4588 /* bash does not allow "{echo...", requires whitespace */
4590 if (ch != ' ' && ch != '\t' && ch != '\n'
4591 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4593 syntax_error_unexpected_ch(ch);
4597 ch = i_getch(input);
4598 nommu_addchr(&ctx->as_string, ch);
4602 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4603 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4604 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
4607 o_addstr(&ctx->as_string, as_string);
4610 /* empty ()/{} or parse error? */
4611 if (!pipe_list || pipe_list == ERR_PTR) {
4612 /* parse_stream already emitted error msg */
4615 debug_printf_parse("parse_group return -1: "
4616 "parse_stream returned %p\n", pipe_list);
4620 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4621 command->group_as_string = as_string;
4622 debug_printf_parse("end of group, remembering as:'%s'\n",
4623 command->group_as_string);
4626 #if ENABLE_HUSH_FUNCTIONS
4627 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4628 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4629 struct command *cmd2;
4631 cmd2 = xzalloc(sizeof(*cmd2));
4632 cmd2->cmd_type = CMD_SUBSHELL;
4633 cmd2->group = pipe_list;
4636 cmd2->group_as_string = command->group_as_string;
4637 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4640 pipe_list = new_pipe();
4641 pipe_list->cmds = cmd2;
4642 pipe_list->num_cmds = 1;
4646 command->group = pipe_list;
4648 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4650 /* command remains "open", available for possible redirects */
4654 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4655 /* Subroutines for copying $(...) and `...` things */
4657 static int add_till_single_quote(o_string *dest, struct in_str *input)
4660 int ch = i_getch(input);
4662 syntax_error_unterm_ch('\'');
4670 static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4673 int ch = i_getch(input);
4675 syntax_error_unterm_ch('\'');
4680 o_addqchr(dest, ch);
4683 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4684 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4685 static int add_till_double_quote(o_string *dest, struct in_str *input)
4688 int ch = i_getch(input);
4690 syntax_error_unterm_ch('"');
4695 if (ch == '\\') { /* \x. Copy both chars. */
4697 ch = i_getch(input);
4701 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4706 //if (ch == '$') ...
4709 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4711 * "Within the backquoted style of command substitution, backslash
4712 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4713 * The search for the matching backquote shall be satisfied by the first
4714 * backquote found without a preceding backslash; during this search,
4715 * if a non-escaped backquote is encountered within a shell comment,
4716 * a here-document, an embedded command substitution of the $(command)
4717 * form, or a quoted string, undefined results occur. A single-quoted
4718 * or double-quoted string that begins, but does not end, within the
4719 * "`...`" sequence produces undefined results."
4721 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4723 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4726 int ch = i_getch(input);
4730 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4731 ch = i_getch(input);
4735 && (!in_dquote || ch != '"')
4737 o_addchr(dest, '\\');
4741 syntax_error_unterm_ch('`');
4747 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4748 * quoting and nested ()s.
4749 * "With the $(command) style of command substitution, all characters
4750 * following the open parenthesis to the matching closing parenthesis
4751 * constitute the command. Any valid shell script can be used for command,
4752 * except a script consisting solely of redirections which produces
4753 * unspecified results."
4755 * echo $(echo '(TEST)' BEST) (TEST) BEST
4756 * echo $(echo 'TEST)' BEST) TEST) BEST
4757 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4759 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4760 * can contain arbitrary constructs, just like $(cmd).
4761 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4762 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4764 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4765 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4768 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4769 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4770 char end_char2 = end_ch >> 8;
4772 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4774 # if ENABLE_HUSH_INTERACTIVE
4775 G.promptmode = 1; /* PS2 */
4777 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4780 ch = i_getch(input);
4782 syntax_error_unterm_ch(end_ch);
4786 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4792 /* we look for closing )) of $((EXPR)) */
4793 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4794 i_getch(input); /* eat second ')' */
4799 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
4800 if (ch == '(' || ch == '{') {
4801 ch = (ch == '(' ? ')' : '}');
4802 if (!add_till_closing_bracket(dest, input, ch))
4808 if (!add_till_single_quote(dest, input))
4814 if (!add_till_double_quote(dest, input))
4820 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4826 /* \x. Copy verbatim. Important for \(, \) */
4827 ch = i_getch(input);
4829 syntax_error_unterm_ch(end_ch);
4834 /* "backslash+newline", ignore both */
4835 o_delchr(dest); /* undo insertion of '\' */
4840 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
4844 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
4847 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4849 /* Return code: 0 for OK, 1 for syntax error */
4851 #define parse_dollar(as_string, dest, input, quote_mask) \
4852 parse_dollar(dest, input, quote_mask)
4853 #define as_string NULL
4855 static int parse_dollar(o_string *as_string,
4857 struct in_str *input, unsigned char quote_mask)
4859 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4861 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4864 ch = i_getch(input);
4865 nommu_addchr(as_string, ch);
4867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4869 debug_printf_parse(": '%c'\n", ch);
4870 o_addchr(dest, ch | quote_mask);
4872 ch = i_peek_and_eat_bkslash_nl(input);
4873 if (!isalnum(ch) && ch != '_') {
4874 /* End of variable name reached */
4877 ch = i_getch(input);
4878 nommu_addchr(as_string, ch);
4880 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4881 } else if (isdigit(ch)) {
4883 ch = i_getch(input);
4884 nommu_addchr(as_string, ch);
4885 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4886 debug_printf_parse(": '%c'\n", ch);
4887 o_addchr(dest, ch | quote_mask);
4888 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4889 } else switch (ch) {
4891 case '!': /* last bg pid */
4892 case '?': /* last exit code */
4893 case '#': /* number of args */
4894 case '*': /* args */
4895 case '@': /* args */
4896 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
4897 goto make_one_char_var;
4901 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4903 ch = i_getch(input); /* eat '{' */
4904 nommu_addchr(as_string, ch);
4906 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4907 /* It should be ${?}, or ${#var},
4908 * or even ${?+subst} - operator acting on a special variable,
4909 * or the beginning of variable name.
4912 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4915 syntax_error_unterm_str("${name}");
4916 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4919 nommu_addchr(as_string, ch);
4923 /* It's possible to just call add_till_closing_bracket() at this point.
4924 * However, this regresses some of our testsuite cases
4925 * which check invalid constructs like ${%}.
4926 * Oh well... let's check that the var name part is fine... */
4932 debug_printf_parse(": '%c'\n", ch);
4934 ch = i_getch(input);
4935 nommu_addchr(as_string, ch);
4939 if (!isalnum(ch) && ch != '_') {
4941 unsigned char last_ch;
4942 /* handle parameter expansions
4943 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4945 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4946 if (len_single_ch != '#'
4947 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4948 || i_peek(input) != '}'
4950 goto bad_dollar_syntax;
4952 /* else: it's "length of C" ${#C} op,
4953 * where C is a single char
4954 * special var name, e.g. ${#!}.
4957 /* Eat everything until closing '}' (or ':') */
4961 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4963 /* It's ${var:N[:M]} thing */
4964 end_ch = '}' * 0x100 + ':';
4966 if (BASH_PATTERN_SUBST
4969 /* It's ${var/[/]pattern[/repl]} thing */
4970 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4972 nommu_addchr(as_string, '/');
4975 end_ch = '}' * 0x100 + '/';
4978 /* The pattern can't be empty.
4979 * IOW: if the first char after "${v//" is a slash,
4980 * it does not terminate the pattern - it's the first char of the pattern:
4981 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4982 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4984 if (i_peek(input) == '/') {
4985 o_addchr(dest, i_getch(input));
4990 #if ENABLE_HUSH_DOLLAR_OPS
4991 last_ch = add_till_closing_bracket(dest, input, end_ch);
4992 if (last_ch == 0) /* error? */
4995 # error Simple code to only allow ${var} is not implemented
4998 o_addstr(as_string, dest->data + pos);
4999 o_addchr(as_string, last_ch);
5002 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5003 && (end_ch & 0xff00)
5005 /* close the first block: */
5006 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5007 /* while parsing N from ${var:N[:M]}
5008 * or pattern from ${var/[/]pattern[/repl]} */
5009 if ((end_ch & 0xff) == last_ch) {
5010 /* got ':' or '/'- parse the rest */
5015 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
5016 /* it's ${var:N} - emulate :999999999 */
5017 o_addstr(dest, "999999999");
5018 } /* else: it's ${var/[/]pattern} */
5022 len_single_ch = 0; /* it can't be ${#C} op */
5024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5027 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
5031 ch = i_getch(input);
5032 nommu_addchr(as_string, ch);
5033 # if ENABLE_FEATURE_SH_MATH
5034 if (i_peek_and_eat_bkslash_nl(input) == '(') {
5035 ch = i_getch(input);
5036 nommu_addchr(as_string, ch);
5037 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5038 o_addchr(dest, /*quote_mask |*/ '+');
5041 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5042 return 0; /* error */
5044 o_addstr(as_string, dest->data + pos);
5045 o_addchr(as_string, ')');
5046 o_addchr(as_string, ')');
5048 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5052 # if ENABLE_HUSH_TICK
5053 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5054 o_addchr(dest, quote_mask | '`');
5057 if (!add_till_closing_bracket(dest, input, ')'))
5058 return 0; /* error */
5060 o_addstr(as_string, dest->data + pos);
5061 o_addchr(as_string, ')');
5063 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5072 /* $_ Shell or shell script name; or last argument of last command
5073 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5074 * but in command's env, set to full pathname used to invoke it */
5075 ch = i_getch(input);
5076 nommu_addchr(as_string, ch);
5077 ch = i_peek_and_eat_bkslash_nl(input);
5078 if (isalnum(ch)) { /* it's $_name or $_123 */
5085 o_addQchr(dest, '$');
5087 debug_printf_parse("parse_dollar return 1 (ok)\n");
5093 #define encode_string(as_string, dest, input, dquote_end) \
5094 encode_string(dest, input, dquote_end)
5095 #define as_string NULL
5097 static int encode_string(o_string *as_string,
5099 struct in_str *input,
5106 ch = i_getch(input);
5108 nommu_addchr(as_string, ch);
5109 if (ch == dquote_end) { /* may be only '"' or EOF */
5110 debug_printf_parse("encode_string return 1 (ok)\n");
5113 /* note: can't move it above ch == dquote_end check! */
5115 syntax_error_unterm_ch('"');
5116 return 0; /* error */
5120 next = i_peek(input);
5122 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
5123 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5126 /* Testcase: in interactive shell a file with
5127 * echo "unterminated string\<eof>
5130 syntax_error_unterm_ch('"');
5131 return 0; /* error */
5134 * "The backslash retains its special meaning [in "..."]
5135 * only when followed by one of the following characters:
5136 * $, `, ", \, or <newline>. A double quote may be quoted
5137 * within double quotes by preceding it with a backslash."
5138 * NB: in (unquoted) heredoc, above does not apply to ",
5139 * therefore we check for it by "next == dquote_end" cond.
5141 if (next == dquote_end || strchr("$`\\\n", next)) {
5142 ch = i_getch(input); /* eat next */
5144 goto again; /* skip \<newline> */
5145 } /* else: ch remains == '\\', and we double it below: */
5146 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
5147 nommu_addchr(as_string, ch);
5151 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5152 debug_printf_parse("encode_string return 0: "
5153 "parse_dollar returned 0 (error)\n");
5158 #if ENABLE_HUSH_TICK
5160 //unsigned pos = dest->length;
5161 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5162 o_addchr(dest, 0x80 | '`');
5163 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5164 return 0; /* error */
5165 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5166 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5170 o_addQchr(dest, ch);
5176 * Scan input until EOF or end_trigger char.
5177 * Return a list of pipes to execute, or NULL on EOF
5178 * or if end_trigger character is met.
5179 * On syntax error, exit if shell is not interactive,
5180 * reset parsing machinery and start parsing anew,
5181 * or return ERR_PTR.
5183 static struct pipe *parse_stream(char **pstring,
5184 int *heredoc_cnt_ptr,
5185 struct in_str *input,
5188 struct parse_context ctx;
5191 /* Single-quote triggers a bypass of the main loop until its mate is
5192 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
5194 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5195 end_trigger ? end_trigger : 'X');
5198 initialize_context(&ctx);
5200 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5203 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
5205 /* We used to separate words on $IFS here. This was wrong.
5206 * $IFS is used only for word splitting when $var is expanded,
5207 * here we should use blank chars as separators, not $IFS
5212 const char *is_blank;
5213 const char *is_special;
5217 redir_type redir_style;
5219 ch = i_getch(input);
5220 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5221 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5226 syntax_error_unterm_str("here document");
5229 if (end_trigger == ')') {
5230 syntax_error_unterm_ch('(');
5233 if (end_trigger == '}') {
5234 syntax_error_unterm_ch('{');
5238 if (done_word(&ctx)) {
5241 o_free_and_set_NULL(&ctx.word);
5242 done_pipe(&ctx, PIPE_SEQ);
5244 /* If we got nothing... */
5245 /* (this makes bare "&" cmd a no-op.
5246 * bash says: "syntax error near unexpected token '&'") */
5247 if (pi->num_cmds == 0
5248 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
5254 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
5256 *pstring = ctx.as_string.data;
5258 o_free(&ctx.as_string);
5260 // heredoc_cnt must be 0 here anyway
5261 //if (heredoc_cnt_ptr)
5262 // *heredoc_cnt_ptr = heredoc_cnt;
5264 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5265 debug_printf_parse("parse_stream return %p\n", pi);
5269 /* Handle "'" and "\" first, as they won't play nice with
5270 * i_peek_and_eat_bkslash_nl() anyway:
5278 ch = i_getch(input);
5280 continue; /* drop \<newline>, get next char */
5281 nommu_addchr(&ctx.as_string, '\\');
5282 o_addchr(&ctx.word, '\\');
5284 /* Testcase: eval 'echo Ok\' */
5285 /* bash-4.3.43 was removing backslash,
5286 * but 4.4.19 retains it, most other shells too
5288 continue; /* get next char */
5290 /* Example: echo Hello \2>file
5291 * we need to know that word 2 is quoted
5293 ctx.word.has_quoted_part = 1;
5294 nommu_addchr(&ctx.as_string, ch);
5295 o_addchr(&ctx.word, ch);
5296 continue; /* get next char */
5298 nommu_addchr(&ctx.as_string, ch);
5300 ctx.word.has_quoted_part = 1;
5301 next = i_getch(input);
5302 if (next == '\'' && !ctx.pending_redirect)
5303 goto insert_empty_quoted_str_marker;
5308 syntax_error_unterm_ch('\'');
5311 nommu_addchr(&ctx.as_string, ch);
5314 if (ch == SPECIAL_VAR_SYMBOL) {
5315 /* Convert raw ^C to corresponding special variable reference */
5316 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5317 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5319 o_addqchr(&ctx.word, ch);
5320 ch = i_getch(input);
5322 continue; /* get next char */
5327 next = i_peek_and_eat_bkslash_nl(input);
5329 is_special = "{}<>;&|()#" /* special outside of "str" */
5330 "$\"" IF_HUSH_TICK("`") /* always special */
5331 SPECIAL_VAR_SYMBOL_STR;
5332 /* Are { and } special here? */
5333 if (ctx.command->argv /* word [word]{... - non-special */
5334 || ctx.word.length /* word{... - non-special */
5335 || ctx.word.has_quoted_part /* ""{... - non-special */
5336 || (next != ';' /* }; - special */
5337 && next != ')' /* }) - special */
5338 && next != '(' /* {( - special */
5339 && next != '&' /* }& and }&& ... - special */
5340 && next != '|' /* }|| ... - special */
5341 && !strchr(defifs, next) /* {word - non-special */
5344 /* They are not special, skip "{}" */
5347 is_special = strchr(is_special, ch);
5348 is_blank = strchr(defifs, ch);
5350 if (!is_special && !is_blank) { /* ordinary char */
5352 o_addQchr(&ctx.word, ch);
5353 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5354 || ctx.is_assignment == WORD_IS_KEYWORD)
5356 && endofname(ctx.word.data)[0] == '='
5358 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5359 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5365 #if ENABLE_HUSH_LINENO_VAR
5367 * "while ...; do<whitespace><newline>
5369 * would think that "cmd" starts in <whitespace> -
5370 * i.e., at the previous line.
5371 * We need to skip all whitespace before newlines.
5373 while (ch != '\n') {
5374 next = i_peek(input);
5375 if (next != ' ' && next != '\t' && next != '\n')
5376 break; /* next char is not ws */
5377 ch = i_getch(input);
5379 /* ch == last eaten whitespace char */
5381 if (done_word(&ctx)) {
5385 /* Is this a case when newline is simply ignored?
5387 * "cmd | <newline> cmd ..."
5388 * "case ... in <newline> word) ..."
5390 if (IS_NULL_CMD(ctx.command)
5391 && ctx.word.length == 0
5392 && !ctx.word.has_quoted_part
5395 /* This newline can be ignored. But...
5396 * Without check #1, interactive shell
5397 * ignores even bare <newline>,
5398 * and shows the continuation prompt:
5399 * ps1_prompt$ <enter>
5400 * ps2> _ <=== wrong, should be ps1
5401 * Without check #2, "cmd & <newline>"
5402 * is similarly mistreated.
5403 * (BTW, this makes "cmd & cmd"
5404 * and "cmd && cmd" non-orthogonal.
5405 * Really, ask yourself, why
5406 * "cmd && <newline>" doesn't start
5407 * cmd but waits for more input?
5408 * The only reason is that it might be
5409 * a "cmd1 && <nl> cmd2 &" construct,
5410 * cmd1 may need to run in BG).
5412 struct pipe *pi = ctx.list_head;
5413 if (pi->num_cmds != 0 /* check #1 */
5414 && pi->followup != PIPE_BG /* check #2 */
5419 /* Treat newline as a command separator. */
5420 done_pipe(&ctx, PIPE_SEQ);
5421 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
5423 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5424 if (heredoc_cnt != 0)
5427 ctx.is_assignment = MAYBE_ASSIGNMENT;
5428 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5430 /* note: if (is_blank) continue;
5431 * will still trigger for us */
5435 /* "cmd}" or "cmd }..." without semicolon or &:
5436 * } is an ordinary char in this case, even inside { cmd; }
5437 * Pathological example: { ""}; } should exec "}" cmd
5440 if (ctx.word.length != 0 /* word} */
5441 || ctx.word.has_quoted_part /* ""} */
5445 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5446 /* Generally, there should be semicolon: "cmd; }"
5447 * However, bash allows to omit it if "cmd" is
5448 * a group. Examples:
5451 * { echo 0 >&2 | { echo 1; } }
5452 * { while false; do :; done }
5453 * { case a in b) ;; esac }
5455 if (ctx.command->group)
5459 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5460 /* Can't be an end of {cmd}, skip the check */
5461 goto skip_end_trigger;
5462 /* else: } does terminate a group */
5465 if (end_trigger && end_trigger == ch
5466 && (ch != ';' || heredoc_cnt == 0)
5467 #if ENABLE_HUSH_CASE
5469 || ctx.ctx_res_w != RES_MATCH
5470 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
5474 if (done_word(&ctx)) {
5477 done_pipe(&ctx, PIPE_SEQ);
5478 ctx.is_assignment = MAYBE_ASSIGNMENT;
5479 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5480 /* Do we sit outside of any if's, loops or case's? */
5482 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5484 o_free_and_set_NULL(&ctx.word);
5486 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5488 *pstring = ctx.as_string.data;
5490 o_free(&ctx.as_string);
5492 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5493 /* Example: bare "{ }", "()" */
5494 G.last_exitcode = 2; /* bash compat */
5495 syntax_error_unexpected_ch(ch);
5498 if (heredoc_cnt_ptr)
5499 *heredoc_cnt_ptr = heredoc_cnt;
5500 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
5501 debug_printf_parse("parse_stream return %p: "
5502 "end_trigger char found\n",
5505 return ctx.list_head;
5512 /* Catch <, > before deciding whether this word is
5513 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5516 redir_fd = redirect_opt_num(&ctx.word);
5517 if (done_word(&ctx)) {
5520 redir_style = REDIRECT_OVERWRITE;
5522 redir_style = REDIRECT_APPEND;
5523 ch = i_getch(input);
5524 nommu_addchr(&ctx.as_string, ch);
5527 else if (next == '(') {
5528 syntax_error(">(process) not supported");
5532 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5534 continue; /* get next char */
5536 redir_fd = redirect_opt_num(&ctx.word);
5537 if (done_word(&ctx)) {
5540 redir_style = REDIRECT_INPUT;
5542 redir_style = REDIRECT_HEREDOC;
5544 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
5545 ch = i_getch(input);
5546 nommu_addchr(&ctx.as_string, ch);
5547 } else if (next == '>') {
5548 redir_style = REDIRECT_IO;
5549 ch = i_getch(input);
5550 nommu_addchr(&ctx.as_string, ch);
5553 else if (next == '(') {
5554 syntax_error("<(process) not supported");
5558 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5560 continue; /* get next char */
5562 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
5563 /* skip "#comment" */
5564 /* note: we do not add it to &ctx.as_string */
5566 * comment inside $() goes to the next \n, even inside quoted string (!):
5567 * cmd "$(cmd2 #comment)" - syntax error
5568 * cmd "`cmd2 #comment`" - ok
5569 * We accept both (comment ends where command subst ends, in both cases).
5574 nommu_addchr(&ctx.as_string, '\n');
5577 ch = i_getch(input);
5581 continue; /* get next char */
5587 if (ctx.is_assignment == MAYBE_ASSIGNMENT
5588 /* check that we are not in word in "a=1 2>word b=1": */
5589 && !ctx.pending_redirect
5591 /* ch is a special char and thus this word
5592 * cannot be an assignment */
5593 ctx.is_assignment = NOT_ASSIGNMENT;
5594 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5597 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5600 case SPECIAL_VAR_SYMBOL:
5601 /* Convert raw ^C to corresponding special variable reference */
5602 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5603 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5606 /* non-comment #: "echo a#b" etc */
5607 o_addchr(&ctx.word, ch);
5608 continue; /* get next char */
5610 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
5611 debug_printf_parse("parse_stream parse error: "
5612 "parse_dollar returned 0 (error)\n");
5615 continue; /* get next char */
5617 ctx.word.has_quoted_part = 1;
5618 if (next == '"' && !ctx.pending_redirect) {
5619 i_getch(input); /* eat second " */
5620 insert_empty_quoted_str_marker:
5621 nommu_addchr(&ctx.as_string, next);
5622 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5623 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5624 continue; /* get next char */
5626 if (ctx.is_assignment == NOT_ASSIGNMENT)
5627 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5628 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
5630 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5631 continue; /* get next char */
5632 #if ENABLE_HUSH_TICK
5634 USE_FOR_NOMMU(unsigned pos;)
5636 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5637 o_addchr(&ctx.word, '`');
5638 USE_FOR_NOMMU(pos = ctx.word.length;)
5639 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
5642 o_addstr(&ctx.as_string, ctx.word.data + pos);
5643 o_addchr(&ctx.as_string, '`');
5645 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5646 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
5647 continue; /* get next char */
5651 #if ENABLE_HUSH_CASE
5654 if (done_word(&ctx)) {
5657 done_pipe(&ctx, PIPE_SEQ);
5658 #if ENABLE_HUSH_CASE
5659 /* Eat multiple semicolons, detect
5660 * whether it means something special */
5662 ch = i_peek_and_eat_bkslash_nl(input);
5665 ch = i_getch(input);
5666 nommu_addchr(&ctx.as_string, ch);
5667 if (ctx.ctx_res_w == RES_CASE_BODY) {
5668 ctx.ctx_dsemicolon = 1;
5669 ctx.ctx_res_w = RES_MATCH;
5675 /* We just finished a cmd. New one may start
5676 * with an assignment */
5677 ctx.is_assignment = MAYBE_ASSIGNMENT;
5678 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
5679 continue; /* get next char */
5681 if (done_word(&ctx)) {
5685 ch = i_getch(input);
5686 nommu_addchr(&ctx.as_string, ch);
5687 done_pipe(&ctx, PIPE_AND);
5689 done_pipe(&ctx, PIPE_BG);
5693 if (done_word(&ctx)) {
5696 #if ENABLE_HUSH_CASE
5697 if (ctx.ctx_res_w == RES_MATCH)
5698 break; /* we are in case's "word | word)" */
5700 if (next == '|') { /* || */
5701 ch = i_getch(input);
5702 nommu_addchr(&ctx.as_string, ch);
5703 done_pipe(&ctx, PIPE_OR);
5705 /* we could pick up a file descriptor choice here
5706 * with redirect_opt_num(), but bash doesn't do it.
5707 * "echo foo 2| cat" yields "foo 2". */
5712 #if ENABLE_HUSH_CASE
5713 /* "case... in [(]word)..." - skip '(' */
5714 if (ctx.ctx_res_w == RES_MATCH
5715 && ctx.command->argv == NULL /* not (word|(... */
5716 && ctx.word.length == 0 /* not word(... */
5717 && ctx.word.has_quoted_part == 0 /* not ""(... */
5719 continue; /* get next char */
5724 int n = parse_group(&ctx, input, ch);
5728 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5733 #if ENABLE_HUSH_CASE
5734 if (ctx.ctx_res_w == RES_MATCH)
5739 /* proper use of this character is caught by end_trigger:
5740 * if we see {, we call parse_group(..., end_trigger='}')
5741 * and it will match } earlier (not here). */
5742 G.last_exitcode = 2;
5743 syntax_error_unexpected_ch(ch);
5747 bb_error_msg_and_die("BUG: unexpected %c", ch);
5752 G.last_exitcode = 1;
5755 struct parse_context *pctx;
5756 IF_HAS_KEYWORDS(struct parse_context *p2;)
5758 /* Clean up allocated tree.
5759 * Sample for finding leaks on syntax error recovery path.
5760 * Run it from interactive shell, watch pmap `pidof hush`.
5761 * while if false; then false; fi; do break; fi
5762 * Samples to catch leaks at execution:
5763 * while if (true | { true;}); then echo ok; fi; do break; done
5764 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5768 /* Update pipe/command counts,
5769 * otherwise freeing may miss some */
5770 done_pipe(pctx, PIPE_SEQ);
5771 debug_printf_clean("freeing list %p from ctx %p\n",
5772 pctx->list_head, pctx);
5773 debug_print_tree(pctx->list_head, 0);
5774 free_pipe_list(pctx->list_head);
5775 debug_printf_clean("freed list %p\n", pctx->list_head);
5777 o_free(&pctx->as_string);
5779 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5783 IF_HAS_KEYWORDS(pctx = p2;)
5784 } while (HAS_KEYWORDS && pctx);
5797 /*** Execution routines ***/
5799 /* Expansion can recurse, need forward decls: */
5800 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5801 #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
5802 expand_string_to_string(str)
5804 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
5805 #if ENABLE_HUSH_TICK
5806 static int process_command_subs(o_string *dest, const char *s);
5808 static int expand_vars_to_list(o_string *output, int n, char *arg);
5810 /* expand_strvec_to_strvec() takes a list of strings, expands
5811 * all variable references within and returns a pointer to
5812 * a list of expanded strings, possibly with larger number
5813 * of strings. (Think VAR="a b"; echo $VAR).
5814 * This new list is allocated as a single malloc block.
5815 * NULL-terminated list of char* pointers is at the beginning of it,
5816 * followed by strings themselves.
5817 * Caller can deallocate entire list by single free(list). */
5819 /* A horde of its helpers come first: */
5821 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5823 while (--len >= 0) {
5826 #if ENABLE_HUSH_BRACE_EXPANSION
5827 if (c == '{' || c == '}') {
5828 /* { -> \{, } -> \} */
5830 /* And now we want to add { or } and continue:
5833 * luckily, just falling through achieves this.
5839 /* \z -> \\\z; \<eol> -> \\<eol> */
5844 o_addchr(o, *str++);
5850 /* Store given string, finalizing the word and starting new one whenever
5851 * we encounter IFS char(s). This is used for expanding variable values.
5852 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5853 * Return in output->ended_in_ifs:
5854 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5856 static int expand_on_ifs(o_string *output, int n, const char *str)
5858 int last_is_ifs = 0;
5863 if (!*str) /* EOL - do not finalize word */
5865 word_len = strcspn(str, G.ifs);
5867 /* We have WORD_LEN leading non-IFS chars */
5868 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5869 o_addblock(output, str, word_len);
5871 /* Protect backslashes against globbing up :)
5872 * Example: "v='\*'; echo b$v" prints "b\*"
5873 * (and does not try to glob on "*")
5875 o_addblock_duplicate_backslash(output, str, word_len);
5876 /*/ Why can't we do it easier? */
5877 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5878 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5882 if (!*str) /* EOL - do not finalize word */
5886 /* We know str here points to at least one IFS char */
5888 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
5889 if (!*str) /* EOL - do not finalize word */
5892 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5893 && strchr(G.ifs, *str) /* the second check would fail */
5895 /* This is a non-whitespace $IFS char */
5896 /* Skip it and IFS whitespace chars, start new word */
5898 str += strspn(str, G.ifs_whitespace);
5902 /* Start new word... but not always! */
5903 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5904 if (output->has_quoted_part
5906 * Case "v=' a'; echo $v":
5907 * here nothing precedes the space in $v expansion,
5908 * therefore we should not finish the word
5909 * (IOW: if there *is* word to finalize, only then do it):
5910 * It's okay if this accesses the byte before first argv[]:
5911 * past call to o_save_ptr() cleared it to zero byte
5912 * (grep for -prev-ifs-check-).
5914 || output->data[output->length - 1]
5917 o_addchr(output, '\0');
5918 debug_print_list("expand_on_ifs", output, n);
5919 n = o_save_ptr(output, n);
5923 output->ended_in_ifs = last_is_ifs;
5924 debug_print_list("expand_on_ifs[1]", output, n);
5928 /* Helper to expand $((...)) and heredoc body. These act as if
5929 * they are in double quotes, with the exception that they are not :).
5930 * Just the rules are similar: "expand only $var and `cmd`"
5932 * Returns malloced string.
5933 * As an optimization, we return NULL if expansion is not needed.
5935 static char *encode_then_expand_string(const char *str)
5938 struct in_str input;
5939 o_string dest = NULL_O_STRING;
5944 if (!*cp) return NULL; /* string has no special chars */
5945 if (*cp == '$') break;
5946 if (*cp == '\\') break;
5947 #if ENABLE_HUSH_TICK
5948 if (*cp == '`') break;
5953 /* We need to expand. Example:
5954 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5956 setup_string_in_str(&input, str);
5957 encode_string(NULL, &dest, &input, EOF);
5958 //TODO: error check (encode_string returns 0 on error)?
5959 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5960 exp_str = expand_string_to_string(dest.data,
5961 EXP_FLAG_ESC_GLOB_CHARS,
5964 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5969 static const char *first_special_char_in_vararg(const char *cp)
5972 if (!*cp) return NULL; /* string has no special chars */
5973 if (*cp == '$') return cp;
5974 if (*cp == '\\') return cp;
5975 if (*cp == '\'') return cp;
5976 if (*cp == '"') return cp;
5977 #if ENABLE_HUSH_TICK
5978 if (*cp == '`') return cp;
5980 /* dquoted "${x:+ARG}" should not glob, therefore
5981 * '*' et al require some non-literal processing: */
5982 if (*cp == '*') return cp;
5983 if (*cp == '?') return cp;
5984 if (*cp == '[') return cp;
5989 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5990 * These can contain single- and double-quoted strings,
5991 * and treated as if the ARG string is initially unquoted. IOW:
5992 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5993 * a dquoted string: "${var#"zz"}"), the difference only comes later
5994 * (word splitting and globbing of the ${var...} result).
5996 #if !BASH_PATTERN_SUBST
5997 #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5998 encode_then_expand_vararg(str, handle_squotes)
6000 static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6002 #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
6003 const int do_unbackslash = 0;
6006 struct in_str input;
6007 o_string dest = NULL_O_STRING;
6009 if (!first_special_char_in_vararg(str)) {
6010 /* string has no special chars */
6014 setup_string_in_str(&input, str);
6015 dest.data = xzalloc(1); /* start as "", not as NULL */
6021 ch = i_getch(&input);
6022 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6023 __func__, ch, ch, !!dest.o_expflags);
6025 if (!dest.o_expflags) {
6028 if (handle_squotes && ch == '\'') {
6029 if (!add_till_single_quote_dquoted(&dest, &input))
6030 goto ret; /* error */
6035 syntax_error_unterm_ch('"');
6036 goto ret; /* error */
6039 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6043 ch = i_getch(&input);
6045 //example? error message? syntax_error_unterm_ch('"');
6046 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6049 o_addqchr(&dest, ch);
6053 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6054 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6059 #if ENABLE_HUSH_TICK
6061 //unsigned pos = dest->length;
6062 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6063 o_addchr(&dest, 0x80 | '`');
6064 if (!add_till_backquote(&dest, &input,
6065 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6068 goto ret; /* error */
6070 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6071 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6075 o_addQchr(&dest, ch);
6078 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6079 exp_str = expand_string_to_string(dest.data,
6080 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6084 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
6089 /* Expanding ARG in ${var+ARG}, ${var-ARG}
6091 static int encode_then_append_var_plusminus(o_string *output, int n,
6092 char *str, int dquoted)
6094 struct in_str input;
6095 o_string dest = NULL_O_STRING;
6097 if (!first_special_char_in_vararg(str)
6098 && '\0' == str[strcspn(str, G.ifs)]
6100 /* string has no special chars
6101 * && string has no $IFS chars
6104 /* Prints 1 (quoted expansion is a "" word, not nothing):
6105 * set -- "${notexist-}"; echo $#
6107 output->has_quoted_part = 1;
6109 return expand_vars_to_list(output, n, str);
6112 setup_string_in_str(&input, str);
6117 ch = i_getch(&input);
6118 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6119 __func__, ch, ch, dest.o_expflags);
6121 if (!dest.o_expflags) {
6124 if (!dquoted && strchr(G.ifs, ch)) {
6125 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6126 * do not assume we are at the start of the word (PREFIX above).
6129 n = expand_vars_to_list(output, n, dest.data);
6130 o_free_and_set_NULL(&dest);
6131 o_addchr(output, '\0');
6132 n = o_save_ptr(output, n); /* create next word */
6134 if (output->length != o_get_last_ptr(output, n)
6135 || output->has_quoted_part
6138 * f() { for i; do echo "|$i|"; done; }; x=x
6139 * f a${x:+ }b # 1st condition
6142 * f ""${x:+ }b # 2nd condition
6146 o_addchr(output, '\0');
6147 n = o_save_ptr(output, n); /* create next word */
6151 if (!dquoted && ch == '\'') {
6152 if (!add_till_single_quote_dquoted(&dest, &input))
6153 goto ret; /* error */
6154 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6155 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6160 syntax_error_unterm_ch('"');
6161 goto ret; /* error */
6164 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6165 if (dest.o_expflags) {
6166 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6167 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6172 ch = i_getch(&input);
6174 //example? error message? syntax_error_unterm_ch('"');
6175 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6178 o_addqchr(&dest, ch);
6182 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6183 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6188 #if ENABLE_HUSH_TICK
6190 //unsigned pos = dest->length;
6191 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6192 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6193 if (!add_till_backquote(&dest, &input,
6194 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6197 goto ret; /* error */
6199 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6200 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6205 /* Always glob-protect if in dquotes:
6206 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6207 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6209 o_addqchr(&dest, ch);
6211 /* Glob-protect only if char is quoted:
6212 * x=x; echo ${x:+/bin/c*} - prints many filenames
6213 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6215 o_addQchr(&dest, ch);
6220 n = expand_vars_to_list(output, n, dest.data);
6227 #if ENABLE_FEATURE_SH_MATH
6228 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
6230 arith_state_t math_state;
6234 math_state.lookupvar = get_local_var_value;
6235 math_state.setvar = set_local_var_from_halves;
6236 //math_state.endofname = endofname;
6237 exp_str = encode_then_expand_string(arg);
6238 res = arith(&math_state, exp_str ? exp_str : arg);
6241 *errmsg_p = math_state.errmsg;
6242 if (math_state.errmsg)
6243 msg_and_die_if_script(math_state.errmsg);
6248 #if BASH_PATTERN_SUBST
6249 /* ${var/[/]pattern[/repl]} helpers */
6250 static char *strstr_pattern(char *val, const char *pattern, int *size)
6253 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6254 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6261 /* Optimization: if "*pat" did not match the start of "string",
6262 * we know that "tring", "ring" etc will not match too:
6264 if (pattern[0] == '*')
6269 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6271 char *result = NULL;
6272 unsigned res_len = 0;
6273 unsigned repl_len = strlen(repl);
6275 /* Null pattern never matches, including if "var" is empty */
6277 return result; /* NULL, no replaces happened */
6281 char *s = strstr_pattern(val, pattern, &size);
6285 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
6286 strcpy(mempcpy(result + res_len, val, s - val), repl);
6287 res_len += (s - val) + repl_len;
6288 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6294 if (*val && result) {
6295 result = xrealloc(result, res_len + strlen(val) + 1);
6296 strcpy(result + res_len, val);
6297 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6299 debug_printf_varexp("result:'%s'\n", result);
6302 #endif /* BASH_PATTERN_SUBST */
6304 static int append_str_maybe_ifs_split(o_string *output, int n,
6305 int first_ch, const char *val)
6307 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6308 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6309 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6311 n = expand_on_ifs(output, n, val);
6312 } else { /* quoted "$VAR" */
6313 output->has_quoted_part = 1;
6314 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6315 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6317 o_addQstr(output, val);
6322 /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6324 static NOINLINE int expand_one_var(o_string *output, int n,
6325 int first_ch, char *arg, char **pp)
6332 char exp_save = exp_save; /* for compiler */
6333 char *exp_saveptr; /* points to expansion operator */
6334 char *exp_word = exp_word; /* for compiler */
6340 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
6342 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
6344 arg[0] = (arg0 & 0x7f);
6347 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
6348 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6349 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6350 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
6352 /* It must be length operator: ${#var} */
6356 /* Maybe handle parameter expansion */
6357 if (exp_saveptr /* if 2nd char is one of expansion operators */
6358 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
6360 /* ${?:0}, ${#[:]%0} etc */
6361 exp_saveptr = var + 1;
6363 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6364 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6366 exp_op = exp_save = *exp_saveptr;
6368 exp_word = exp_saveptr + 1;
6369 if (exp_op == ':') {
6370 exp_op = *exp_word++;
6371 //TODO: try ${var:} and ${var:bogus} in non-bash config
6373 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
6375 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6380 *exp_saveptr = '\0';
6381 } /* else: it's not an expansion op, but bare ${var} */
6384 /* Look up the variable in question */
6385 if (isdigit(var[0])) {
6386 /* parse_dollar should have vetted var for us */
6387 int nn = xatoi_positive(var);
6388 if (nn < G.global_argc)
6389 val = G.global_argv[nn];
6390 /* else val remains NULL: $N with too big N */
6394 val = utoa(G.root_pid);
6396 case '!': /* bg pid */
6397 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6399 case '?': /* exitcode */
6400 val = utoa(G.last_exitcode);
6402 case '#': /* argc */
6403 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6405 case '-': { /* active options */
6406 /* Check set_mode() to see what option chars we support */
6408 val = cp = G.optstring_buf;
6409 if (G.o_opt[OPT_O_ERREXIT])
6411 if (G_interactive_fd)
6415 /* If G.o_opt[OPT_O_NOEXEC] is true,
6416 * commands read but are not executed,
6417 * so $- can not execute too, 'n' is never seen in $-.
6427 val = get_local_var_value(var);
6431 /* Handle any expansions */
6432 if (exp_op == 'L') {
6433 reinit_unicode_for_hush();
6434 debug_printf_expand("expand: length(%s)=", val);
6435 val = utoa(val ? unicode_strlen(val) : 0);
6436 debug_printf_expand("%s\n", val);
6437 } else if (exp_op) {
6438 if (exp_op == '%' || exp_op == '#') {
6439 /* Standard-mandated substring removal ops:
6440 * ${parameter%word} - remove smallest suffix pattern
6441 * ${parameter%%word} - remove largest suffix pattern
6442 * ${parameter#word} - remove smallest prefix pattern
6443 * ${parameter##word} - remove largest prefix pattern
6445 * Word is expanded to produce a glob pattern.
6446 * Then var's value is matched to it and matching part removed.
6448 //FIXME: ${x#...${...}...}
6449 //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6450 //inner ${...} may have side effects!
6451 if (val && val[0]) {
6455 unsigned scan_flags = pick_scan(exp_op, *exp_word);
6456 if (exp_op == *exp_word) /* ## or %% */
6458 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6459 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6461 exp_word = exp_exp_word;
6462 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6464 * HACK ALERT. We depend here on the fact that
6465 * G.global_argv and results of utoa and get_local_var_value
6466 * are actually in writable memory:
6467 * scan_and_match momentarily stores NULs there.
6470 loc = scan_and_match(t, exp_word, scan_flags);
6471 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
6473 if (loc) { /* match was found */
6474 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
6475 val = loc; /* take right part */
6477 val = to_be_freed = xstrndup(val, loc - val); /* left */
6481 #if BASH_PATTERN_SUBST
6482 else if (exp_op == '/' || exp_op == '\\') {
6483 /* It's ${var/[/]pattern[/repl]} thing.
6484 * Note that in encoded form it has TWO parts:
6485 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6486 * and if // is used, it is encoded as \:
6487 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
6489 if (val && val[0]) {
6490 /* pattern uses non-standard expansion.
6491 * repl should be unbackslashed and globbed
6492 * by the usual expansion rules:
6494 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6495 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6496 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6497 * v='a bz'; echo ${v/a*z/\z} #prints "z"
6498 * (note that a*z _pattern_ is never globbed!)
6500 char *pattern, *repl, *t;
6501 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
6503 pattern = xstrdup(exp_word);
6504 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6505 *p++ = SPECIAL_VAR_SYMBOL;
6507 p = strchr(p, SPECIAL_VAR_SYMBOL);
6509 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
6510 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6511 /* HACK ALERT. We depend here on the fact that
6512 * G.global_argv and results of utoa and get_local_var_value
6513 * are actually in writable memory:
6514 * replace_pattern momentarily stores NULs there. */
6516 to_be_freed = replace_pattern(t,
6518 (repl ? repl : exp_word),
6520 if (to_be_freed) /* at least one replace happened */
6525 /* Empty variable always gives nothing */
6526 // "v=''; echo ${v/*/w}" prints "", not "w"
6527 /* Just skip "replace" part */
6528 *p++ = SPECIAL_VAR_SYMBOL;
6529 p = strchr(p, SPECIAL_VAR_SYMBOL);
6533 #endif /* BASH_PATTERN_SUBST */
6534 else if (exp_op == ':') {
6535 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
6536 /* It's ${var:N[:M]} bashism.
6537 * Note that in encoded form it has TWO parts:
6538 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6543 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6546 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6547 *p++ = SPECIAL_VAR_SYMBOL;
6549 p = strchr(p, SPECIAL_VAR_SYMBOL);
6551 len = expand_and_evaluate_arith(exp_word, &errmsg);
6554 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
6556 /* negative beg counts from the end */
6557 beg = (arith_t)strlen(val) + beg;
6558 if (beg < 0) /* ${v: -999999} is "" */
6561 debug_printf_varexp("from val:'%s'\n", val);
6563 /* in bash, len=-n means strlen()-n */
6564 len = (arith_t)strlen(val) - beg + len;
6565 if (len < 0) /* bash compat */
6566 msg_and_die_if_script("%s: substring expression < 0", var);
6568 if (len <= 0 || !val || beg >= strlen(val)) {
6572 /* Paranoia. What if user entered 9999999999999
6573 * which fits in arith_t but not int? */
6576 val = to_be_freed = xstrndup(val + beg, len);
6578 debug_printf_varexp("val:'%s'\n", val);
6579 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
6580 msg_and_die_if_script("malformed ${%s:...}", var);
6583 } else { /* one of "-=+?" */
6584 /* Standard-mandated substitution ops:
6585 * ${var?word} - indicate error if unset
6586 * If var is unset, word (or a message indicating it is unset
6587 * if word is null) is written to standard error
6588 * and the shell exits with a non-zero exit status.
6589 * Otherwise, the value of var is substituted.
6590 * ${var-word} - use default value
6591 * If var is unset, word is substituted.
6592 * ${var=word} - assign and use default value
6593 * If var is unset, word is assigned to var.
6594 * In all cases, final value of var is substituted.
6595 * ${var+word} - use alternative value
6596 * If var is unset, null is substituted.
6597 * Otherwise, word is substituted.
6599 * Word is subjected to tilde expansion, parameter expansion,
6600 * command substitution, and arithmetic expansion.
6601 * If word is not needed, it is not expanded.
6603 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6604 * but also treat null var as if it is unset.
6606 * Word-splitting and single quote behavior:
6608 * $ f() { for i; do echo "|$i|"; done; };
6610 * $ x=; f ${x:?'x y' z}
6611 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6612 * $ x=; f "${x:?'x y' z}"
6613 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6615 * $ x=; f ${x:='x y' z}
6619 * $ x=; f "${x:='x y' z}"
6622 * $ x=x; f ${x:+'x y' z}
6625 * $ x=x; f "${x:+'x y' z}"
6628 * $ x=; f ${x:-'x y' z}
6631 * $ x=; f "${x:-'x y' z}"
6634 int use_word = (!val || ((exp_save == ':') && !val[0]));
6636 use_word = !use_word;
6637 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6638 (exp_save == ':') ? "true" : "false", use_word);
6640 if (exp_op == '+' || exp_op == '-') {
6641 /* ${var+word} - use alternative value */
6642 /* ${var-word} - use default value */
6643 n = encode_then_append_var_plusminus(output, n, exp_word,
6644 /*dquoted:*/ (arg0 & 0x80)
6648 /* ${var?word} - indicate error if unset */
6649 /* ${var=word} - assign and use default value */
6650 to_be_freed = encode_then_expand_vararg(exp_word,
6651 /*handle_squotes:*/ !(arg0 & 0x80),
6655 exp_word = to_be_freed;
6656 if (exp_op == '?') {
6657 /* mimic bash message */
6658 msg_and_die_if_script("%s: %s",
6662 : "parameter null or not set"
6663 /* ash has more specific messages, a-la: */
6664 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6666 //TODO: how interactive bash aborts expansion mid-command?
6667 //It aborts the entire line, returns to prompt:
6668 // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6671 // ("echo YO" is not executed, neither the f function call)
6675 if (exp_op == '=') {
6676 /* ${var=[word]} or ${var:=[word]} */
6677 if (isdigit(var[0]) || var[0] == '#') {
6678 /* mimic bash message */
6679 msg_and_die_if_script("$%s: cannot assign in this way", var);
6682 char *new_var = xasprintf("%s=%s", var, val);
6683 set_local_var(new_var, /*flag:*/ 0);
6688 } /* one of "-=+?" */
6690 *exp_saveptr = exp_save;
6696 n = append_str_maybe_ifs_split(output, n, first_ch, val);
6702 /* Expand all variable references in given string, adding words to list[]
6703 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6704 * to be filled). This routine is extremely tricky: has to deal with
6705 * variables/parameters with whitespace, $* and $@, and constructs like
6706 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
6707 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
6709 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
6710 * expansion of right-hand side of assignment == 1-element expand.
6712 char cant_be_null = 0; /* only bit 0x80 matters */
6715 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6716 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
6717 debug_print_list("expand_vars_to_list[0]", output, n);
6719 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6721 #if ENABLE_FEATURE_SH_MATH
6722 char arith_buf[sizeof(arith_t)*3 + 2];
6725 if (output->ended_in_ifs) {
6726 o_addchr(output, '\0');
6727 n = o_save_ptr(output, n);
6728 output->ended_in_ifs = 0;
6731 o_addblock(output, arg, p - arg);
6732 debug_print_list("expand_vars_to_list[1]", output, n);
6734 p = strchr(p, SPECIAL_VAR_SYMBOL);
6736 /* Fetch special var name (if it is indeed one of them)
6737 * and quote bit, force the bit on if singleword expansion -
6738 * important for not getting v=$@ expand to many words. */
6739 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
6741 /* Is this variable quoted and thus expansion can't be null?
6742 * "$@" is special. Even if quoted, it can still
6743 * expand to nothing (not even an empty string),
6744 * thus it is excluded. */
6745 if ((first_ch & 0x7f) != '@')
6746 cant_be_null |= first_ch;
6748 switch (first_ch & 0x7f) {
6749 /* Highest bit in first_ch indicates that var is double-quoted */
6753 if (!G.global_argv[1])
6756 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
6757 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
6758 while (G.global_argv[i]) {
6759 n = expand_on_ifs(output, n, G.global_argv[i]);
6760 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6761 if (G.global_argv[i++][0] && G.global_argv[i]) {
6762 /* this argv[] is not empty and not last:
6763 * put terminating NUL, start new word */
6764 o_addchr(output, '\0');
6765 debug_print_list("expand_vars_to_list[2]", output, n);
6766 n = o_save_ptr(output, n);
6767 debug_print_list("expand_vars_to_list[3]", output, n);
6771 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6772 * and in this case should treat it like '$*' - see 'else...' below */
6773 if (first_ch == (char)('@'|0x80) /* quoted $@ */
6774 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6777 o_addQstr(output, G.global_argv[i]);
6778 if (++i >= G.global_argc)
6780 o_addchr(output, '\0');
6781 debug_print_list("expand_vars_to_list[4]", output, n);
6782 n = o_save_ptr(output, n);
6784 } else { /* quoted $* (or v="$@" case): add as one word */
6786 o_addQstr(output, G.global_argv[i]);
6787 if (!G.global_argv[++i])
6790 o_addchr(output, G.ifs[0]);
6792 output->has_quoted_part = 1;
6796 case SPECIAL_VAR_SYMBOL: {
6797 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6798 /* "Empty variable", used to make "" etc to not disappear */
6799 output->has_quoted_part = 1;
6800 cant_be_null = 0x80;
6804 case SPECIAL_VAR_QUOTED_SVS:
6805 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6806 /* "^C variable", represents literal ^C char (possible in scripts) */
6807 o_addchr(output, SPECIAL_VAR_SYMBOL);
6810 #if ENABLE_HUSH_TICK
6812 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6813 o_string subst_result = NULL_O_STRING;
6815 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6817 /* Can't just stuff it into output o_string,
6818 * expanded result may need to be globbed
6820 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6821 G.last_exitcode = process_command_subs(&subst_result, arg);
6822 G.expand_exitcode = G.last_exitcode;
6823 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6824 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
6825 o_free(&subst_result);
6829 #if ENABLE_FEATURE_SH_MATH
6831 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
6834 arg++; /* skip '+' */
6835 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6836 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6837 res = expand_and_evaluate_arith(arg, NULL);
6838 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6839 sprintf(arith_buf, ARITH_FMT, res);
6840 o_addstr(output, arith_buf);
6845 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
6846 n = expand_one_var(output, n, first_ch, arg, &p);
6848 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6850 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6851 * Do the check to avoid writing to a const string. */
6852 if (*p != SPECIAL_VAR_SYMBOL)
6853 *p = SPECIAL_VAR_SYMBOL;
6855 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6858 /* handle trailing string */
6859 if (output->ended_in_ifs) {
6860 o_addchr(output, '\0');
6861 n = o_save_ptr(output, n);
6863 debug_print_list("expand_vars_to_list[a]", output, n);
6864 /* this part is literal, and it was already pre-quoted
6865 * if needed (much earlier), do not use o_addQstr here!
6867 o_addstr(output, arg);
6868 debug_print_list("expand_vars_to_list[b]", output, n);
6870 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6871 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6872 && !output->has_quoted_part
6875 /* allow to reuse list[n] later without re-growth */
6876 output->has_empty_slot = 1;
6882 static char **expand_variables(char **argv, unsigned expflags)
6886 o_string output = NULL_O_STRING;
6888 output.o_expflags = expflags;
6892 /* go to next list[n] */
6893 output.ended_in_ifs = 0;
6894 n = o_save_ptr(&output, n);
6899 /* expand argv[i] */
6900 n = expand_vars_to_list(&output, n, *argv++);
6901 /* if (!output->has_empty_slot) -- need this?? */
6902 o_addchr(&output, '\0');
6904 debug_print_list("expand_variables", &output, n);
6906 /* output.data (malloced in one block) gets returned in "list" */
6907 list = o_finalize_list(&output, n);
6908 debug_print_strings("expand_variables[1]", list);
6912 static char **expand_strvec_to_strvec(char **argv)
6914 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6917 #if defined(CMD_SINGLEWORD_NOGLOB)
6918 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6920 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6924 /* Used for expansion of right hand of assignments,
6925 * $((...)), heredocs, variable expansion parts.
6927 * NB: should NOT do globbing!
6928 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6930 static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
6932 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6933 const int do_unbackslash = 1;
6934 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
6936 char *argv[2], **list;
6938 debug_printf_expand("string_to_string<='%s'\n", str);
6939 /* This is generally an optimization, but it also
6940 * handles "", which otherwise trips over !list[0] check below.
6941 * (is this ever happens that we actually get str="" here?)
6943 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6944 //TODO: Can use on strings with \ too, just unbackslash() them?
6945 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6946 return xstrdup(str);
6949 argv[0] = (char*)str;
6951 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
6953 /* Example where it happens:
6954 * x=; echo ${x:-"$@"}
6956 ((char*)list)[0] = '\0';
6960 bb_simple_error_msg_and_die("BUG in varexp2");
6961 /* actually, just move string 2*sizeof(char*) bytes back */
6962 overlapping_strcpy((char*)list, list[0]);
6964 unbackslash((char*)list);
6966 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6971 static char* expand_strvec_to_string(char **argv)
6975 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6976 /* Convert all NULs to spaces */
6981 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6982 bb_error_msg_and_die("BUG in varexp3");
6983 /* bash uses ' ' regardless of $IFS contents */
6988 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6989 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6994 static char **expand_assignments(char **argv, int count)
6999 G.expanded_assignments = p = NULL;
7000 /* Expand assignments into one string each */
7001 for (i = 0; i < count; i++) {
7002 p = add_string_to_strings(p,
7003 expand_string_to_string(argv[i],
7004 EXP_FLAG_ESC_GLOB_CHARS,
7008 G.expanded_assignments = p;
7010 G.expanded_assignments = NULL;
7015 static void switch_off_special_sigs(unsigned mask)
7018 while ((mask >>= 1) != 0) {
7022 #if ENABLE_HUSH_TRAP
7024 if (G_traps[sig] && !G_traps[sig][0])
7025 /* trap is '', has to remain SIG_IGN */
7028 G_traps[sig] = NULL;
7031 /* We are here only if no trap or trap was not '' */
7032 install_sighandler(sig, SIG_DFL);
7038 void re_execute_shell(char ***to_free, const char *s,
7039 char *g_argv0, char **g_argv,
7040 char **builtin_argv) NORETURN;
7042 static void reset_traps_to_defaults(void)
7044 /* This function is always called in a child shell
7045 * after fork (not vfork, NOMMU doesn't use this function).
7047 IF_HUSH_TRAP(unsigned sig;)
7050 /* Child shells are not interactive.
7051 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7052 * Testcase: (while :; do :; done) + ^Z should background.
7053 * Same goes for SIGTERM, SIGHUP, SIGINT.
7055 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
7056 if (!G_traps && !mask)
7057 return; /* already no traps and no special sigs */
7059 /* Switch off special sigs */
7060 switch_off_special_sigs(mask);
7061 # if ENABLE_HUSH_JOB
7062 G_fatal_sig_mask = 0;
7064 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
7065 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7066 * remain set in G.special_sig_mask */
7068 # if ENABLE_HUSH_TRAP
7072 /* Reset all sigs to default except ones with empty traps */
7073 for (sig = 0; sig < NSIG; sig++) {
7075 continue; /* no trap: nothing to do */
7076 if (!G_traps[sig][0])
7077 continue; /* empty trap: has to remain SIG_IGN */
7078 /* sig has non-empty trap, reset it: */
7080 G_traps[sig] = NULL;
7081 /* There is no signal for trap 0 (EXIT) */
7084 install_sighandler(sig, pick_sighandler(sig));
7091 static void re_execute_shell(char ***to_free, const char *s,
7092 char *g_argv0, char **g_argv,
7093 char **builtin_argv) NORETURN;
7094 static void re_execute_shell(char ***to_free, const char *s,
7095 char *g_argv0, char **g_argv,
7096 char **builtin_argv)
7098 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7099 /* delims + 2 * (number of bytes in printed hex numbers) */
7100 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7101 char *heredoc_argv[4];
7102 struct variable *cur;
7103 # if ENABLE_HUSH_FUNCTIONS
7104 struct function *funcp;
7108 unsigned long long empty_trap_mask;
7110 if (!g_argv0) { /* heredoc */
7111 argv = heredoc_argv;
7112 argv[0] = (char *) G.argv0_for_re_execing;
7113 argv[1] = (char *) "-<";
7114 argv[2] = (char *) s;
7116 pp = &argv[3]; /* used as pointer to empty environment */
7122 if (pp) while (*pp++)
7125 empty_trap_mask = 0;
7128 for (sig = 1; sig < NSIG; sig++) {
7129 if (G_traps[sig] && !G_traps[sig][0])
7130 empty_trap_mask |= 1LL << sig;
7134 sprintf(param_buf, NOMMU_HACK_FMT
7135 , (unsigned) G.root_pid
7136 , (unsigned) G.root_ppid
7137 , (unsigned) G.last_bg_pid
7138 , (unsigned) G.last_exitcode
7141 IF_HUSH_LOOPS(, G.depth_of_loop)
7143 # undef NOMMU_HACK_FMT
7144 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7145 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7148 for (cur = G.top_var; cur; cur = cur->next) {
7149 if (!cur->flg_export || cur->flg_read_only)
7152 # if ENABLE_HUSH_FUNCTIONS
7153 for (funcp = G.top_func; funcp; funcp = funcp->next)
7159 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7160 *pp++ = (char *) G.argv0_for_re_execing;
7162 for (cur = G.top_var; cur; cur = cur->next) {
7163 if (strcmp(cur->varstr, hush_version_str) == 0)
7165 if (cur->flg_read_only) {
7166 *pp++ = (char *) "-R";
7167 *pp++ = cur->varstr;
7168 } else if (!cur->flg_export) {
7169 *pp++ = (char *) "-V";
7170 *pp++ = cur->varstr;
7173 # if ENABLE_HUSH_FUNCTIONS
7174 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7175 *pp++ = (char *) "-F";
7176 *pp++ = funcp->name;
7177 *pp++ = funcp->body_as_string;
7180 /* We can pass activated traps here. Say, -Tnn:trap_string
7182 * However, POSIX says that subshells reset signals with traps
7184 * I tested bash-3.2 and it not only does that with true subshells
7185 * of the form ( list ), but with any forked children shells.
7186 * I set trap "echo W" WINCH; and then tried:
7188 * { echo 1; sleep 20; echo 2; } &
7189 * while true; do echo 1; sleep 20; echo 2; break; done &
7190 * true | { echo 1; sleep 20; echo 2; } | cat
7192 * In all these cases sending SIGWINCH to the child shell
7193 * did not run the trap. If I add trap "echo V" WINCH;
7194 * _inside_ group (just before echo 1), it works.
7196 * I conclude it means we don't need to pass active traps here.
7198 *pp++ = (char *) "-c";
7201 while (*++builtin_argv)
7202 *pp++ = *builtin_argv;
7203 *pp++ = (char *) "";
7208 /* *pp = NULL; - is already there */
7212 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
7213 /* Don't propagate SIG_IGN to the child */
7214 if (SPECIAL_JOBSTOP_SIGS != 0)
7215 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7216 execve(bb_busybox_exec_path, argv, pp);
7217 /* Fallback. Useful for init=/bin/hush usage etc */
7218 if (argv[0][0] == '/')
7219 execve(argv[0], argv, pp);
7220 xfunc_error_retval = 127;
7221 bb_simple_error_msg_and_die("can't re-execute the shell");
7223 #endif /* !BB_MMU */
7226 static int run_and_free_list(struct pipe *pi);
7228 /* Executing from string: eval, sh -c '...'
7229 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7230 * end_trigger controls how often we stop parsing
7231 * NUL: parse all, execute, return
7232 * ';': parse till ';' or newline, execute, repeat till EOF
7234 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7236 /* Why we need empty flag?
7237 * An obscure corner case "false; ``; echo $?":
7238 * empty command in `` should still set $? to 0.
7239 * But we can't just set $? to 0 at the start,
7240 * this breaks "false; echo `echo $?`" case.
7244 struct pipe *pipe_list;
7246 #if ENABLE_HUSH_INTERACTIVE
7247 if (end_trigger == ';') {
7248 G.promptmode = 0; /* PS1 */
7249 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7252 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
7253 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7254 /* If we are in "big" script
7255 * (not in `cmd` or something similar)...
7257 if (pipe_list == ERR_PTR && end_trigger == ';') {
7258 /* Discard cached input (rest of line) */
7259 int ch = inp->last_char;
7260 while (ch != EOF && ch != '\n') {
7261 //bb_error_msg("Discarded:'%c'", ch);
7266 /* This stream isn't empty */
7270 if (!pipe_list && empty)
7271 G.last_exitcode = 0;
7274 debug_print_tree(pipe_list, 0);
7275 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7276 run_and_free_list(pipe_list);
7278 if (G_flag_return_in_progress == 1)
7283 static void parse_and_run_string(const char *s)
7285 struct in_str input;
7286 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
7288 setup_string_in_str(&input, s);
7289 parse_and_run_stream(&input, '\0');
7290 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
7293 static void parse_and_run_file(HFILE *fp)
7295 struct in_str input;
7296 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
7298 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
7299 setup_file_in_str(&input, fp);
7300 parse_and_run_stream(&input, ';');
7301 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
7304 #if ENABLE_HUSH_TICK
7305 static int generate_stream_from_string(const char *s, pid_t *pid_p)
7310 char **to_free = NULL;
7314 pid = BB_MMU ? xfork() : xvfork();
7315 if (pid == 0) { /* child */
7316 disable_restore_tty_pgrp_on_exit();
7317 /* Process substitution is not considered to be usual
7318 * 'command execution'.
7319 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7326 close(channel[0]); /* NB: close _first_, then move fd! */
7327 xmove_fd(channel[1], 1);
7328 # if ENABLE_HUSH_TRAP
7329 /* Awful hack for `trap` or $(trap).
7331 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7332 * contains an example where "trap" is executed in a subshell:
7334 * save_traps=$(trap)
7336 * eval "$save_traps"
7338 * Standard does not say that "trap" in subshell shall print
7339 * parent shell's traps. It only says that its output
7340 * must have suitable form, but then, in the above example
7341 * (which is not supposed to be normative), it implies that.
7343 * bash (and probably other shell) does implement it
7344 * (traps are reset to defaults, but "trap" still shows them),
7345 * but as a result, "trap" logic is hopelessly messed up:
7348 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7349 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7350 * # true | trap <--- trap is in subshell - no output (ditto)
7351 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7352 * trap -- 'echo Ho' SIGWINCH
7353 * # echo `(trap)` <--- in subshell in subshell - output
7354 * trap -- 'echo Ho' SIGWINCH
7355 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7356 * trap -- 'echo Ho' SIGWINCH
7358 * The rules when to forget and when to not forget traps
7359 * get really complex and nonsensical.
7361 * Our solution: ONLY bare $(trap) or `trap` is special.
7363 s = skip_whitespace(s);
7364 if (is_prefixed_with(s, "trap")
7365 && skip_whitespace(s + 4)[0] == '\0'
7367 static const char *const argv[] = { NULL, NULL };
7368 builtin_trap((char**)argv);
7369 fflush_all(); /* important */
7374 /* Prevent it from trying to handle ctrl-z etc */
7375 IF_HUSH_JOB(G.run_list_level = 1;)
7376 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7377 reset_traps_to_defaults();
7378 IF_HUSH_MODE_X(G.x_mode_depth++;)
7379 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
7380 parse_and_run_string(s);
7381 _exit(G.last_exitcode);
7383 /* We re-execute after vfork on NOMMU. This makes this script safe:
7384 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7385 * huge=`cat BIG` # was blocking here forever
7388 re_execute_shell(&to_free,
7398 # if ENABLE_HUSH_FAST
7400 //bb_error_msg("[%d] fork in generate_stream_from_string:"
7401 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7402 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7404 enable_restore_tty_pgrp_on_exit();
7412 /* Return code is exit status of the process that is run. */
7413 static int process_command_subs(o_string *dest, const char *s)
7417 int status, ch, eol_cnt;
7419 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
7421 /* Now send results of command back into original context */
7423 while ((ch = getc(fp)) != EOF) {
7431 o_addchr(dest, '\n');
7434 o_addQchr(dest, ch);
7437 debug_printf("done reading from `cmd` pipe, closing it\n");
7439 /* We need to extract exitcode. Test case
7440 * "true; echo `sleep 1; false` $?"
7442 safe_waitpid(pid, &status, 0);
7443 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7444 return WEXITSTATUS(status);
7446 #endif /* ENABLE_HUSH_TICK */
7449 static void setup_heredoc(struct redir_struct *redir)
7451 struct fd_pair pair;
7454 /* the _body_ of heredoc (misleading field name) */
7455 const char *heredoc = redir->rd_filename;
7462 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
7463 expanded = encode_then_expand_string(heredoc);
7467 len = strlen(heredoc);
7469 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7471 xmove_fd(pair.rd, redir->rd_fd);
7473 /* Try writing without forking. Newer kernels have
7474 * dynamically growing pipes. Must use non-blocking write! */
7477 written = write(pair.wr, heredoc, len);
7488 ndelay_off(pair.wr);
7490 /* Okay, pipe buffer was not big enough */
7491 /* Note: we must not create a stray child (bastard? :)
7492 * for the unsuspecting parent process. Child creates a grandchild
7493 * and exits before parent execs the process which consumes heredoc
7494 * (that exec happens after we return from this function) */
7501 disable_restore_tty_pgrp_on_exit();
7502 pid = BB_MMU ? xfork() : xvfork();
7506 close(redir->rd_fd); /* read side of the pipe */
7508 full_write(pair.wr, heredoc, len); /* may loop or block */
7511 /* Delegate blocking writes to another process */
7512 xmove_fd(pair.wr, STDOUT_FILENO);
7513 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7517 #if ENABLE_HUSH_FAST
7519 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7521 enable_restore_tty_pgrp_on_exit();
7527 wait(NULL); /* wait till child has died */
7533 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7534 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7537 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7539 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7540 sq[i].orig_fd = orig;
7541 sq[i].moved_to = moved;
7542 sq[i+1].orig_fd = -1; /* end marker */
7546 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7552 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7553 /* If we collide with an already moved fd... */
7554 if (fd == sq[i].moved_to) {
7555 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
7556 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7557 if (sq[i].moved_to < 0) /* what? */
7561 if (fd == sq[i].orig_fd) {
7562 /* Example: echo Hello >/dev/null 1>&2 */
7563 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7568 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
7569 moved_to = dup_CLOEXEC(fd, avoid_fd);
7570 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7571 if (moved_to < 0 && errno != EBADF)
7573 return append_squirrel(sq, i, fd, moved_to);
7576 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7581 if (sq) for (; sq[i].orig_fd >= 0; i++) {
7582 /* If we collide with an already moved fd... */
7583 if (fd == sq[i].orig_fd) {
7585 * "echo 3>FILE 3>&- 3>FILE"
7586 * "echo 3>&- 3>FILE"
7587 * No need for last redirect to insert
7588 * another "need to close 3" indicator.
7590 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7595 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7596 return append_squirrel(sq, i, fd, -1);
7599 /* fd: redirect wants this fd to be used (e.g. 3>file).
7600 * Move all conflicting internally used fds,
7601 * and remember them so that we can restore them later.
7603 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
7605 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7608 #if ENABLE_HUSH_INTERACTIVE
7609 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7610 && fd == G_interactive_fd
7612 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
7613 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7614 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
7615 return 1; /* "we closed fd" */
7618 /* Are we called from setup_redirects(squirrel==NULL)
7619 * in redirect in a [v]forked child?
7622 /* No need to move script fds.
7623 * For NOMMU case, it's actively wrong: we'd change ->fd
7624 * fields in memory for the parent, but parent's fds
7625 * aren't moved, it would use wrong fd!
7626 * Reproducer: "cmd 3>FILE" in script.
7627 * If we would call move_HFILEs_on_redirect(), child would:
7628 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7630 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7632 //bb_error_msg("sqp == NULL: [v]forked child");
7636 /* If this one of script's fds? */
7637 if (move_HFILEs_on_redirect(fd, avoid_fd))
7638 return 1; /* yes. "we closed fd" (actually moved it) */
7640 /* Are we called for "exec 3>FILE"? Came through
7641 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7642 * This case used to fail for this script:
7645 * ...100000 more lines...
7648 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7649 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7651 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7653 * write(1, "Ok\n", 3) = 3
7655 * write(1, "Ok\n", 3) = 3
7656 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7657 * ^^^^^^^^ oops, wrong fd!!!
7658 * With this case separate from sqp == NULL and *after* move_HFILEs,
7661 if (sqp == ERR_PTR) {
7662 /* Don't preserve redirected fds: exec is _meant_ to change these */
7663 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
7667 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7668 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7669 return 0; /* "we did not close fd" */
7672 static void restore_redirects(struct squirrel *sq)
7676 for (i = 0; sq[i].orig_fd >= 0; i++) {
7677 if (sq[i].moved_to >= 0) {
7678 /* We simply die on error */
7679 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7680 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7682 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7683 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7684 close(sq[i].orig_fd);
7690 && G.HFILE_stdin->fd != STDIN_FILENO
7692 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7693 * Redirect moves ->fd to e.g. 10,
7694 * and it is not restored above (we do not restore script fds
7695 * after redirects, we just use new, "moved" fds).
7696 * However for stdin, get_user_input() -> read_line_input(),
7697 * and read builtin, depend on fd == STDIN_FILENO.
7699 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7700 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
7701 G.HFILE_stdin->fd = STDIN_FILENO;
7704 /* If moved, G_interactive_fd stays on new fd, not restoring it */
7707 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
7708 static void close_saved_fds_and_FILE_fds(void)
7710 if (G_interactive_fd)
7711 close(G_interactive_fd);
7712 close_all_HFILE_list();
7716 static int internally_opened_fd(int fd, struct squirrel *sq)
7720 #if ENABLE_HUSH_INTERACTIVE
7721 if (fd == G_interactive_fd)
7724 /* If this one of script's fds? */
7725 if (fd_in_HFILEs(fd))
7728 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7729 if (fd == sq[i].moved_to)
7735 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
7736 * and stderr if they are redirected. */
7737 static int setup_redirects(struct command *prog, struct squirrel **sqp)
7739 struct redir_struct *redir;
7741 for (redir = prog->redirects; redir; redir = redir->next) {
7745 if (redir->rd_type == REDIRECT_HEREDOC2) {
7746 /* "rd_fd<<HERE" case */
7747 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
7748 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7750 debug_printf_redir("set heredoc '%s'\n",
7751 redir->rd_filename);
7752 setup_heredoc(redir);
7756 if (redir->rd_dup == REDIRFD_TO_FILE) {
7757 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
7761 if (redir->rd_filename == NULL) {
7763 * "cmd >" (no filename)
7764 * "cmd > <file" (2nd redirect starts too early)
7766 syntax_error("invalid redirect");
7769 mode = redir_table[redir->rd_type].mode;
7770 p = expand_string_to_string(redir->rd_filename,
7771 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
7772 newfd = open_or_warn(p, mode);
7775 /* Error message from open_or_warn can be lost
7776 * if stderr has been redirected, but bash
7777 * and ash both lose it as well
7778 * (though zsh doesn't!)
7782 if (newfd == redir->rd_fd && sqp) {
7783 /* open() gave us precisely the fd we wanted.
7784 * This means that this fd was not busy
7785 * (not opened to anywhere).
7786 * Remember to close it on restore:
7788 *sqp = add_squirrel_closed(*sqp, newfd);
7789 debug_printf_redir("redir to previously closed fd %d\n", newfd);
7792 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7793 newfd = redir->rd_dup;
7796 if (newfd == redir->rd_fd)
7799 /* if "N>FILE": move newfd to redir->rd_fd */
7800 /* if "N>&M": dup newfd to redir->rd_fd */
7801 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7803 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7804 if (newfd == REDIRFD_CLOSE) {
7805 /* "N>&-" means "close me" */
7807 /* ^^^ optimization: saving may already
7808 * have closed it. If not... */
7809 close(redir->rd_fd);
7811 /* Sometimes we do another close on restore, getting EBADF.
7812 * Consider "echo 3>FILE 3>&-"
7813 * first redirect remembers "need to close 3",
7814 * and second redirect closes 3! Restore code then closes 3 again.
7817 /* if newfd is a script fd or saved fd, simulate EBADF */
7818 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
7820 //bb_perror_msg_and_die("can't duplicate file descriptor");
7821 newfd = -1; /* same effect as code above */
7823 xdup2(newfd, redir->rd_fd);
7824 if (redir->rd_dup == REDIRFD_TO_FILE)
7825 /* "rd_fd > FILE" */
7827 /* else: "rd_fd > rd_dup" */
7833 static char *find_in_path(const char *arg)
7836 const char *PATH = get_local_var_value("PATH");
7842 const char *end = strchrnul(PATH, ':');
7843 int sz = end - PATH; /* must be int! */
7847 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7849 /* We have xxx::yyyy in $PATH,
7850 * it means "use current dir" */
7853 if (access(ret, F_OK) == 0)
7866 static const struct built_in_command *find_builtin_helper(const char *name,
7867 const struct built_in_command *x,
7868 const struct built_in_command *end)
7871 if (strcmp(name, x->b_cmd) != 0) {
7875 debug_printf_exec("found builtin '%s'\n", name);
7880 static const struct built_in_command *find_builtin1(const char *name)
7882 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7884 static const struct built_in_command *find_builtin(const char *name)
7886 const struct built_in_command *x = find_builtin1(name);
7889 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7892 #if EDITING_HAS_get_exe_name
7893 static const char * FAST_FUNC get_builtin_name(int i)
7895 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
7896 return bltins1[i].b_cmd;
7898 i -= ARRAY_SIZE(bltins1);
7899 if (i < ARRAY_SIZE(bltins2)) {
7900 return bltins2[i].b_cmd;
7906 static void remove_nested_vars(void)
7908 struct variable *cur;
7909 struct variable **cur_pp;
7911 cur_pp = &G.top_var;
7912 while ((cur = *cur_pp) != NULL) {
7913 if (cur->var_nest_level <= G.var_nest_level) {
7914 cur_pp = &cur->next;
7918 if (cur->flg_export) {
7919 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7920 bb_unsetenv(cur->varstr);
7922 /* Remove from global list */
7923 *cur_pp = cur->next;
7925 if (!cur->max_len) {
7926 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7933 static void enter_var_nest_level(void)
7936 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7938 /* Try: f() { echo -n .; f; }; f
7939 * struct variable::var_nest_level is uint16_t,
7940 * thus limiting recursion to < 2^16.
7941 * In any case, with 8 Mbyte stack SEGV happens
7942 * not too long after 2^16 recursions anyway.
7944 if (G.var_nest_level > 0xff00)
7945 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7948 static void leave_var_nest_level(void)
7951 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7952 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7953 bb_simple_error_msg_and_die("BUG: nesting underflow");
7955 remove_nested_vars();
7958 #if ENABLE_HUSH_FUNCTIONS
7959 static struct function **find_function_slot(const char *name)
7961 struct function *funcp;
7962 struct function **funcpp = &G.top_func;
7964 while ((funcp = *funcpp) != NULL) {
7965 if (strcmp(name, funcp->name) == 0) {
7966 debug_printf_exec("found function '%s'\n", name);
7969 funcpp = &funcp->next;
7974 static ALWAYS_INLINE const struct function *find_function(const char *name)
7976 const struct function *funcp = *find_function_slot(name);
7980 /* Note: takes ownership on name ptr */
7981 static struct function *new_function(char *name)
7983 struct function **funcpp = find_function_slot(name);
7984 struct function *funcp = *funcpp;
7986 if (funcp != NULL) {
7987 struct command *cmd = funcp->parent_cmd;
7988 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7990 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7992 /* Note: if !funcp->body, do not free body_as_string!
7993 * This is a special case of "-F name body" function:
7994 * body_as_string was not malloced! */
7996 free_pipe_list(funcp->body);
7998 free(funcp->body_as_string);
8002 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8003 cmd->argv[0] = funcp->name;
8004 cmd->group = funcp->body;
8006 cmd->group_as_string = funcp->body_as_string;
8010 debug_printf_exec("remembering new function '%s'\n", name);
8011 funcp = *funcpp = xzalloc(sizeof(*funcp));
8012 /*funcp->next = NULL;*/
8019 # if ENABLE_HUSH_UNSET
8020 static void unset_func(const char *name)
8022 struct function **funcpp = find_function_slot(name);
8023 struct function *funcp = *funcpp;
8025 if (funcp != NULL) {
8026 debug_printf_exec("freeing function '%s'\n", funcp->name);
8027 *funcpp = funcp->next;
8028 /* funcp is unlinked now, deleting it.
8029 * Note: if !funcp->body, the function was created by
8030 * "-F name body", do not free ->body_as_string
8031 * and ->name as they were not malloced. */
8033 free_pipe_list(funcp->body);
8036 free(funcp->body_as_string);
8045 #define exec_function(to_free, funcp, argv) \
8046 exec_function(funcp, argv)
8048 static void exec_function(char ***to_free,
8049 const struct function *funcp,
8050 char **argv) NORETURN;
8051 static void exec_function(char ***to_free,
8052 const struct function *funcp,
8058 argv[0] = G.global_argv[0];
8059 G.global_argv = argv;
8060 G.global_argc = n = 1 + string_array_len(argv + 1);
8062 // Example when we are here: "cmd | func"
8063 // func will run with saved-redirect fds open.
8064 // $ f() { echo /proc/self/fd/*; }
8066 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8067 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8070 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8071 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8072 // They are CLOEXEC so external programs won't see them, but
8073 // for "more correctness" we might want to close those extra fds here:
8074 //? close_saved_fds_and_FILE_fds();
8076 /* "we are in a function, ok to use return" */
8077 G_flag_return_in_progress = -1;
8078 enter_var_nest_level();
8079 IF_HUSH_LOCAL(G.func_nest_level++;)
8081 /* On MMU, funcp->body is always non-NULL */
8082 n = run_list(funcp->body);
8086 //? close_saved_fds_and_FILE_fds();
8088 //TODO: check whether "true | func_with_return" works
8090 re_execute_shell(to_free,
8091 funcp->body_as_string,
8098 static int run_function(const struct function *funcp, char **argv)
8104 save_and_replace_G_args(&sv, argv);
8106 /* "We are in function, ok to use return" */
8107 sv_flg = G_flag_return_in_progress;
8108 G_flag_return_in_progress = -1;
8110 /* Make "local" variables properly shadow previous ones */
8111 IF_HUSH_LOCAL(enter_var_nest_level();)
8112 IF_HUSH_LOCAL(G.func_nest_level++;)
8114 /* On MMU, funcp->body is always non-NULL */
8117 /* Function defined by -F */
8118 parse_and_run_string(funcp->body_as_string);
8119 rc = G.last_exitcode;
8123 rc = run_list(funcp->body);
8126 IF_HUSH_LOCAL(G.func_nest_level--;)
8127 IF_HUSH_LOCAL(leave_var_nest_level();)
8129 G_flag_return_in_progress = sv_flg;
8131 restore_G_args(&sv, argv);
8135 #endif /* ENABLE_HUSH_FUNCTIONS */
8139 #define exec_builtin(to_free, x, argv) \
8140 exec_builtin(x, argv)
8142 #define exec_builtin(to_free, x, argv) \
8143 exec_builtin(to_free, argv)
8145 static void exec_builtin(char ***to_free,
8146 const struct built_in_command *x,
8147 char **argv) NORETURN;
8148 static void exec_builtin(char ***to_free,
8149 const struct built_in_command *x,
8155 //? close_saved_fds_and_FILE_fds();
8156 rcode = x->b_function(argv);
8161 /* On NOMMU, we must never block!
8162 * Example: { sleep 99 | read line; } & echo Ok
8164 re_execute_shell(to_free,
8173 static void execvp_or_die(char **argv) NORETURN;
8174 static void execvp_or_die(char **argv)
8177 debug_printf_exec("execing '%s'\n", argv[0]);
8178 /* Don't propagate SIG_IGN to the child */
8179 if (SPECIAL_JOBSTOP_SIGS != 0)
8180 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8181 execvp(argv[0], argv);
8183 if (errno == EACCES) e = 126;
8184 if (errno == ENOENT) e = 127;
8185 bb_perror_msg("can't execute '%s'", argv[0]);
8189 #if ENABLE_HUSH_MODE_X
8190 static void x_mode_print_optionally_squoted(const char *str)
8197 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8198 /* test a char with: bash -c 'set -x; echo "CH"' */
8199 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8200 " " "\001\002\003\004\005\006\007"
8201 "\010\011\012\013\014\015\016\017"
8202 "\020\021\022\023\024\025\026\027"
8203 "\030\031\032\033\034\035\036\037"
8207 /* string has no special chars */
8214 /* print '....' up to EOL or first squote */
8215 len = (int)(strchrnul(cp, '\'') - cp);
8217 x_mode_addchr('\'');
8218 x_mode_addblock(cp, len);
8219 x_mode_addchr('\'');
8224 /* string contains squote(s), print them as \' */
8225 x_mode_addchr('\\');
8226 x_mode_addchr('\'');
8230 static void dump_cmd_in_x_mode(char **argv)
8232 if (G_x_mode && argv) {
8235 /* "+[+++...][ cmd...]\n\0" */
8240 if (argv[n][0] == '\0') {
8241 x_mode_addchr('\'');
8242 x_mode_addchr('\'');
8244 x_mode_print_optionally_squoted(argv[n]);
8252 # define dump_cmd_in_x_mode(argv) ((void)0)
8255 #if ENABLE_HUSH_COMMAND
8256 static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8265 char *path = getenv("PATH");
8266 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
8268 _exit(1); /* PROG was not found */
8270 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8272 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
8278 # define if_command_vV_print_and_exit(a,b,c) ((void)0)
8282 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8283 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8284 #define pseudo_exec(nommu_save, command, argv_expanded) \
8285 pseudo_exec(command, argv_expanded)
8288 /* Called after [v]fork() in run_pipe, or from builtin_exec.
8290 * Don't exit() here. If you don't exec, use _exit instead.
8291 * The at_exit handlers apparently confuse the calling process,
8292 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
8294 static void pseudo_exec_argv(nommu_save_t *nommu_save,
8295 char **argv, int assignment_cnt,
8296 char **argv_expanded) NORETURN;
8297 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8298 char **argv, int assignment_cnt,
8299 char **argv_expanded)
8301 const struct built_in_command *x;
8302 struct variable **sv_shadowed;
8304 IF_HUSH_COMMAND(char opt_vV = 0;)
8305 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8307 new_env = expand_assignments(argv, assignment_cnt);
8308 dump_cmd_in_x_mode(new_env);
8310 if (!argv[assignment_cnt]) {
8311 /* Case when we are here: ... | var=val | ...
8312 * (note that we do not exit early, i.e., do not optimize out
8313 * expand_assignments(): think about ... | var=`sleep 1` | ...
8315 free_strings(new_env);
8316 _exit(EXIT_SUCCESS);
8319 sv_shadowed = G.shadowed_vars_pp;
8321 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
8323 G.shadowed_vars_pp = &nommu_save->old_vars;
8326 set_vars_and_save_old(new_env);
8327 G.shadowed_vars_pp = sv_shadowed;
8329 if (argv_expanded) {
8330 argv = argv_expanded;
8332 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8334 nommu_save->argv = argv;
8337 dump_cmd_in_x_mode(argv);
8339 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8340 if (strchr(argv[0], '/') != NULL)
8344 #if ENABLE_HUSH_FUNCTIONS
8345 /* Check if the command matches any functions (this goes before bltins) */
8346 funcp = find_function(argv[0]);
8348 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
8351 #if ENABLE_HUSH_COMMAND
8352 /* "command BAR": run BAR without looking it up among functions
8353 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8354 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8356 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8361 if (p[0] != '-' || !p[1])
8362 continue; /* bash allows "command command command [-OPT] BAR" */
8370 if (p[0] != '-' || !p[1])
8372 continue; /* next arg is also -opts, process it too */
8378 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8383 # if ENABLE_HUSH_FUNCTIONS
8384 if (opt_vV && find_function(argv[0]))
8385 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8389 /* Check if the command matches any of the builtins.
8390 * Depending on context, this might be redundant. But it's
8391 * easier to waste a few CPU cycles than it is to figure out
8392 * if this is one of those cases.
8394 /* Why "BB_MMU ? :" difference in logic? -
8395 * On NOMMU, it is more expensive to re-execute shell
8396 * just in order to run echo or test builtin.
8397 * It's better to skip it here and run corresponding
8398 * non-builtin later. */
8399 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8401 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8402 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
8405 #if ENABLE_FEATURE_SH_STANDALONE
8406 /* Check if the command matches any busybox applets */
8408 int a = find_applet_by_name(argv[0]);
8410 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
8411 # if BB_MMU /* see above why on NOMMU it is not allowed */
8412 if (APPLET_IS_NOEXEC(a)) {
8413 /* Do not leak open fds from opened script files etc.
8414 * Testcase: interactive "ls -l /proc/self/fd"
8415 * should not show tty fd open.
8417 close_saved_fds_and_FILE_fds();
8418 //FIXME: should also close saved redir fds
8419 //This casuses test failures in
8420 //redir_children_should_not_see_saved_fd_2.tests
8421 //redir_children_should_not_see_saved_fd_3.tests
8422 //if you replace "busybox find" with just "find" in them
8423 /* Without this, "rm -i FILE" can't be ^C'ed: */
8424 switch_off_special_sigs(G.special_sig_mask);
8425 debug_printf_exec("running applet '%s'\n", argv[0]);
8426 run_noexec_applet_and_exit(a, argv[0], argv);
8429 /* Re-exec ourselves */
8430 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
8431 /* Don't propagate SIG_IGN to the child */
8432 if (SPECIAL_JOBSTOP_SIGS != 0)
8433 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
8434 execv(bb_busybox_exec_path, argv);
8435 /* If they called chroot or otherwise made the binary no longer
8436 * executable, fall through */
8441 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8444 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
8445 execvp_or_die(argv);
8448 /* Called after [v]fork() in run_pipe
8450 static void pseudo_exec(nommu_save_t *nommu_save,
8451 struct command *command,
8452 char **argv_expanded) NORETURN;
8453 static void pseudo_exec(nommu_save_t *nommu_save,
8454 struct command *command,
8455 char **argv_expanded)
8457 #if ENABLE_HUSH_FUNCTIONS
8458 if (command->cmd_type == CMD_FUNCDEF) {
8459 /* Ignore funcdefs in pipes:
8460 * true | f() { cmd }
8466 if (command->argv) {
8467 pseudo_exec_argv(nommu_save, command->argv,
8468 command->assignment_cnt, argv_expanded);
8471 if (command->group) {
8472 /* Cases when we are here:
8475 * ... | ( list ) | ...
8476 * ... | { list } | ...
8480 debug_printf_exec("pseudo_exec: run_list\n");
8481 reset_traps_to_defaults();
8482 rcode = run_list(command->group);
8483 /* OK to leak memory by not calling free_pipe_list,
8484 * since this process is about to exit */
8487 re_execute_shell(&nommu_save->argv_from_re_execing,
8488 command->group_as_string,
8495 /* Case when we are here: ... | >file */
8496 debug_printf_exec("pseudo_exec'ed null command\n");
8497 _exit(EXIT_SUCCESS);
8501 static const char *get_cmdtext(struct pipe *pi)
8507 /* This is subtle. ->cmdtext is created only on first backgrounding.
8508 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8509 * On subsequent bg argv is trashed, but we won't use it */
8513 argv = pi->cmds[0].argv;
8515 pi->cmdtext = xzalloc(1);
8520 len += strlen(*argv) + 1;
8524 argv = pi->cmds[0].argv;
8526 p = stpcpy(p, *argv);
8533 static void remove_job_from_table(struct pipe *pi)
8535 struct pipe *prev_pipe;
8537 if (pi == G.job_list) {
8538 G.job_list = pi->next;
8540 prev_pipe = G.job_list;
8541 while (prev_pipe->next != pi)
8542 prev_pipe = prev_pipe->next;
8543 prev_pipe->next = pi->next;
8547 G.last_jobid = G.job_list->jobid;
8550 static void delete_finished_job(struct pipe *pi)
8552 remove_job_from_table(pi);
8556 static void clean_up_last_dead_job(void)
8558 if (G.job_list && !G.job_list->alive_cmds)
8559 delete_finished_job(G.job_list);
8562 static void insert_job_into_table(struct pipe *pi)
8564 struct pipe *job, **jobp;
8567 clean_up_last_dead_job();
8569 /* Find the end of the list, and find next job ID to use */
8572 while ((job = *jobp) != NULL) {
8579 /* Create a new job struct at the end */
8580 job = *jobp = xmemdup(pi, sizeof(*pi));
8582 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8583 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8584 for (i = 0; i < pi->num_cmds; i++) {
8585 job->cmds[i].pid = pi->cmds[i].pid;
8586 /* all other fields are not used and stay zero */
8588 job->cmdtext = xstrdup(get_cmdtext(pi));
8590 if (G_interactive_fd)
8591 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
8592 G.last_jobid = job->jobid;
8596 static int job_exited_or_stopped(struct pipe *pi)
8600 if (pi->alive_cmds != pi->stopped_cmds)
8603 /* All processes in fg pipe have exited or stopped */
8607 rcode = pi->cmds[i].cmd_exitcode;
8608 /* usually last process gives overall exitstatus,
8609 * but with "set -o pipefail", last *failed* process does */
8610 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8613 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8617 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
8624 dead = WIFEXITED(status) || WIFSIGNALED(status);
8627 if (WIFSTOPPED(status))
8628 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8629 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8630 if (WIFSIGNALED(status))
8631 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8632 childpid, WTERMSIG(status), WEXITSTATUS(status));
8633 if (WIFEXITED(status))
8634 debug_printf_jobs("pid %d exited, exitcode %d\n",
8635 childpid, WEXITSTATUS(status));
8637 /* Were we asked to wait for a fg pipe? */
8639 i = fg_pipe->num_cmds;
8644 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8645 if (fg_pipe->cmds[i].pid != childpid)
8649 fg_pipe->cmds[i].pid = 0;
8650 fg_pipe->alive_cmds--;
8651 ex = WEXITSTATUS(status);
8652 /* bash prints killer signal's name for *last*
8653 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8654 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8656 if (WIFSIGNALED(status)) {
8657 int sig = WTERMSIG(status);
8658 if (i == fg_pipe->num_cmds-1)
8659 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8660 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8661 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8662 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8663 * Maybe we need to use sig | 128? */
8666 fg_pipe->cmds[i].cmd_exitcode = ex;
8668 fg_pipe->stopped_cmds++;
8670 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8671 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
8672 rcode = job_exited_or_stopped(fg_pipe);
8674 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
8675 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8676 * and "killall -STOP cat" */
8677 if (G_interactive_fd) {
8679 if (fg_pipe->alive_cmds != 0)
8680 insert_job_into_table(fg_pipe);
8684 if (fg_pipe->alive_cmds == 0)
8687 /* There are still running processes in the fg_pipe */
8690 /* It wasn't in fg_pipe, look for process in bg pipes */
8694 /* We were asked to wait for bg or orphaned children */
8695 /* No need to remember exitcode in this case */
8696 for (pi = G.job_list; pi; pi = pi->next) {
8697 for (i = 0; i < pi->num_cmds; i++) {
8698 if (pi->cmds[i].pid == childpid)
8699 goto found_pi_and_prognum;
8702 /* Happens when shell is used as init process (init=/bin/sh) */
8703 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8704 return -1; /* this wasn't a process from fg_pipe */
8706 found_pi_and_prognum:
8709 int rcode = WEXITSTATUS(status);
8710 if (WIFSIGNALED(status))
8711 rcode = 128 + WTERMSIG(status);
8712 pi->cmds[i].cmd_exitcode = rcode;
8713 if (G.last_bg_pid == pi->cmds[i].pid)
8714 G.last_bg_pid_exitcode = rcode;
8715 pi->cmds[i].pid = 0;
8717 if (!pi->alive_cmds) {
8718 # if ENABLE_HUSH_BASH_COMPAT
8719 G.dead_job_exitcode = job_exited_or_stopped(pi);
8721 if (G_interactive_fd) {
8722 printf(JOB_STATUS_FORMAT, pi->jobid,
8723 "Done", pi->cmdtext);
8724 delete_finished_job(pi);
8727 * bash deletes finished jobs from job table only in interactive mode,
8728 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8729 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8730 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8731 * We only retain one "dead" job, if it's the single job on the list.
8732 * This covers most of real-world scenarios where this is useful.
8734 if (pi != G.job_list)
8735 delete_finished_job(pi);
8743 return -1; /* this wasn't a process from fg_pipe */
8746 /* Check to see if any processes have exited -- if they have,
8747 * figure out why and see if a job has completed.
8749 * If non-NULL fg_pipe: wait for its completion or stop.
8750 * Return its exitcode or zero if stopped.
8752 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8753 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8754 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8755 * or 0 if no children changed status.
8757 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8758 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8759 * or 0 if no children changed status.
8761 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8767 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8769 attributes = WUNTRACED;
8770 if (fg_pipe == NULL)
8771 attributes |= WNOHANG;
8774 #if ENABLE_HUSH_FAST
8775 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8776 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8777 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8778 /* There was neither fork nor SIGCHLD since last waitpid */
8779 /* Avoid doing waitpid syscall if possible */
8780 if (!G.we_have_children) {
8784 if (fg_pipe == NULL) { /* is WNOHANG set? */
8785 /* We have children, but they did not exit
8786 * or stop yet (we saw no SIGCHLD) */
8789 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8793 /* Do we do this right?
8794 * bash-3.00# sleep 20 | false
8796 * [3]+ Stopped sleep 20 | false
8797 * bash-3.00# echo $?
8798 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8799 * [hush 1.14.0: yes we do it right]
8803 #if ENABLE_HUSH_FAST
8805 i = G.count_SIGCHLD;
8807 childpid = waitpid(-1, &status, attributes);
8808 if (childpid <= 0) {
8809 if (childpid && errno != ECHILD)
8810 bb_simple_perror_msg("waitpid");
8811 #if ENABLE_HUSH_FAST
8812 else { /* Until next SIGCHLD, waitpid's are useless */
8813 G.we_have_children = (childpid == 0);
8814 G.handled_SIGCHLD = i;
8815 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8818 /* ECHILD (no children), or 0 (no change in children status) */
8822 rcode = process_wait_result(fg_pipe, childpid, status);
8824 /* fg_pipe exited or stopped */
8827 if (childpid == waitfor_pid) { /* "wait PID" */
8828 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
8829 rcode = WEXITSTATUS(status);
8830 if (WIFSIGNALED(status))
8831 rcode = 128 + WTERMSIG(status);
8832 if (WIFSTOPPED(status))
8833 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8834 rcode = 128 + WSTOPSIG(status);
8836 break; /* "wait PID" called us, give it exitcode+1 */
8838 #if ENABLE_HUSH_BASH_COMPAT
8839 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8840 && G.dead_job_exitcode >= 0 /* some job did finish */
8842 debug_printf_exec("waitfor_pid:-1\n");
8843 rcode = G.dead_job_exitcode + 1;
8847 /* This wasn't one of our processes, or */
8848 /* fg_pipe still has running processes, do waitpid again */
8849 } /* while (waitpid succeeds)... */
8855 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
8858 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
8859 if (G_saved_tty_pgrp) {
8860 /* Job finished, move the shell to the foreground */
8861 p = getpgrp(); /* our process group id */
8862 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8863 tcsetpgrp(G_interactive_fd, p);
8869 /* Start all the jobs, but don't wait for anything to finish.
8872 * Return code is normally -1, when the caller has to wait for children
8873 * to finish to determine the exit status of the pipe. If the pipe
8874 * is a simple builtin command, however, the action is done by the
8875 * time run_pipe returns, and the exit code is provided as the
8878 * Returns -1 only if started some children. IOW: we have to
8879 * mask out retvals of builtins etc with 0xff!
8881 * The only case when we do not need to [v]fork is when the pipe
8882 * is single, non-backgrounded, non-subshell command. Examples:
8883 * cmd ; ... { list } ; ...
8884 * cmd && ... { list } && ...
8885 * cmd || ... { list } || ...
8886 * If it is, then we can run cmd as a builtin, NOFORK,
8887 * or (if SH_STANDALONE) an applet, and we can run the { list }
8888 * with run_list. If it isn't one of these, we fork and exec cmd.
8890 * Cases when we must fork:
8891 * non-single: cmd | cmd
8892 * backgrounded: cmd & { list } &
8893 * subshell: ( list ) [&]
8895 #if !ENABLE_HUSH_MODE_X
8896 #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8897 redirect_and_varexp_helper(command, sqp)
8899 static int redirect_and_varexp_helper(
8900 struct command *command,
8901 struct squirrel **sqp,
8902 char **argv_expanded)
8904 /* Assignments occur before redirects. Try:
8905 * a=`sleep 1` sleep 2 3>/qwe/rty
8908 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8909 dump_cmd_in_x_mode(new_env);
8910 dump_cmd_in_x_mode(argv_expanded);
8911 /* this takes ownership of new_env[i] elements, and frees new_env: */
8912 set_vars_and_save_old(new_env);
8914 return setup_redirects(command, sqp);
8916 static NOINLINE int run_pipe(struct pipe *pi)
8918 static const char *const null_ptr = NULL;
8922 struct command *command;
8923 char **argv_expanded;
8925 struct squirrel *squirrel = NULL;
8928 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8931 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8932 * Result should be 3 lines: q w e, qwe, q w e
8934 if (G.ifs_whitespace != G.ifs)
8935 free(G.ifs_whitespace);
8936 G.ifs = get_local_var_value("IFS");
8939 G.ifs_whitespace = (char*)G.ifs;
8940 p = skip_whitespace(G.ifs);
8942 /* Not all $IFS is whitespace */
8944 int len = p - G.ifs;
8945 p = skip_non_whitespace(p);
8946 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8947 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8957 G.ifs_whitespace = (char*)G.ifs;
8960 IF_HUSH_JOB(pi->pgrp = -1;)
8961 pi->stopped_cmds = 0;
8962 command = &pi->cmds[0];
8963 argv_expanded = NULL;
8965 if (pi->num_cmds != 1
8966 || pi->followup == PIPE_BG
8967 || command->cmd_type == CMD_SUBSHELL
8974 debug_printf_exec(": group:%p argv:'%s'\n",
8975 command->group, command->argv ? command->argv[0] : "NONE");
8977 if (command->group) {
8978 #if ENABLE_HUSH_FUNCTIONS
8979 if (command->cmd_type == CMD_FUNCDEF) {
8980 /* "executing" func () { list } */
8981 struct function *funcp;
8983 funcp = new_function(command->argv[0]);
8984 /* funcp->name is already set to argv[0] */
8985 funcp->body = command->group;
8987 funcp->body_as_string = command->group_as_string;
8988 command->group_as_string = NULL;
8990 command->group = NULL;
8991 command->argv[0] = NULL;
8992 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8993 funcp->parent_cmd = command;
8994 command->child_func = funcp;
8996 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8998 return EXIT_SUCCESS;
9002 debug_printf_exec("non-subshell group\n");
9003 rcode = 1; /* exitcode if redir failed */
9004 if (setup_redirects(command, &squirrel) == 0) {
9005 debug_printf_exec(": run_list\n");
9006 //FIXME: we need to pass squirrel down into run_list()
9007 //for SH_STANDALONE case, or else this construct:
9008 // { find /proc/self/fd; true; } >FILE; cmd2
9009 //has no way of closing saved fd#1 for "find",
9010 //and in SH_STANDALONE mode, "find" is not execed,
9011 //therefore CLOEXEC on saved fd does not help.
9012 rcode = run_list(command->group) & 0xff;
9014 restore_redirects(squirrel);
9015 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9017 debug_printf_exec("run_pipe: return %d\n", rcode);
9021 argv = command->argv ? command->argv : (char **) &null_ptr;
9023 const struct built_in_command *x;
9024 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9025 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
9026 struct variable **sv_shadowed;
9027 struct variable *old_vars;
9029 #if ENABLE_HUSH_LINENO_VAR
9030 G.execute_lineno = command->lineno;
9033 if (argv[command->assignment_cnt] == NULL) {
9034 /* Assignments, but no command.
9035 * Ensure redirects take effect (that is, create files).
9039 G.expand_exitcode = 0;
9041 rcode = setup_redirects(command, &squirrel);
9042 restore_redirects(squirrel);
9044 /* Set shell variables */
9046 while (i < command->assignment_cnt) {
9047 char *p = expand_string_to_string(argv[i],
9048 EXP_FLAG_ESC_GLOB_CHARS,
9051 #if ENABLE_HUSH_MODE_X
9057 eq = strchrnul(p, '=');
9059 x_mode_addblock(p, (eq - p));
9060 x_mode_print_optionally_squoted(eq);
9064 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
9065 if (set_local_var(p, /*flag:*/ 0)) {
9066 /* assignment to readonly var / putenv error? */
9071 /* Redirect error sets $? to 1. Otherwise,
9072 * if evaluating assignment value set $?, retain it.
9074 * false; q=`exit 2`; echo $? - should print 2
9075 * false; x=1; echo $? - should print 0
9076 * Because of the 2nd case, we can't just use G.last_exitcode.
9079 rcode = G.expand_exitcode;
9080 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9082 debug_printf_exec("run_pipe: return %d\n", rcode);
9086 /* Expand the rest into (possibly) many strings each */
9087 #if defined(CMD_SINGLEWORD_NOGLOB)
9088 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
9089 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9092 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
9094 /* If someone gives us an empty string: `cmd with empty output` */
9095 if (!argv_expanded[0]) {
9096 free(argv_expanded);
9097 /* `false` still has to set exitcode 1 */
9098 G.expand_exitcode = G.last_exitcode;
9099 goto only_assignments;
9103 sv_shadowed = G.shadowed_vars_pp;
9105 /* Check if argv[0] matches any functions (this goes before bltins) */
9106 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9107 IF_HUSH_FUNCTIONS(x = NULL;)
9108 IF_HUSH_FUNCTIONS(if (!funcp))
9109 x = find_builtin(argv_expanded[0]);
9111 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9112 debug_printf("exec with redirects only\n");
9114 * Variable assignments are executed, but then "forgotten":
9115 * a=`sleep 1;echo A` exec 3>&-; echo $a
9116 * sleeps, but prints nothing.
9118 enter_var_nest_level();
9119 G.shadowed_vars_pp = &old_vars;
9120 rcode = redirect_and_varexp_helper(command,
9121 /*squirrel:*/ ERR_PTR,
9124 G.shadowed_vars_pp = sv_shadowed;
9125 /* rcode=1 can be if redir file can't be opened */
9127 goto clean_up_and_ret1;
9130 /* Bump var nesting, or this will leak exported $a:
9131 * a=b true; env | grep ^a=
9133 enter_var_nest_level();
9134 /* Collect all variables "shadowed" by helper
9135 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9136 * into old_vars list:
9138 G.shadowed_vars_pp = &old_vars;
9139 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9142 /* Do not collect *to old_vars list* vars shadowed
9143 * by e.g. "local VAR" builtin (collect them
9144 * in the previously nested list instead):
9145 * don't want them to be restored immediately
9146 * after "local" completes.
9148 G.shadowed_vars_pp = sv_shadowed;
9150 debug_printf_exec(": builtin '%s' '%s'...\n",
9151 x->b_cmd, argv_expanded[1]);
9153 rcode = x->b_function(argv_expanded) & 0xff;
9156 #if ENABLE_HUSH_FUNCTIONS
9158 debug_printf_exec(": function '%s' '%s'...\n",
9159 funcp->name, argv_expanded[1]);
9160 rcode = run_function(funcp, argv_expanded) & 0xff;
9162 * But do collect *to old_vars list* vars shadowed
9163 * within function execution. To that end, restore
9164 * this pointer _after_ function run:
9166 G.shadowed_vars_pp = sv_shadowed;
9171 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
9172 int n = find_applet_by_name(argv_expanded[0]);
9173 if (n < 0 || !APPLET_IS_NOFORK(n))
9176 enter_var_nest_level();
9177 /* Collect all variables "shadowed" by helper into old_vars list */
9178 G.shadowed_vars_pp = &old_vars;
9179 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9180 G.shadowed_vars_pp = sv_shadowed;
9183 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9184 argv_expanded[0], argv_expanded[1]);
9186 * Note: signals (^C) can't interrupt here.
9187 * We remember them and they will be acted upon
9188 * after applet returns.
9189 * This makes applets which can run for a long time
9190 * and/or wait for user input ineligible for NOFORK:
9191 * for example, "yes" or "rm" (rm -i waits for input).
9193 rcode = run_nofork_applet(n, argv_expanded);
9198 restore_redirects(squirrel);
9200 leave_var_nest_level();
9204 * Try "usleep 99999999" + ^C + "echo $?"
9205 * with FEATURE_SH_NOFORK=y.
9208 /* It was builtin or nofork.
9209 * if this would be a real fork/execed program,
9210 * it should have died if a fatal sig was received.
9211 * But OTOH, there was no separate process,
9212 * the sig was sent to _shell_, not to non-existing
9214 * Let's just handle ^C only, this one is obvious:
9215 * we aren't ok with exitcode 0 when ^C was pressed
9216 * during builtin/nofork.
9218 if (sigismember(&G.pending_set, SIGINT))
9219 rcode = 128 + SIGINT;
9221 free(argv_expanded);
9222 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9224 debug_printf_exec("run_pipe return %d\n", rcode);
9229 /* NB: argv_expanded may already be created, and that
9230 * might include `cmd` runs! Do not rerun it! We *must*
9231 * use argv_expanded if it's non-NULL */
9233 /* Going to fork a child per each pipe member */
9238 while (cmd_no < pi->num_cmds) {
9239 struct fd_pair pipefds;
9241 int sv_var_nest_level = G.var_nest_level;
9242 volatile nommu_save_t nommu_save;
9243 nommu_save.old_vars = NULL;
9244 nommu_save.argv = NULL;
9245 nommu_save.argv_from_re_execing = NULL;
9247 command = &pi->cmds[cmd_no];
9249 if (command->argv) {
9250 debug_printf_exec(": pipe member '%s' '%s'...\n",
9251 command->argv[0], command->argv[1]);
9253 debug_printf_exec(": pipe member with no argv\n");
9256 /* pipes are inserted between pairs of commands */
9259 if (cmd_no < pi->num_cmds)
9260 xpiped_pair(pipefds);
9262 #if ENABLE_HUSH_LINENO_VAR
9263 G.execute_lineno = command->lineno;
9266 command->pid = BB_MMU ? fork() : vfork();
9267 if (!command->pid) { /* child */
9269 disable_restore_tty_pgrp_on_exit();
9270 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9272 /* Every child adds itself to new process group
9273 * with pgid == pid_of_first_child_in_pipe */
9274 if (G.run_list_level == 1 && G_interactive_fd) {
9277 if (pgrp < 0) /* true for 1st process only */
9279 if (setpgid(0, pgrp) == 0
9280 && pi->followup != PIPE_BG
9281 && G_saved_tty_pgrp /* we have ctty */
9283 /* We do it in *every* child, not just first,
9285 tcsetpgrp(G_interactive_fd, pgrp);
9289 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9290 /* 1st cmd in backgrounded pipe
9291 * should have its stdin /dev/null'ed */
9293 if (open(bb_dev_null, O_RDONLY))
9294 xopen("/", O_RDONLY);
9296 xmove_fd(next_infd, 0);
9298 xmove_fd(pipefds.wr, 1);
9301 /* Like bash, explicit redirects override pipes,
9302 * and the pipe fd (fd#1) is available for dup'ing:
9303 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9304 * of cmd1 goes into pipe.
9306 if (setup_redirects(command, NULL)) {
9307 /* Happens when redir file can't be opened:
9308 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9310 * hush: can't open '/qwe/rty': No such file or directory
9312 * (echo BAR is not executed, it hits _exit(1) below)
9317 /* Stores to nommu_save list of env vars putenv'ed
9318 * (NOMMU, on MMU we don't need that) */
9319 /* cast away volatility... */
9320 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9321 /* pseudo_exec() does not return */
9324 /* parent or error */
9325 #if ENABLE_HUSH_FAST
9327 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9329 enable_restore_tty_pgrp_on_exit();
9331 /* Clean up after vforked child */
9332 free(nommu_save.argv);
9333 free(nommu_save.argv_from_re_execing);
9334 G.var_nest_level = sv_var_nest_level;
9335 remove_nested_vars();
9336 add_vars(nommu_save.old_vars);
9338 free(argv_expanded);
9339 argv_expanded = NULL;
9340 if (command->pid < 0) { /* [v]fork failed */
9341 /* Clearly indicate, was it fork or vfork */
9342 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9346 /* Second and next children need to know pid of first one */
9348 pi->pgrp = command->pid;
9354 if (cmd_no < pi->num_cmds)
9356 /* Pass read (output) pipe end to next iteration */
9357 next_infd = pipefds.rd;
9360 if (!pi->alive_cmds) {
9362 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9367 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9371 /* NB: called by pseudo_exec, and therefore must not modify any
9372 * global data until exec/_exit (we can be a child after vfork!) */
9373 static int run_list(struct pipe *pi)
9375 #if ENABLE_HUSH_CASE
9376 char *case_word = NULL;
9378 #if ENABLE_HUSH_LOOPS
9379 struct pipe *loop_top = NULL;
9380 char **for_lcur = NULL;
9381 char **for_list = NULL;
9383 smallint last_followup;
9385 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9386 smalluint cond_code = 0;
9388 enum { cond_code = 0 };
9391 smallint rword; /* RES_foo */
9392 smallint last_rword; /* ditto */
9395 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9398 #if ENABLE_HUSH_LOOPS
9399 /* Check syntax for "for" */
9402 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9403 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9405 /* current word is FOR or IN (BOLD in comments below) */
9406 if (cpipe->next == NULL) {
9407 syntax_error("malformed for");
9409 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9412 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9413 if (cpipe->next->res_word == RES_DO)
9415 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9416 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9417 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9419 syntax_error("malformed for");
9421 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9428 /* Past this point, all code paths should jump to ret: label
9429 * in order to return, no direct "return" statements please.
9430 * This helps to ensure that no memory is leaked. */
9438 last_rword = RES_XXXX;
9440 last_followup = PIPE_SEQ;
9441 rcode = G.last_exitcode;
9443 /* Go through list of pipes, (maybe) executing them. */
9444 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
9446 int sv_errexit_depth;
9450 if (G_flag_return_in_progress == 1)
9453 IF_HAS_KEYWORDS(rword = pi->res_word;)
9454 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9455 rword, cond_code, last_rword);
9457 sv_errexit_depth = G.errexit_depth;
9460 rword == RES_IF || rword == RES_ELIF ||
9462 pi->followup != PIPE_SEQ
9466 #if ENABLE_HUSH_LOOPS
9467 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9468 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9470 /* start of a loop: remember where loop starts */
9475 /* Still in the same "if...", "then..." or "do..." branch? */
9476 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9477 if ((rcode == 0 && last_followup == PIPE_OR)
9478 || (rcode != 0 && last_followup == PIPE_AND)
9480 /* It is "<true> || CMD" or "<false> && CMD"
9481 * and we should not execute CMD */
9482 debug_printf_exec("skipped cmd because of || or &&\n");
9483 last_followup = pi->followup;
9484 goto dont_check_jobs_but_continue;
9487 last_followup = pi->followup;
9488 IF_HAS_KEYWORDS(last_rword = rword;)
9491 if (rword == RES_THEN) {
9492 /* if false; then ... fi has exitcode 0! */
9493 G.last_exitcode = rcode = EXIT_SUCCESS;
9494 /* "if <false> THEN cmd": skip cmd */
9498 if (rword == RES_ELSE || rword == RES_ELIF) {
9499 /* "if <true> then ... ELSE/ELIF cmd":
9500 * skip cmd and all following ones */
9505 #if ENABLE_HUSH_LOOPS
9506 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9508 /* first loop through for */
9510 static const char encoded_dollar_at[] ALIGN1 = {
9511 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9512 }; /* encoded representation of "$@" */
9513 static const char *const encoded_dollar_at_argv[] = {
9514 encoded_dollar_at, NULL
9515 }; /* argv list with one element: "$@" */
9518 G.last_exitcode = rcode = EXIT_SUCCESS;
9519 vals = (char**)encoded_dollar_at_argv;
9520 if (pi->next->res_word == RES_IN) {
9521 /* if no variable values after "in" we skip "for" */
9522 if (!pi->next->cmds[0].argv) {
9523 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9526 vals = pi->next->cmds[0].argv;
9527 } /* else: "for var; do..." -> assume "$@" list */
9528 /* create list of variable values */
9529 debug_print_strings("for_list made from", vals);
9530 for_list = expand_strvec_to_strvec(vals);
9531 for_lcur = for_list;
9532 debug_print_strings("for_list", for_list);
9535 /* "for" loop is over, clean up */
9541 /* Insert next value from for_lcur */
9542 /* note: *for_lcur already has quotes removed, $var expanded, etc */
9543 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
9546 if (rword == RES_IN) {
9547 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9549 if (rword == RES_DONE) {
9550 continue; /* "done" has no cmds too */
9553 #if ENABLE_HUSH_CASE
9554 if (rword == RES_CASE) {
9555 debug_printf_exec("CASE cond_code:%d\n", cond_code);
9556 case_word = expand_string_to_string(pi->cmds->argv[0],
9557 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
9558 debug_printf_exec("CASE word1:'%s'\n", case_word);
9559 //unbackslash(case_word);
9560 //debug_printf_exec("CASE word2:'%s'\n", case_word);
9563 if (rword == RES_MATCH) {
9566 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
9567 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9569 /* all prev words didn't match, does this one match? */
9570 argv = pi->cmds->argv;
9573 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9574 pattern = expand_string_to_string(*argv,
9575 EXP_FLAG_ESC_GLOB_CHARS,
9578 /* TODO: which FNM_xxx flags to use? */
9579 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
9580 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9581 pattern, case_word, cond_code);
9583 if (cond_code == 0) {
9584 /* match! we will execute this branch */
9586 case_word = NULL; /* make future "word)" stop */
9593 if (rword == RES_CASE_BODY) { /* inside of a case branch */
9594 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
9596 continue; /* not matched yet, skip this pipe */
9598 if (rword == RES_ESAC) {
9599 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9601 /* "case" did not match anything: still set $? (to 0) */
9602 G.last_exitcode = rcode = EXIT_SUCCESS;
9606 /* Just pressing <enter> in shell should check for jobs.
9607 * OTOH, in non-interactive shell this is useless
9608 * and only leads to extra job checks */
9609 if (pi->num_cmds == 0) {
9610 if (G_interactive_fd)
9611 goto check_jobs_and_continue;
9615 /* After analyzing all keywords and conditions, we decided
9616 * to execute this pipe. NB: have to do checkjobs(NULL)
9617 * after run_pipe to collect any background children,
9618 * even if list execution is to be stopped. */
9619 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
9620 #if ENABLE_HUSH_LOOPS
9621 G.flag_break_continue = 0;
9623 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9625 /* We ran a builtin, function, or group.
9626 * rcode is already known
9627 * and we don't need to wait for anything. */
9628 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9629 G.last_exitcode = rcode;
9630 check_and_run_traps();
9631 #if ENABLE_HUSH_LOOPS
9632 /* Was it "break" or "continue"? */
9633 if (G.flag_break_continue) {
9634 smallint fbc = G.flag_break_continue;
9635 /* We might fall into outer *loop*,
9636 * don't want to break it too */
9638 G.depth_break_continue--;
9639 if (G.depth_break_continue == 0)
9640 G.flag_break_continue = 0;
9641 /* else: e.g. "continue 2" should *break* once, *then* continue */
9642 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9643 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
9644 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9647 /* "continue": simulate end of loop */
9652 if (G_flag_return_in_progress == 1) {
9653 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9656 } else if (pi->followup == PIPE_BG) {
9657 /* What does bash do with attempts to background builtins? */
9658 /* even bash 3.2 doesn't do that well with nested bg:
9659 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9660 * I'm NOT treating inner &'s as jobs */
9662 if (G.run_list_level == 1)
9663 insert_job_into_table(pi);
9665 /* Last command's pid goes to $! */
9666 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
9667 G.last_bg_pid_exitcode = 0;
9668 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
9669 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
9670 rcode = EXIT_SUCCESS;
9674 if (G.run_list_level == 1 && G_interactive_fd) {
9675 /* Waits for completion, then fg's main shell */
9676 rcode = checkjobs_and_fg_shell(pi);
9677 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
9681 /* This one just waits for completion */
9682 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9683 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9685 G.last_exitcode = rcode;
9686 check_and_run_traps();
9689 /* Handle "set -e" */
9690 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9691 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9692 if (G.errexit_depth == 0)
9695 G.errexit_depth = sv_errexit_depth;
9697 /* Analyze how result affects subsequent commands */
9699 if (rword == RES_IF || rword == RES_ELIF)
9702 check_jobs_and_continue:
9703 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9704 dont_check_jobs_but_continue: ;
9705 #if ENABLE_HUSH_LOOPS
9706 /* Beware of "while false; true; do ..."! */
9708 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
9709 /* check for RES_DONE is needed for "while ...; do \n done" case */
9711 if (rword == RES_WHILE) {
9713 /* "while false; do...done" - exitcode 0 */
9714 G.last_exitcode = rcode = EXIT_SUCCESS;
9715 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
9719 if (rword == RES_UNTIL) {
9721 debug_printf_exec(": until expr is true: breaking\n");
9732 #if ENABLE_HUSH_LOOPS
9737 #if ENABLE_HUSH_CASE
9741 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9745 /* Select which version we will use */
9746 static int run_and_free_list(struct pipe *pi)
9749 debug_printf_exec("run_and_free_list entered\n");
9750 if (!G.o_opt[OPT_O_NOEXEC]) {
9751 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9752 rcode = run_list(pi);
9754 /* free_pipe_list has the side effect of clearing memory.
9755 * In the long run that function can be merged with run_list,
9756 * but doing that now would hobble the debugging effort. */
9758 debug_printf_exec("run_and_free_list return %d\n", rcode);
9763 static void install_sighandlers(unsigned mask)
9765 sighandler_t old_handler;
9767 while ((mask >>= 1) != 0) {
9771 old_handler = install_sighandler(sig, pick_sighandler(sig));
9772 /* POSIX allows shell to re-enable SIGCHLD
9773 * even if it was SIG_IGN on entry.
9774 * Therefore we skip IGN check for it:
9778 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9779 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9781 //if (sig == SIGHUP) continue; - TODO?
9782 if (old_handler == SIG_IGN) {
9783 /* oops... restore back to IGN, and record this fact */
9784 install_sighandler(sig, old_handler);
9785 #if ENABLE_HUSH_TRAP
9787 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9789 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9795 /* Called a few times only (or even once if "sh -c") */
9796 static void install_special_sighandlers(void)
9800 /* Which signals are shell-special? */
9801 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
9802 if (G_interactive_fd) {
9803 mask |= SPECIAL_INTERACTIVE_SIGS;
9804 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
9805 mask |= SPECIAL_JOBSTOP_SIGS;
9807 /* Careful, do not re-install handlers we already installed */
9808 if (G.special_sig_mask != mask) {
9809 unsigned diff = mask & ~G.special_sig_mask;
9810 G.special_sig_mask = mask;
9811 install_sighandlers(diff);
9817 /* Set handlers to restore tty pgrp and exit */
9818 static void install_fatal_sighandlers(void)
9822 /* We will restore tty pgrp on these signals */
9824 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9825 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
9826 + (1 << SIGBUS ) * HUSH_DEBUG
9827 + (1 << SIGSEGV) * HUSH_DEBUG
9828 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
9830 /* bash 3.2 seems to handle these just like 'fatal' ones */
9833 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
9834 * if we aren't interactive... but in this case
9835 * we never want to restore pgrp on exit, and this fn is not called
9837 /*+ (1 << SIGHUP )*/
9838 /*+ (1 << SIGTERM)*/
9839 /*+ (1 << SIGINT )*/
9841 G_fatal_sig_mask = mask;
9843 install_sighandlers(mask);
9847 static int set_mode(int state, char mode, const char *o_opt)
9852 G.o_opt[OPT_O_NOEXEC] = state;
9855 IF_HUSH_MODE_X(G_x_mode = state;)
9856 IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
9859 G.o_opt[OPT_O_ERREXIT] = state;
9863 /* "set -o" or "set +o" without parameter.
9864 * in bash, set -o produces this output:
9868 * We always use the second form.
9870 const char *p = o_opt_strings;
9873 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9879 idx = index_in_strings(o_opt_strings, o_opt);
9881 G.o_opt[idx] = state;
9884 /* fall through to error */
9886 return EXIT_FAILURE;
9888 return EXIT_SUCCESS;
9891 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
9892 int hush_main(int argc, char **argv)
9895 OPT_login = (1 << 0),
9898 unsigned builtin_argc;
9900 struct variable *cur_var;
9901 struct variable *shell_ver;
9904 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
9905 G.last_exitcode = EXIT_SUCCESS;
9907 #if ENABLE_HUSH_FAST
9908 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9911 G.argv0_for_re_execing = argv[0];
9914 /* Deal with HUSH_VERSION */
9915 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9916 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
9917 shell_ver = xzalloc(sizeof(*shell_ver));
9918 shell_ver->flg_export = 1;
9919 shell_ver->flg_read_only = 1;
9920 /* Code which handles ${var<op>...} needs writable values for all variables,
9921 * therefore we xstrdup: */
9922 shell_ver->varstr = xstrdup(hush_version_str);
9924 /* Create shell local variables from the values
9925 * currently living in the environment */
9926 G.top_var = shell_ver;
9927 cur_var = G.top_var;
9930 char *value = strchr(*e, '=');
9931 if (value) { /* paranoia */
9932 cur_var->next = xzalloc(sizeof(*cur_var));
9933 cur_var = cur_var->next;
9934 cur_var->varstr = *e;
9935 cur_var->max_len = strlen(*e);
9936 cur_var->flg_export = 1;
9940 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
9941 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9942 putenv(shell_ver->varstr);
9945 set_pwd_var(SETFLAG_EXPORT);
9947 #if BASH_HOSTNAME_VAR
9948 /* Set (but not export) HOSTNAME unless already set */
9949 if (!get_local_var_value("HOSTNAME")) {
9952 set_local_var_from_halves("HOSTNAME", uts.nodename);
9955 /* IFS is not inherited from the parent environment */
9956 set_local_var_from_halves("IFS", defifs);
9958 if (!get_local_var_value("PATH"))
9959 set_local_var_from_halves("PATH", bb_default_root_path);
9961 /* PS1/PS2 are set later, if we determine that we are interactive */
9963 /* bash also exports SHLVL and _,
9964 * and sets (but doesn't export) the following variables:
9966 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9967 * BASH_VERSION='3.2.0(1)-release'
9969 * MACHTYPE=i386-pc-linux-gnu
9971 * PPID=<NNNNN> - we also do it elsewhere
9982 * PIPESTATUS=([0]="0")
9983 * HISTFILE=/<xxx>/.bash_history
9987 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9989 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9996 /* Initialize some more globals to non-zero values */
9997 die_func = restore_ttypgrp_and__exit;
9999 /* Shell is non-interactive at first. We need to call
10000 * install_special_sighandlers() if we are going to execute "sh <script>",
10001 * "sh -c <cmds>" or login shell's /etc/profile and friends.
10002 * If we later decide that we are interactive, we run install_special_sighandlers()
10003 * in order to intercept (more) signals.
10006 /* Parse options */
10007 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
10008 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
10010 #if NUM_SCRIPTS > 0
10012 optarg = get_script_content(-argc - 1);
10014 argc = string_array_len(argv);
10019 int opt = getopt(argc, argv, "+c:exinsl"
10022 # if ENABLE_HUSH_FUNCTIONS
10032 * sh ... -c 'script'
10033 * sh ... -c 'script' ARG0 [ARG1...]
10034 * On NOMMU, if builtin_argc != 0,
10035 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
10036 * "" needs to be replaced with NULL
10037 * and BARGV vector fed to builtin function.
10038 * Note: the form without ARG0 never happens:
10039 * sh ... -c 'builtin' BARGV... ""
10041 #if NUM_SCRIPTS > 0
10045 G.root_pid = getpid();
10046 G.root_ppid = getppid();
10048 G.global_argv = argv + optind;
10049 G.global_argc = argc - optind;
10050 if (builtin_argc) {
10051 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10052 const struct built_in_command *x;
10054 install_special_sighandlers();
10055 x = find_builtin(optarg);
10056 if (x) { /* paranoia */
10057 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10058 G.global_argv += builtin_argc;
10059 G.global_argv[-1] = NULL; /* replace "" */
10061 G.last_exitcode = x->b_function(argv + optind - 1);
10066 if (!G.global_argv[0]) {
10067 /* -c 'script' (no params): prevent empty $0 */
10068 G.global_argv--; /* points to argv[i] of 'script' */
10069 G.global_argv[0] = argv[0];
10071 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10072 install_special_sighandlers();
10073 parse_and_run_string(optarg);
10076 /* Well, we cannot just declare interactiveness,
10077 * we have to have some stuff (ctty, etc) */
10078 /* G_interactive_fd++; */
10084 flags |= OPT_login;
10087 case '<': /* "big heredoc" support */
10088 full_write1_str(optarg);
10091 unsigned long long empty_trap_mask;
10093 G.root_pid = bb_strtou(optarg, &optarg, 16);
10095 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10097 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10099 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
10101 builtin_argc = bb_strtou(optarg, &optarg, 16);
10103 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10104 if (empty_trap_mask != 0) {
10105 IF_HUSH_TRAP(int sig;)
10106 install_special_sighandlers();
10107 # if ENABLE_HUSH_TRAP
10108 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10109 for (sig = 1; sig < NSIG; sig++) {
10110 if (empty_trap_mask & (1LL << sig)) {
10111 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
10112 install_sighandler(sig, SIG_IGN);
10117 # if ENABLE_HUSH_LOOPS
10119 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
10121 # if ENABLE_HUSH_FUNCTIONS
10122 /* nommu uses re-exec trick for "... | func | ...",
10123 * should allow "return".
10124 * This accidentally allows returns in subshells.
10126 G_flag_return_in_progress = -1;
10132 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
10134 # if ENABLE_HUSH_FUNCTIONS
10136 struct function *funcp = new_function(optarg);
10137 /* funcp->name is already set to optarg */
10138 /* funcp->body is set to NULL. It's a special case. */
10139 funcp->body_as_string = argv[optind];
10148 if (set_mode(1, opt, NULL) == 0) /* no error */
10152 fprintf(stderr, "Usage: sh [FILE]...\n"
10153 " or: sh -c command [args]...\n\n");
10154 exit(EXIT_FAILURE);
10159 } /* option parsing loop */
10161 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10162 G.global_argc = argc - (optind - 1);
10163 G.global_argv = argv + (optind - 1);
10164 G.global_argv[0] = argv[0];
10167 G.root_pid = getpid();
10168 G.root_ppid = getppid();
10171 /* If we are login shell... */
10172 if (flags & OPT_login) {
10174 debug_printf("sourcing /etc/profile\n");
10175 input = hfopen("/etc/profile");
10176 if (input != NULL) {
10177 install_special_sighandlers();
10178 parse_and_run_file(input);
10181 /* bash: after sourcing /etc/profile,
10182 * tries to source (in the given order):
10183 * ~/.bash_profile, ~/.bash_login, ~/.profile,
10184 * stopping on first found. --noprofile turns this off.
10185 * bash also sources ~/.bash_logout on exit.
10186 * If called as sh, skips .bash_XXX files.
10190 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10191 if (!G.opt_s && G.global_argv[1]) {
10194 * "bash <script>" (which is never interactive (unless -i?))
10195 * sources $BASH_ENV here (without scanning $PATH).
10196 * If called as sh, does the same but with $ENV.
10197 * Also NB, per POSIX, $ENV should undergo parameter expansion.
10201 debug_printf("running script '%s'\n", G.global_argv[0]);
10202 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
10203 input = hfopen(G.global_argv[0]);
10205 bb_simple_perror_msg_and_die(G.global_argv[0]);
10207 xfunc_error_retval = 1;
10208 install_special_sighandlers();
10209 parse_and_run_file(input);
10210 #if ENABLE_FEATURE_CLEAN_UP
10215 /* "implicit" -s: bare interactive hush shows 's' in $- */
10218 /* Up to here, shell was non-interactive. Now it may become one.
10219 * NB: don't forget to (re)run install_special_sighandlers() as needed.
10222 /* A shell is interactive if the '-i' flag was given,
10223 * or if all of the following conditions are met:
10225 * no arguments remaining or the -s flag given
10226 * standard input is a terminal
10227 * standard output is a terminal
10228 * Refer to Posix.2, the description of the 'sh' utility.
10230 #if ENABLE_HUSH_JOB
10231 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10232 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10233 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10234 if (G_saved_tty_pgrp < 0)
10235 G_saved_tty_pgrp = 0;
10237 /* try to dup stdin to high fd#, >= 255 */
10238 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10239 if (G_interactive_fd < 0) {
10240 /* try to dup to any fd */
10241 G_interactive_fd = dup(STDIN_FILENO);
10242 if (G_interactive_fd < 0) {
10244 G_interactive_fd = 0;
10245 G_saved_tty_pgrp = 0;
10249 debug_printf("interactive_fd:%d\n", G_interactive_fd);
10250 if (G_interactive_fd) {
10251 close_on_exec_on(G_interactive_fd);
10253 if (G_saved_tty_pgrp) {
10254 /* If we were run as 'hush &', sleep until we are
10255 * in the foreground (tty pgrp == our pgrp).
10256 * If we get started under a job aware app (like bash),
10257 * make sure we are now in charge so we don't fight over
10258 * who gets the foreground */
10260 pid_t shell_pgrp = getpgrp();
10261 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10262 if (G_saved_tty_pgrp == shell_pgrp)
10264 /* send TTIN to ourself (should stop us) */
10265 kill(- shell_pgrp, SIGTTIN);
10269 /* Install more signal handlers */
10270 install_special_sighandlers();
10272 if (G_saved_tty_pgrp) {
10273 /* Set other signals to restore saved_tty_pgrp */
10274 install_fatal_sighandlers();
10275 /* Put ourselves in our own process group
10276 * (bash, too, does this only if ctty is available) */
10277 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10278 /* Grab control of the terminal */
10279 tcsetpgrp(G_interactive_fd, getpid());
10281 enable_restore_tty_pgrp_on_exit();
10283 # if ENABLE_FEATURE_EDITING
10284 G.line_input_state = new_line_input_t(FOR_SHELL);
10285 # if EDITING_HAS_get_exe_name
10286 G.line_input_state->get_exe_name = get_builtin_name;
10289 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10291 const char *hp = get_local_var_value("HISTFILE");
10293 hp = get_local_var_value("HOME");
10295 hp = concat_path_file(hp, ".hush_history");
10300 G.line_input_state->hist_file = hp;
10301 //set_local_var(xasprintf("HISTFILE=%s", ...));
10303 # if ENABLE_FEATURE_SH_HISTFILESIZE
10304 hp = get_local_var_value("HISTFILESIZE");
10305 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10310 install_special_sighandlers();
10312 #elif ENABLE_HUSH_INTERACTIVE
10313 /* No job control compiled in, only prompt/line editing */
10314 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
10315 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
10316 if (G_interactive_fd < 0) {
10317 /* try to dup to any fd */
10318 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
10319 if (G_interactive_fd < 0)
10321 G_interactive_fd = 0;
10324 if (G_interactive_fd) {
10325 close_on_exec_on(G_interactive_fd);
10327 install_special_sighandlers();
10329 /* We have interactiveness code disabled */
10330 install_special_sighandlers();
10333 * if interactive but not a login shell, sources ~/.bashrc
10334 * (--norc turns this off, --rcfile <file> overrides)
10337 if (G_interactive_fd) {
10338 #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10339 /* Set (but not export) PS1/2 unless already set */
10340 if (!get_local_var_value("PS1"))
10341 set_local_var_from_halves("PS1", "\\w \\$ ");
10342 if (!get_local_var_value("PS2"))
10343 set_local_var_from_halves("PS2", "> ");
10345 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10346 /* note: ash and hush share this string */
10347 printf("\n\n%s %s\n"
10348 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10351 "hush - the humble shell"
10356 parse_and_run_file(hfopen(NULL)); /* stdin */
10359 hush_exit(G.last_exitcode);
10366 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
10371 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
10372 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
10374 int argc = string_array_len(argv);
10375 return applet_main_func(argc, argv);
10378 #if ENABLE_HUSH_TEST || BASH_TEST2
10379 static int FAST_FUNC builtin_test(char **argv)
10381 return run_applet_main(argv, test_main);
10384 #if ENABLE_HUSH_ECHO
10385 static int FAST_FUNC builtin_echo(char **argv)
10387 return run_applet_main(argv, echo_main);
10390 #if ENABLE_HUSH_PRINTF
10391 static int FAST_FUNC builtin_printf(char **argv)
10393 return run_applet_main(argv, printf_main);
10397 #if ENABLE_HUSH_HELP
10398 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10400 const struct built_in_command *x;
10403 "Built-in commands:\n"
10404 "------------------\n");
10405 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10407 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10409 return EXIT_SUCCESS;
10413 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
10414 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10416 if (G.line_input_state)
10417 show_history(G.line_input_state);
10418 return EXIT_SUCCESS;
10422 static char **skip_dash_dash(char **argv)
10425 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10430 static int FAST_FUNC builtin_cd(char **argv)
10432 const char *newdir;
10434 argv = skip_dash_dash(argv);
10436 if (newdir == NULL) {
10437 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
10438 * bash says "bash: cd: HOME not set" and does nothing
10441 const char *home = get_local_var_value("HOME");
10442 newdir = home ? home : "/";
10444 if (chdir(newdir)) {
10445 /* Mimic bash message exactly */
10446 bb_perror_msg("cd: %s", newdir);
10447 return EXIT_FAILURE;
10449 /* Read current dir (get_cwd(1) is inside) and set PWD.
10450 * Note: do not enforce exporting. If PWD was unset or unexported,
10451 * set it again, but do not export. bash does the same.
10453 set_pwd_var(/*flag:*/ 0);
10454 return EXIT_SUCCESS;
10457 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10460 return EXIT_SUCCESS;
10463 static int FAST_FUNC builtin_eval(char **argv)
10465 argv = skip_dash_dash(argv);
10468 return EXIT_SUCCESS;
10470 IF_HUSH_MODE_X(G.x_mode_depth++;)
10471 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
10474 * eval "echo Hi; done" ("done" is syntax error):
10475 * "echo Hi" will not execute too.
10477 parse_and_run_string(argv[0]);
10479 /* "The eval utility shall construct a command by
10480 * concatenating arguments together, separating
10481 * each with a <space> character."
10487 len += strlen(*pp) + 1;
10489 str = p = xmalloc(len);
10492 p = stpcpy(p, *pp);
10498 parse_and_run_string(str);
10501 IF_HUSH_MODE_X(G.x_mode_depth--;)
10502 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
10503 return G.last_exitcode;
10506 static int FAST_FUNC builtin_exec(char **argv)
10508 argv = skip_dash_dash(argv);
10509 if (argv[0] == NULL)
10510 return EXIT_SUCCESS; /* bash does this */
10512 /* Careful: we can end up here after [v]fork. Do not restore
10513 * tty pgrp then, only top-level shell process does that */
10514 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10515 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10517 /* Saved-redirect fds, script fds and G_interactive_fd are still
10518 * open here. However, they are all CLOEXEC, and execv below
10519 * closes them. Try interactive "exec ls -l /proc/self/fd",
10520 * it should show no extra open fds in the "ls" process.
10521 * If we'd try to run builtins/NOEXECs, this would need improving.
10523 //close_saved_fds_and_FILE_fds();
10525 /* TODO: if exec fails, bash does NOT exit! We do.
10526 * We'll need to undo trap cleanup (it's inside execvp_or_die)
10527 * and tcsetpgrp, and this is inherently racy.
10529 execvp_or_die(argv);
10532 static int FAST_FUNC builtin_exit(char **argv)
10534 debug_printf_exec("%s()\n", __func__);
10536 /* interactive bash:
10537 * # trap "echo EEE" EXIT
10540 * There are stopped jobs.
10541 * (if there are _stopped_ jobs, running ones don't count)
10544 * EEE (then bash exits)
10546 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
10549 /* note: EXIT trap is run by hush_exit */
10550 argv = skip_dash_dash(argv);
10551 if (argv[0] == NULL)
10552 hush_exit(G.last_exitcode);
10553 /* mimic bash: exit 123abc == exit 255 + error msg */
10554 xfunc_error_retval = 255;
10555 /* bash: exit -2 == exit 254, no error msg */
10556 hush_exit(xatoi(argv[0]) & 0xff);
10559 #if ENABLE_HUSH_TYPE
10560 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10561 static int FAST_FUNC builtin_type(char **argv)
10563 int ret = EXIT_SUCCESS;
10569 if (0) {} /* make conditional compile easier below */
10570 /*else if (find_alias(*argv))
10571 type = "an alias";*/
10572 # if ENABLE_HUSH_FUNCTIONS
10573 else if (find_function(*argv))
10574 type = "a function";
10576 else if (find_builtin(*argv))
10577 type = "a shell builtin";
10578 else if ((path = find_in_path(*argv)) != NULL)
10581 bb_error_msg("type: %s: not found", *argv);
10582 ret = EXIT_FAILURE;
10586 printf("%s is %s\n", *argv, type);
10594 #if ENABLE_HUSH_READ
10595 /* Interruptibility of read builtin in bash
10596 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10598 * Empty trap makes read ignore corresponding signal, for any signal.
10601 * - terminates non-interactive shell;
10602 * - interrupts read in interactive shell;
10603 * if it has non-empty trap:
10604 * - executes trap and returns to command prompt in interactive shell;
10605 * - executes trap and returns to read in non-interactive shell;
10607 * - is ignored (does not interrupt) read in interactive shell;
10608 * - terminates non-interactive shell;
10609 * if it has non-empty trap:
10610 * - executes trap and returns to read;
10612 * - terminates shell (regardless of interactivity);
10613 * if it has non-empty trap:
10614 * - executes trap and returns to read;
10615 * SIGCHLD from children:
10616 * - does not interrupt read regardless of interactivity:
10617 * try: sleep 1 & read x; echo $x
10619 static int FAST_FUNC builtin_read(char **argv)
10622 struct builtin_read_params params;
10624 memset(¶ms, 0, sizeof(params));
10626 /* "!": do not abort on errors.
10627 * Option string must start with "sr" to match BUILTIN_READ_xxx
10629 params.read_flags = getopt32(argv,
10631 "!srn:p:t:u:d:", ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u, ¶ms.opt_d
10633 "!srn:p:t:u:", ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u
10636 if ((uint32_t)params.read_flags == (uint32_t)-1)
10637 return EXIT_FAILURE;
10639 params.argv = argv;
10640 params.setvar = set_local_var_from_halves;
10641 params.ifs = get_local_var_value("IFS"); /* can be NULL */
10644 r = shell_builtin_read(¶ms);
10646 if ((uintptr_t)r == 1 && errno == EINTR) {
10647 unsigned sig = check_and_run_traps();
10652 if ((uintptr_t)r > 1) {
10653 bb_simple_error_msg(r);
10654 r = (char*)(uintptr_t)1;
10657 return (uintptr_t)r;
10661 #if ENABLE_HUSH_UMASK
10662 static int FAST_FUNC builtin_umask(char **argv)
10669 argv = skip_dash_dash(argv);
10671 mode_t old_mask = mask;
10673 /* numeric umasks are taken as-is */
10674 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10675 if (!isdigit(argv[0][0]))
10677 mask = bb_parse_mode(argv[0], mask);
10678 if (!isdigit(argv[0][0]))
10680 if ((unsigned)mask > 0777) {
10683 * bash: umask: 'q': invalid symbolic mode operator
10684 * bash: umask: 999: octal number out of range
10686 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10691 printf("%04o\n", (unsigned) mask);
10692 /* fall through and restore mask which we set to 0 */
10696 return !rc; /* rc != 0 - success */
10700 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
10701 static void print_escaped(const char *s)
10706 const char *p = strchrnul(s, '\'');
10707 /* print 'xxxx', possibly just '' */
10708 printf("'%.*s'", (int)(p - s), s);
10713 /* s points to '; print "'''...'''" */
10715 do putchar('\''); while (*++s == '\'');
10721 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
10722 static int helper_export_local(char **argv, unsigned flags)
10725 char *name = *argv;
10726 const char *name_end = endofname(name);
10728 if (*name_end == '\0') {
10729 struct variable *var, **vpp;
10731 vpp = get_ptr_to_local_var(name, name_end - name);
10732 var = vpp ? *vpp : NULL;
10734 if (flags & SETFLAG_UNEXPORT) {
10735 /* export -n NAME (without =VALUE) */
10737 var->flg_export = 0;
10738 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10740 } /* else: export -n NOT_EXISTING_VAR: no-op */
10743 if (flags & SETFLAG_EXPORT) {
10744 /* export NAME (without =VALUE) */
10746 var->flg_export = 1;
10747 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10748 putenv(var->varstr);
10752 if (flags & SETFLAG_MAKE_RO) {
10753 /* readonly NAME (without =VALUE) */
10755 var->flg_read_only = 1;
10759 # if ENABLE_HUSH_LOCAL
10760 /* Is this "local" bltin? */
10761 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
10762 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10763 if (var && var->var_nest_level == lvl) {
10764 /* "local x=abc; ...; local x" - ignore second local decl */
10769 /* Exporting non-existing variable.
10770 * bash does not put it in environment,
10771 * but remembers that it is exported,
10772 * and does put it in env when it is set later.
10773 * We just set it to "" and export.
10775 /* Or, it's "local NAME" (without =VALUE).
10776 * bash sets the value to "".
10778 /* Or, it's "readonly NAME" (without =VALUE).
10779 * bash remembers NAME and disallows its creation
10782 name = xasprintf("%s=", name);
10784 if (*name_end != '=') {
10785 bb_error_msg("'%s': bad variable name", name);
10786 /* do not parse following argv[]s: */
10789 /* (Un)exporting/making local NAME=VALUE */
10790 name = xstrdup(name);
10791 /* Testcase: export PS1='\w \$ ' */
10794 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
10795 if (set_local_var(name, flags))
10796 return EXIT_FAILURE;
10798 return EXIT_SUCCESS;
10802 #if ENABLE_HUSH_EXPORT
10803 static int FAST_FUNC builtin_export(char **argv)
10805 unsigned opt_unexport;
10807 # if ENABLE_HUSH_EXPORT_N
10808 /* "!": do not abort on errors */
10809 opt_unexport = getopt32(argv, "!n");
10810 if (opt_unexport == (uint32_t)-1)
10811 return EXIT_FAILURE;
10818 if (argv[0] == NULL) {
10819 char **e = environ;
10825 /* ash emits: export VAR='VAL'
10826 * bash: declare -x VAR="VAL"
10827 * we follow ash example */
10828 const char *s = *e++;
10829 const char *p = strchr(s, '=');
10831 if (!p) /* wtf? take next variable */
10834 printf("export %.*s", (int)(p - s) + 1, s);
10835 print_escaped(p + 1);
10839 /*fflush_all(); - done after each builtin anyway */
10841 return EXIT_SUCCESS;
10844 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
10848 #if ENABLE_HUSH_LOCAL
10849 static int FAST_FUNC builtin_local(char **argv)
10851 if (G.func_nest_level == 0) {
10852 bb_error_msg("%s: not in a function", argv[0]);
10853 return EXIT_FAILURE; /* bash compat */
10856 /* Since all builtins run in a nested variable level,
10857 * need to use level - 1 here. Or else the variable will be removed at once
10858 * after builtin returns.
10860 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
10864 #if ENABLE_HUSH_READONLY
10865 static int FAST_FUNC builtin_readonly(char **argv)
10868 if (*argv == NULL) {
10869 /* bash: readonly [-p]: list all readonly VARs
10870 * (-p has no effect in bash)
10872 struct variable *e;
10873 for (e = G.top_var; e; e = e->next) {
10874 if (e->flg_read_only) {
10875 //TODO: quote value: readonly VAR='VAL'
10876 printf("readonly %s\n", e->varstr);
10879 return EXIT_SUCCESS;
10881 return helper_export_local(argv, SETFLAG_MAKE_RO);
10885 #if ENABLE_HUSH_UNSET
10886 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10887 static int FAST_FUNC builtin_unset(char **argv)
10892 /* "!": do not abort on errors */
10893 /* "+": stop at 1st non-option */
10894 opts = getopt32(argv, "!+vf");
10895 if (opts == (unsigned)-1)
10896 return EXIT_FAILURE;
10898 bb_simple_error_msg("unset: -v and -f are exclusive");
10899 return EXIT_FAILURE;
10903 ret = EXIT_SUCCESS;
10905 if (!(opts & 2)) { /* not -f */
10906 if (unset_local_var(*argv)) {
10907 /* unset <nonexistent_var> doesn't fail.
10908 * Error is when one tries to unset RO var.
10909 * Message was printed by unset_local_var. */
10910 ret = EXIT_FAILURE;
10913 # if ENABLE_HUSH_FUNCTIONS
10924 #if ENABLE_HUSH_SET
10925 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10926 * built-in 'set' handler
10928 * set [-abCefhmnuvx] [-o option] [argument...]
10929 * set [+abCefhmnuvx] [+o option] [argument...]
10930 * set -- [argument...]
10933 * Implementations shall support the options in both their hyphen and
10934 * plus-sign forms. These options can also be specified as options to sh.
10936 * Write out all variables and their values: set
10937 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10938 * Turn on the -x and -v options: set -xv
10939 * Unset all positional parameters: set --
10940 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10941 * Set the positional parameters to the expansion of x, even if x expands
10942 * with a leading '-' or '+': set -- $x
10944 * So far, we only support "set -- [argument...]" and some of the short names.
10946 static int FAST_FUNC builtin_set(char **argv)
10949 char **pp, **g_argv;
10950 char *arg = *++argv;
10953 struct variable *e;
10954 for (e = G.top_var; e; e = e->next)
10956 return EXIT_SUCCESS;
10960 if (strcmp(arg, "--") == 0) {
10964 if (arg[0] != '+' && arg[0] != '-')
10966 for (n = 1; arg[n]; ++n) {
10967 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
10968 bb_error_msg("%s: %s: invalid option", "set", arg);
10969 return EXIT_FAILURE;
10971 if (arg[n] == 'o' && argv[1])
10974 } while ((arg = *++argv) != NULL);
10975 /* Now argv[0] is 1st argument */
10978 return EXIT_SUCCESS;
10981 /* NB: G.global_argv[0] ($0) is never freed/changed */
10982 g_argv = G.global_argv;
10983 if (G.global_args_malloced) {
10989 G.global_args_malloced = 1;
10990 pp = xzalloc(sizeof(pp[0]) * 2);
10991 pp[0] = g_argv[0]; /* retain $0 */
10994 /* This realloc's G.global_argv */
10995 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10997 G.global_argc = 1 + string_array_len(pp + 1);
10999 return EXIT_SUCCESS;
11003 static int FAST_FUNC builtin_shift(char **argv)
11006 argv = skip_dash_dash(argv);
11008 n = bb_strtou(argv[0], NULL, 10);
11009 if (errno || n < 0) {
11010 /* shared string with ash.c */
11011 bb_error_msg("Illegal number: %s", argv[0]);
11013 * ash aborts in this case.
11014 * bash prints error message and set $? to 1.
11015 * Interestingly, for "shift 99999" bash does not
11016 * print error message, but does set $? to 1
11017 * (and does no shifting at all).
11021 if (n >= 0 && n < G.global_argc) {
11022 if (G_global_args_malloced) {
11025 free(G.global_argv[m++]);
11027 G.global_argc -= n;
11028 memmove(&G.global_argv[1], &G.global_argv[n+1],
11029 G.global_argc * sizeof(G.global_argv[0]));
11030 return EXIT_SUCCESS;
11032 return EXIT_FAILURE;
11035 #if ENABLE_HUSH_GETOPTS
11036 static int FAST_FUNC builtin_getopts(char **argv)
11038 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11041 If a required argument is not found, and getopts is not silent,
11042 a question mark (?) is placed in VAR, OPTARG is unset, and a
11043 diagnostic message is printed. If getopts is silent, then a
11044 colon (:) is placed in VAR and OPTARG is set to the option
11047 Test that VAR is a valid variable name?
11049 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
11052 const char *cp, *optstring, *var;
11053 int c, n, exitcode, my_opterr;
11056 optstring = *++argv;
11057 if (!optstring || !(var = *++argv)) {
11058 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
11059 return EXIT_FAILURE;
11063 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11065 argv = G.global_argv;
11069 if (optstring[0] != ':') {
11070 cp = get_local_var_value("OPTERR");
11071 /* 0 if "OPTERR=0", 1 otherwise */
11072 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
11075 /* getopts stops on first non-option. Add "+" to force that */
11076 /*if (optstring[0] != '+')*/ {
11077 char *s = alloca(strlen(optstring) + 2);
11078 sprintf(s, "+%s", optstring);
11082 /* Naively, now we should just
11083 * cp = get_local_var_value("OPTIND");
11084 * optind = cp ? atoi(cp) : 0;
11086 * opterr = my_opterr;
11087 * c = getopt(string_array_len(argv), argv, optstring);
11088 * and be done? Not so fast...
11089 * Unlike normal getopt() usage in C programs, here
11090 * each successive call will (usually) have the same argv[] CONTENTS,
11091 * but not the ADDRESSES. Worse yet, it's possible that between
11092 * invocations of "getopts", there will be calls to shell builtins
11093 * which use getopt() internally. Example:
11094 * while getopts "abc" RES -a -bc -abc de; do
11097 * This would not work correctly: getopt() call inside "unset"
11098 * modifies internal libc state which is tracking position in
11099 * multi-option strings ("-abc"). At best, it can skip options
11100 * or return the same option infinitely. With glibc implementation
11101 * of getopt(), it would use outright invalid pointers and return
11102 * garbage even _without_ "unset" mangling internal state.
11104 * We resort to resetting getopt() state and calling it N times,
11105 * until we get Nth result (or failure).
11106 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11110 n = string_array_len(argv);
11113 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11114 c = getopt(n, argv, optstring);
11118 } while (count <= G.getopt_count);
11120 /* Set OPTIND. Prevent resetting of the magic counter! */
11121 set_local_var_from_halves("OPTIND", utoa(optind));
11122 G.getopt_count = count; /* "next time, give me N+1'th result" */
11123 GETOPT_RESET(); /* just in case */
11126 /* Always set or unset, never left as-is, even on exit/error:
11127 * "If no option was found, or if the option that was found
11128 * does not have an option-argument, OPTARG shall be unset."
11132 /* If ":optstring" and unknown option is seen,
11133 * it is stored to OPTARG.
11135 if (optstring[1] == ':') {
11141 set_local_var_from_halves("OPTARG", cp);
11143 unset_local_var("OPTARG");
11145 /* Convert -1 to "?" */
11146 exitcode = EXIT_SUCCESS;
11147 if (c < 0) { /* -1: end of options */
11148 exitcode = EXIT_FAILURE;
11154 set_local_var_from_halves(var, cbuf);
11160 static int FAST_FUNC builtin_source(char **argv)
11162 char *arg_path, *filename;
11165 char *args_need_save;
11166 #if ENABLE_HUSH_FUNCTIONS
11170 argv = skip_dash_dash(argv);
11171 filename = argv[0];
11173 /* bash says: "bash: .: filename argument required" */
11174 return 2; /* bash compat */
11177 if (!strchr(filename, '/')) {
11178 arg_path = find_in_path(filename);
11180 filename = arg_path;
11181 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
11183 bb_simple_perror_msg(filename);
11184 return EXIT_FAILURE;
11187 input = hfopen(filename);
11190 bb_perror_msg("%s", filename);
11191 /* POSIX: non-interactive shell should abort here,
11192 * not merely fail. So far no one complained :)
11194 return EXIT_FAILURE;
11197 #if ENABLE_HUSH_FUNCTIONS
11198 sv_flg = G_flag_return_in_progress;
11199 /* "we are inside sourced file, ok to use return" */
11200 G_flag_return_in_progress = -1;
11202 args_need_save = argv[1]; /* used as a boolean variable */
11203 if (args_need_save)
11204 save_and_replace_G_args(&sv, argv);
11206 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11207 G.last_exitcode = 0;
11208 parse_and_run_file(input);
11211 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11212 restore_G_args(&sv, argv);
11213 #if ENABLE_HUSH_FUNCTIONS
11214 G_flag_return_in_progress = sv_flg;
11217 return G.last_exitcode;
11220 #if ENABLE_HUSH_TRAP
11221 static int FAST_FUNC builtin_trap(char **argv)
11227 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
11232 /* No args: print all trapped */
11233 for (i = 0; i < NSIG; ++i) {
11235 printf("trap -- ");
11236 print_escaped(G_traps[i]);
11237 /* note: bash adds "SIG", but only if invoked
11238 * as "bash". If called as "sh", or if set -o posix,
11239 * then it prints short signal names.
11240 * We are printing short names: */
11241 printf(" %s\n", get_signame(i));
11244 /*fflush_all(); - done after each builtin anyway */
11245 return EXIT_SUCCESS;
11249 /* If first arg is a number: reset all specified signals */
11250 sig = bb_strtou(*argv, NULL, 10);
11254 ret = EXIT_SUCCESS;
11256 sighandler_t handler;
11258 sig = get_signum(*argv++);
11260 ret = EXIT_FAILURE;
11261 /* Mimic bash message exactly */
11262 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
11266 free(G_traps[sig]);
11267 G_traps[sig] = xstrdup(new_cmd);
11269 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
11270 get_signame(sig), sig, G_traps[sig]);
11272 /* There is no signal for 0 (EXIT) */
11277 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11279 /* We are removing trap handler */
11280 handler = pick_sighandler(sig);
11281 install_sighandler(sig, handler);
11286 if (!argv[1]) { /* no second arg */
11287 bb_simple_error_msg("trap: invalid arguments");
11288 return EXIT_FAILURE;
11291 /* First arg is "-": reset all specified to default */
11292 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11293 /* Everything else: set arg as signal handler
11294 * (includes "" case, which ignores signal) */
11295 if (argv[0][0] == '-') {
11296 if (argv[0][1] == '\0') { /* "-" */
11297 /* new_cmd remains NULL: "reset these sigs" */
11300 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11303 /* else: "-something", no special meaning */
11308 goto process_sig_list;
11312 #if ENABLE_HUSH_JOB
11313 static struct pipe *parse_jobspec(const char *str)
11318 if (sscanf(str, "%%%u", &jobnum) != 1) {
11320 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11322 bb_error_msg("bad argument '%s'", str);
11325 /* It is "%%", "%+" or "%" - current job */
11326 jobnum = G.last_jobid;
11328 bb_simple_error_msg("no current job");
11332 for (pi = G.job_list; pi; pi = pi->next) {
11333 if (pi->jobid == jobnum) {
11337 bb_error_msg("%u: no such job", jobnum);
11341 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11344 const char *status_string;
11346 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11347 for (job = G.job_list; job; job = job->next) {
11348 if (job->alive_cmds == job->stopped_cmds)
11349 status_string = "Stopped";
11351 status_string = "Running";
11353 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11356 clean_up_last_dead_job();
11358 return EXIT_SUCCESS;
11361 /* built-in 'fg' and 'bg' handler */
11362 static int FAST_FUNC builtin_fg_bg(char **argv)
11367 if (!G_interactive_fd)
11368 return EXIT_FAILURE;
11370 /* If they gave us no args, assume they want the last backgrounded task */
11372 for (pi = G.job_list; pi; pi = pi->next) {
11373 if (pi->jobid == G.last_jobid) {
11377 bb_error_msg("%s: no current job", argv[0]);
11378 return EXIT_FAILURE;
11381 pi = parse_jobspec(argv[1]);
11383 return EXIT_FAILURE;
11385 /* TODO: bash prints a string representation
11386 * of job being foregrounded (like "sleep 1 | cat") */
11387 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
11388 /* Put the job into the foreground. */
11389 tcsetpgrp(G_interactive_fd, pi->pgrp);
11392 /* Restart the processes in the job */
11393 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11394 for (i = 0; i < pi->num_cmds; i++) {
11395 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
11397 pi->stopped_cmds = 0;
11399 i = kill(- pi->pgrp, SIGCONT);
11401 if (errno == ESRCH) {
11402 delete_finished_job(pi);
11403 return EXIT_SUCCESS;
11405 bb_simple_perror_msg("kill (SIGCONT)");
11408 if (argv[0][0] == 'f') {
11409 remove_job_from_table(pi); /* FG job shouldn't be in job table */
11410 return checkjobs_and_fg_shell(pi);
11412 return EXIT_SUCCESS;
11416 #if ENABLE_HUSH_KILL
11417 static int FAST_FUNC builtin_kill(char **argv)
11421 # if ENABLE_HUSH_JOB
11422 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11430 if (argv[i][0] != '%')
11433 * "kill %N" - job kill
11434 * Converting to pgrp / pid kill
11436 pi = parse_jobspec(argv[i]);
11438 /* Eat bad jobspec */
11442 argv[j - 1] = argv[j];
11449 * In jobs started under job control, we signal
11450 * entire process group by kill -PGRP_ID.
11451 * This happens, f.e., in interactive shell.
11453 * Otherwise, we signal each child via
11454 * kill PID1 PID2 PID3.
11456 * sh -c 'sleep 1|sleep 1 & kill %1'
11457 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11458 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11460 n = G_interactive_fd ? 1 : pi->num_cmds;
11461 dst = alloca(n * sizeof(int)*4);
11463 if (G_interactive_fd)
11464 dst += sprintf(dst, " -%u", (int)pi->pgrp);
11465 else for (j = 0; j < n; j++) {
11466 struct command *cmd = &pi->cmds[j];
11467 /* Skip exited members of the job */
11471 * kill_main has matching code to expect
11472 * leading space. Needed to not confuse
11473 * negative pids with "kill -SIGNAL_NO" syntax
11475 dst += sprintf(dst, " %u", (int)cmd->pid);
11478 } while (argv[++i]);
11482 if (argv[1] || ret == 0) {
11483 ret = run_applet_main(argv, kill_main);
11485 /* else: ret = 1, "kill %bad_jobspec" case */
11490 #if ENABLE_HUSH_WAIT
11491 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
11492 # if !ENABLE_HUSH_JOB
11493 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11495 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
11502 if (!sigisemptyset(&G.pending_set))
11505 /* waitpid is not interruptible by SA_RESTARTed
11506 * signals which we use. Thus, this ugly dance:
11509 /* Make sure possible SIGCHLD is stored in kernel's
11510 * pending signal mask before we call waitpid.
11511 * Or else we may race with SIGCHLD, lose it,
11512 * and get stuck in sigsuspend...
11514 sigfillset(&oldset); /* block all signals, remember old set */
11515 sigprocmask2(SIG_SETMASK, &oldset);
11517 if (!sigisemptyset(&G.pending_set)) {
11518 /* Crap! we raced with some signal! */
11522 /*errno = 0; - checkjobs does this */
11523 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
11524 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
11525 debug_printf_exec("checkjobs:%d\n", ret);
11526 # if ENABLE_HUSH_JOB
11527 if (waitfor_pipe) {
11528 int rcode = job_exited_or_stopped(waitfor_pipe);
11529 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11532 sigprocmask(SIG_SETMASK, &oldset, NULL);
11537 /* if ECHILD, there are no children (ret is -1 or 0) */
11538 /* if ret == 0, no children changed state */
11539 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
11540 if (errno == ECHILD || ret) {
11542 if (ret < 0) /* if ECHILD, may need to fix "ret" */
11544 # if ENABLE_HUSH_BASH_COMPAT
11545 if (waitfor_pid == -1 && errno == ECHILD) {
11546 /* exitcode of "wait -n" with no children is 127, not 0 */
11550 sigprocmask(SIG_SETMASK, &oldset, NULL);
11553 /* Wait for SIGCHLD or any other signal */
11554 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11555 /* Note: sigsuspend invokes signal handler */
11556 sigsuspend(&oldset);
11558 sigprocmask(SIG_SETMASK, &oldset, NULL);
11560 /* So, did we get a signal? */
11561 sig = check_and_run_traps();
11562 if (sig /*&& sig != SIGCHLD - always true */) {
11563 /* Do this for any (non-ignored) signal, not only for ^C */
11567 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11572 static int FAST_FUNC builtin_wait(char **argv)
11577 argv = skip_dash_dash(argv);
11578 # if ENABLE_HUSH_BASH_COMPAT
11579 if (argv[0] && strcmp(argv[0], "-n") == 0) {
11581 /* (bash accepts "wait -n PID" too and ignores PID) */
11582 G.dead_job_exitcode = -1;
11583 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
11586 if (argv[0] == NULL) {
11587 /* Don't care about wait results */
11588 /* Note 1: must wait until there are no more children */
11589 /* Note 2: must be interruptible */
11591 * $ sleep 3 & sleep 6 & wait
11592 * [1] 30934 sleep 3
11593 * [2] 30935 sleep 6
11596 * $ sleep 3 & sleep 6 & wait
11597 * [1] 30936 sleep 3
11598 * [2] 30937 sleep 6
11600 * ^C <-- after ~4 sec from keyboard
11603 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
11607 pid_t pid = bb_strtou(*argv, NULL, 10);
11608 if (errno || pid <= 0) {
11609 # if ENABLE_HUSH_JOB
11610 if (argv[0][0] == '%') {
11611 struct pipe *wait_pipe;
11612 ret = 127; /* bash compat for bad jobspecs */
11613 wait_pipe = parse_jobspec(*argv);
11615 ret = job_exited_or_stopped(wait_pipe);
11617 ret = wait_for_child_or_signal(wait_pipe, 0);
11619 /* waiting on "last dead job" removes it */
11620 clean_up_last_dead_job();
11623 /* else: parse_jobspec() already emitted error msg */
11627 /* mimic bash message */
11628 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
11629 ret = EXIT_FAILURE;
11630 continue; /* bash checks all argv[] */
11633 /* Do we have such child? */
11634 ret = waitpid(pid, &status, WNOHANG);
11638 if (errno == ECHILD) {
11639 if (pid == G.last_bg_pid) {
11640 /* "wait $!" but last bg task has already exited. Try:
11641 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11642 * In bash it prints exitcode 0, then 3.
11643 * In dash, it is 127.
11645 ret = G.last_bg_pid_exitcode;
11647 /* Example: "wait 1". mimic bash message */
11648 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
11652 bb_perror_msg("wait %s", *argv);
11654 continue; /* bash checks all argv[] */
11657 /* Yes, and it still runs */
11658 ret = wait_for_child_or_signal(NULL, pid);
11660 /* Yes, and it just exited */
11661 process_wait_result(NULL, pid, status);
11662 ret = WEXITSTATUS(status);
11663 if (WIFSIGNALED(status))
11664 ret = 128 + WTERMSIG(status);
11672 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11673 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11676 def = bb_strtou(argv[1], NULL, 10);
11677 if (errno || def < def_min || argv[2]) {
11678 bb_error_msg("%s: bad arguments", argv[0]);
11686 #if ENABLE_HUSH_LOOPS
11687 static int FAST_FUNC builtin_break(char **argv)
11690 if (G.depth_of_loop == 0) {
11691 bb_error_msg("%s: only meaningful in a loop", argv[0]);
11692 /* if we came from builtin_continue(), need to undo "= 1" */
11693 G.flag_break_continue = 0;
11694 return EXIT_SUCCESS; /* bash compat */
11696 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
11698 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11699 if (depth == UINT_MAX)
11700 G.flag_break_continue = BC_BREAK;
11701 if (G.depth_of_loop < depth)
11702 G.depth_break_continue = G.depth_of_loop;
11704 return EXIT_SUCCESS;
11707 static int FAST_FUNC builtin_continue(char **argv)
11709 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11710 return builtin_break(argv);
11714 #if ENABLE_HUSH_FUNCTIONS
11715 static int FAST_FUNC builtin_return(char **argv)
11719 if (G_flag_return_in_progress != -1) {
11720 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11721 return EXIT_FAILURE; /* bash compat */
11724 G_flag_return_in_progress = 1;
11727 * out of range: wraps around at 256, does not error out
11728 * non-numeric param:
11729 * f() { false; return qwe; }; f; echo $?
11730 * bash: return: qwe: numeric argument required <== we do this
11731 * 255 <== we also do this
11733 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11738 #if ENABLE_HUSH_TIMES
11739 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11741 static const uint8_t times_tbl[] ALIGN1 = {
11742 ' ', offsetof(struct tms, tms_utime),
11743 '\n', offsetof(struct tms, tms_stime),
11744 ' ', offsetof(struct tms, tms_cutime),
11745 '\n', offsetof(struct tms, tms_cstime),
11752 clk_tck = bb_clk_tck();
11757 unsigned sec, frac;
11759 t = *(clock_t *)(((char *) &buf) + p[1]);
11761 frac = t % clk_tck;
11762 printf("%um%u.%03us%c",
11763 sec / 60, sec % 60,
11764 (frac * 1000) / clk_tck,
11769 return EXIT_SUCCESS;
11773 #if ENABLE_HUSH_MEMLEAK
11774 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11779 # ifdef M_TRIM_THRESHOLD
11780 /* Optional. Reduces probability of false positives */
11783 /* Crude attempt to find where "free memory" starts,
11784 * sans fragmentation. */
11786 l = (unsigned long)p;
11789 if (l < (unsigned long)p) l = (unsigned long)p;
11795 struct mallinfo mi = mallinfo();
11796 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11797 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11801 if (!G.memleak_value)
11802 G.memleak_value = l;
11804 l -= G.memleak_value;
11811 /* Exitcode is "how many kilobytes we leaked since 1st call" */