blob: 3afb70cb042882be2bac29a154ef1deeea9d397a [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * 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.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * 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
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * 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
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
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.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * 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
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * 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)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * 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
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
86 * [[ /bin/* ]]; echo 0:$?
87 * TODO:
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"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//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.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//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
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//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.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//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.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//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
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
360#ifndef F_DUPFD_CLOEXEC
361# define F_DUPFD_CLOEXEC F_DUPFD
362#endif
363#ifndef PIPE_BUF
364# define PIPE_BUF 4096 /* amount of buffering in a pipe */
365#endif
366
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000367
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100368/* So far, all bash compat is controlled by one config option */
369/* Separate defines document which part of code implements what */
370#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100372#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200374#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200375#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376
377
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200378/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000379#define LEAK_HUNTING 0
380#define BUILD_AS_NOMMU 0
381/* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
384 */
385#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200386/* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
391 */
392#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200393/* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
395 */
396#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000397
398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000399#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400# undef BB_MMU
401# undef USE_FOR_NOMMU
402# undef USE_FOR_MMU
403# define BB_MMU 0
404# define USE_FOR_NOMMU(...) __VA_ARGS__
405# define USE_FOR_MMU(...)
406#endif
407
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200408#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100409#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000410/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef CONFIG_FEATURE_SH_STANDALONE
412# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000413# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100414# undef IF_NOT_FEATURE_SH_STANDALONE
415# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# define IF_FEATURE_SH_STANDALONE(...)
417# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000418#endif
419
Denis Vlasenko05743d72008-02-10 12:10:08 +0000420#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# undef ENABLE_FEATURE_EDITING
422# define ENABLE_FEATURE_EDITING 0
423# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200425# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427#endif
428
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000429/* Do we support ANY keywords? */
430#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000431# define HAS_KEYWORDS 1
432# define IF_HAS_KEYWORDS(...) __VA_ARGS__
433# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000434#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000435# define HAS_KEYWORDS 0
436# define IF_HAS_KEYWORDS(...)
437# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000439
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000440/* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_parse(...) do {} while (0)
445#define debug_print_tree(a, b) do {} while (0)
446#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000447#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000448#define debug_printf_jobs(...) do {} while (0)
449#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200450#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000451#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200452#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000453#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000454#define debug_printf_subst(...) do {} while (0)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200455#define debug_printf_prompt(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000456#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000457
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000458#define ERR_PTR ((void*)(long)1)
459
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100460#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000461
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200462#define _SPECIAL_VARS_STR "_*@$!?#"
463#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
464#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100465#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200466/* Support / and // replace ops */
467/* Note that // is stored as \ in "encoded" string representation */
468# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
469# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
470# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
471#else
472# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
473# define VAR_SUBST_OPS "%#:-=+?"
474# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
475#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200476
Denys Vlasenko932b9972018-01-11 12:39:48 +0100477#define SPECIAL_VAR_SYMBOL_STR "\3"
478#define SPECIAL_VAR_SYMBOL 3
479/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
480#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000481
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200482struct variable;
483
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000484static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
485
486/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000487 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488 */
489#if !BB_MMU
490typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200491 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000493 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494} nommu_save_t;
495#endif
496
Denys Vlasenko9b782552010-09-08 13:33:26 +0200497enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000498 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000499#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000500 RES_IF ,
501 RES_THEN ,
502 RES_ELIF ,
503 RES_ELSE ,
504 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000505#endif
506#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_FOR ,
508 RES_WHILE ,
509 RES_UNTIL ,
510 RES_DO ,
511 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000512#endif
513#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516#if ENABLE_HUSH_CASE
517 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200518 /* three pseudo-keywords support contrived "case" syntax: */
519 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
520 RES_MATCH , /* "word)" */
521 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000522 RES_ESAC ,
523#endif
524 RES_XXXX ,
525 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200526};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000527
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000528typedef struct o_string {
529 char *data;
530 int length; /* position where data is appended */
531 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200532 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000533 /* At least some part of the string was inside '' or "",
534 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200535 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000536 smallint has_empty_slot;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537} o_string;
538enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200539 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
540 EXP_FLAG_GLOB = 0x2,
541 /* Protect newly added chars against globbing
542 * by prepending \ to *, ?, [, \ */
543 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
544};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545/* Used for initialization: o_string foo = NULL_O_STRING; */
546#define NULL_O_STRING { NULL }
547
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200548#ifndef debug_printf_parse
549static const char *const assignment_flag[] = {
550 "MAYBE_ASSIGNMENT",
551 "DEFINITELY_ASSIGNMENT",
552 "NOT_ASSIGNMENT",
553 "WORD_IS_KEYWORD",
554};
555#endif
556
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000557typedef struct in_str {
558 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200559 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200560 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000561 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200564/* The descrip member of this structure is only used to make
565 * debugging output pretty */
566static const struct {
567 int mode;
568 signed char default_fd;
569 char descrip[3];
570} redir_table[] = {
571 { O_RDONLY, 0, "<" },
572 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
573 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
574 { O_CREAT|O_RDWR, 1, "<>" },
575 { O_RDONLY, 0, "<<" },
576/* Should not be needed. Bogus default_fd helps in debugging */
577/* { O_RDONLY, 77, "<<" }, */
578};
579
Eric Andersen25f27032001-04-26 23:22:31 +0000580struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000581 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000582 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000583 int rd_fd; /* fd to redirect */
584 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
585 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000586 smallint rd_type; /* (enum redir_type) */
587 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000588 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200589 * bit 0: do we need to trim leading tabs?
590 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000591 */
Eric Andersen25f27032001-04-26 23:22:31 +0000592};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200594 REDIRECT_INPUT = 0,
595 REDIRECT_OVERWRITE = 1,
596 REDIRECT_APPEND = 2,
597 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000598 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200599 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000600
601 REDIRFD_CLOSE = -3,
602 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000603 REDIRFD_TO_FILE = -1,
604 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000605
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000606 HEREDOC_SKIPTABS = 1,
607 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000608} redir_type;
609
Eric Andersen25f27032001-04-26 23:22:31 +0000610
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000611struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000612 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200613 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100614#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100615 unsigned lineno;
616#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200617 smallint cmd_type; /* CMD_xxx */
618#define CMD_NORMAL 0
619#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200620#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
621/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
622 * "export v=t*"
623 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200624# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000625#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200626#if ENABLE_HUSH_FUNCTIONS
627# define CMD_FUNCDEF 3
628#endif
629
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100630 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200631 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
632 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000633#if !BB_MMU
634 char *group_as_string;
635#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000636#if ENABLE_HUSH_FUNCTIONS
637 struct function *child_func;
638/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200639 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000640 * When we execute "f1() {a;}" cmd, we create new function and clear
641 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200642 * When we execute "f1() {b;}", we notice that f1 exists,
643 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000644 * we put those fields back into cmd->xxx
645 * (struct function has ->parent_cmd ptr to facilitate that).
646 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
647 * Without this trick, loop would execute a;b;b;b;...
648 * instead of correct sequence a;b;a;b;...
649 * When command is freed, it severs the link
650 * (sets ->child_func->parent_cmd to NULL).
651 */
652#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000653 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000654/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
655 * and on execution these are substituted with their values.
656 * Substitution can make _several_ words out of one argv[n]!
657 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000658 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000659 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660 struct redir_struct *redirects; /* I/O redirections */
661};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000662/* Is there anything in this command at all? */
663#define IS_NULL_CMD(cmd) \
664 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
665
Eric Andersen25f27032001-04-26 23:22:31 +0000666struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000667 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000668 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000669 int alive_cmds; /* number of commands running (not exited) */
670 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000671#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100672 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000673 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000674 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000675#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000676 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000677 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000678 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
679 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000680};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000681typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100682 PIPE_SEQ = 0,
683 PIPE_AND = 1,
684 PIPE_OR = 2,
685 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000686} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000687/* Is there anything in this pipe at all? */
688#define IS_NULL_PIPE(pi) \
689 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000690
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000691/* This holds pointers to the various results of parsing */
692struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000693 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000694 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000697 /* last command in pipe (being constructed right now) */
698 struct command *command;
699 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000700 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200701 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000702#if !BB_MMU
703 o_string as_string;
704#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200705 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000706#if HAS_KEYWORDS
707 smallint ctx_res_w;
708 smallint ctx_inverted; /* "! cmd | cmd" */
709#if ENABLE_HUSH_CASE
710 smallint ctx_dsemicolon; /* ";;" seen */
711#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000712 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
713 int old_flag;
714 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000715 * example: "if pipe1; pipe2; then pipe3; fi"
716 * when we see "if" or "then", we malloc and copy current context,
717 * and make ->stack point to it. then we parse pipeN.
718 * when closing "then" / fi" / whatever is found,
719 * we move list_head into ->stack->command->group,
720 * copy ->stack into current context, and delete ->stack.
721 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000722 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000723 struct parse_context *stack;
724#endif
725};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726enum {
727 MAYBE_ASSIGNMENT = 0,
728 DEFINITELY_ASSIGNMENT = 1,
729 NOT_ASSIGNMENT = 2,
730 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
731 WORD_IS_KEYWORD = 3,
732};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000733
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000734/* On program start, environ points to initial environment.
735 * putenv adds new pointers into it, unsetenv removes them.
736 * Neither of these (de)allocates the strings.
737 * setenv allocates new strings in malloc space and does putenv,
738 * and thus setenv is unusable (leaky) for shell's purposes */
739#define setenv(...) setenv_is_leaky_dont_use()
740struct variable {
741 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000742 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000743 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200744 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000745 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000746 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000747};
748
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000750 BC_BREAK = 1,
751 BC_CONTINUE = 2,
752};
753
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000754#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000755struct function {
756 struct function *next;
757 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000758 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000759 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200760# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000761 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200762# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000763};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000764#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100767/* set -/+o OPT support. (TODO: make it optional)
768 * bash supports the following opts:
769 * allexport off
770 * braceexpand on
771 * emacs on
772 * errexit off
773 * errtrace off
774 * functrace off
775 * hashall on
776 * histexpand off
777 * history on
778 * ignoreeof off
779 * interactive-comments on
780 * keyword off
781 * monitor on
782 * noclobber off
783 * noexec off
784 * noglob off
785 * nolog off
786 * notify off
787 * nounset off
788 * onecmd off
789 * physical off
790 * pipefail off
791 * posix off
792 * privileged off
793 * verbose off
794 * vi off
795 * xtrace off
796 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800797static const char o_opt_strings[] ALIGN1 =
798 "pipefail\0"
799 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200800 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800801#if ENABLE_HUSH_MODE_X
802 "xtrace\0"
803#endif
804 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100805enum {
806 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800807 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200808 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800809#if ENABLE_HUSH_MODE_X
810 OPT_O_XTRACE,
811#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100812 NUM_OPT_O
813};
814
815
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200816struct FILE_list {
817 struct FILE_list *next;
818 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200819 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200820};
821
822
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000823/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000824/* Sorted roughly by size (smaller offsets == smaller code) */
825struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000826 /* interactive_fd != 0 means we are an interactive shell.
827 * If we are, then saved_tty_pgrp can also be != 0, meaning
828 * that controlling tty is available. With saved_tty_pgrp == 0,
829 * job control still works, but terminal signals
830 * (^C, ^Z, ^Y, ^\) won't work at all, and background
831 * process groups can only be created with "cmd &".
832 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
833 * to give tty to the foreground process group,
834 * and will take it back when the group is stopped (^Z)
835 * or killed (^C).
836 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837#if ENABLE_HUSH_INTERACTIVE
838 /* 'interactive_fd' is a fd# open to ctty, if we have one
839 * _AND_ if we decided to act interactively */
840 int interactive_fd;
841 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200842 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000843# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000844#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000846#endif
847#if ENABLE_FEATURE_EDITING
848 line_input_t *line_input_state;
849#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000850 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200851 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000852 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200853#if ENABLE_HUSH_RANDOM_SUPPORT
854 random_t random_gen;
855#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000856#if ENABLE_HUSH_JOB
857 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100858 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000859 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000860 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400861# define G_saved_tty_pgrp (G.saved_tty_pgrp)
862#else
863# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000864#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200865 /* How deeply are we in context where "set -e" is ignored */
866 int errexit_depth;
867 /* "set -e" rules (do we follow them correctly?):
868 * Exit if pipe, list, or compound command exits with a non-zero status.
869 * Shell does not exit if failed command is part of condition in
870 * if/while, part of && or || list except the last command, any command
871 * in a pipe but the last, or if the command's return value is being
872 * inverted with !. If a compound command other than a subshell returns a
873 * non-zero status because a command failed while -e was being ignored, the
874 * shell does not exit. A trap on ERR, if set, is executed before the shell
875 * exits [ERR is a bashism].
876 *
877 * If a compound command or function executes in a context where -e is
878 * ignored, none of the commands executed within are affected by the -e
879 * setting. If a compound command or function sets -e while executing in a
880 * context where -e is ignored, that setting does not have any effect until
881 * the compound command or the command containing the function call completes.
882 */
883
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100884 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100885#if ENABLE_HUSH_MODE_X
886# define G_x_mode (G.o_opt[OPT_O_XTRACE])
887#else
888# define G_x_mode 0
889#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200890#if ENABLE_HUSH_INTERACTIVE
891 smallint promptmode; /* 0: PS1, 1: PS2 */
892#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000893 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000894#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000895 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000896#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000897#if ENABLE_HUSH_FUNCTIONS
898 /* 0: outside of a function (or sourced file)
899 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000900 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000901 */
902 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200903# define G_flag_return_in_progress (G.flag_return_in_progress)
904#else
905# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000906#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000907 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200908 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000909 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200910 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200911 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100912#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000913 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000914 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100915# define G_global_args_malloced (G.global_args_malloced)
916#else
917# define G_global_args_malloced 0
918#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000919 /* how many non-NULL argv's we have. NB: $# + 1 */
920 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000921 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000922#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000923 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000925#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000926 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000927 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000928#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200929#if ENABLE_HUSH_GETOPTS
930 unsigned getopt_count;
931#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000932 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000933 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200934 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200935 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200936 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200937 unsigned var_nest_level;
938#if ENABLE_HUSH_FUNCTIONS
939# if ENABLE_HUSH_LOCAL
940 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200941# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200942 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000943#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000944 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200945#if ENABLE_HUSH_FAST
946 unsigned count_SIGCHLD;
947 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200948 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200949#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100950#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100951 unsigned lineno;
952 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100953#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200954 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200955 /* Which signals have non-DFL handler (even with no traps set)?
956 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200957 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200958 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200959 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200960 * Other than these two times, never modified.
961 */
962 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200963#if ENABLE_HUSH_JOB
964 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100965# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200966#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200967# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200968#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100969#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000970 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100971# define G_traps G.traps
972#else
973# define G_traps ((char**)NULL)
974#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200975 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100976#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000977 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100978#endif
979#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000980 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000981#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200982 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200983#if ENABLE_FEATURE_EDITING
984 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
985#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000986};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000987#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000988/* Not #defining name to G.name - this quickly gets unwieldy
989 * (too many defines). Also, I actually prefer to see when a variable
990 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000991#define INIT_G() do { \
992 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200993 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
994 sigfillset(&G.sa.sa_mask); \
995 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000996} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000997
998
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000999/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001000static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001001#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001002static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001003#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001004static int builtin_eval(char **argv) FAST_FUNC;
1005static int builtin_exec(char **argv) FAST_FUNC;
1006static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001007#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001008static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001009#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001010#if ENABLE_HUSH_READONLY
1011static int builtin_readonly(char **argv) FAST_FUNC;
1012#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001013#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001014static int builtin_fg_bg(char **argv) FAST_FUNC;
1015static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001017#if ENABLE_HUSH_GETOPTS
1018static int builtin_getopts(char **argv) FAST_FUNC;
1019#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001020#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001022#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001023#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001024static int builtin_history(char **argv) FAST_FUNC;
1025#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001026#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001027static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001028#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001029#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001031#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001032#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001033static int builtin_printf(char **argv) FAST_FUNC;
1034#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001035static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001036#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001038#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001039#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001041#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_shift(char **argv) FAST_FUNC;
1043static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001044#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001045static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001046#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001047#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001048static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001049#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001050#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001052#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001053#if ENABLE_HUSH_TIMES
1054static int builtin_times(char **argv) FAST_FUNC;
1055#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001056static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001057#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001059#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001060#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001061static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001062#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001063#if ENABLE_HUSH_KILL
1064static int builtin_kill(char **argv) FAST_FUNC;
1065#endif
1066#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001067static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001068#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001069#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_break(char **argv) FAST_FUNC;
1071static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001073#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001074static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001075#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001076
1077/* Table of built-in functions. They can be forked or not, depending on
1078 * context: within pipes, they fork. As simple commands, they do not.
1079 * When used in non-forking context, they can change global variables
1080 * in the parent shell process. If forked, of course they cannot.
1081 * For example, 'unset foo | whatever' will parse and run, but foo will
1082 * still be set at the end. */
1083struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001084 const char *b_cmd;
1085 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001086#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001087 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001088# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001090# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001091#endif
1092};
1093
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001094static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001095 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001096 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001097#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001098 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099#endif
1100#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001101 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001102#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001103 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001105 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001107 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1108 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001109 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001110#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001111 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001112#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001113#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001114 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001115#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001116#if ENABLE_HUSH_GETOPTS
1117 BLTIN("getopts" , builtin_getopts , NULL),
1118#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001120 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001122#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001123 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001124#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001125#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001126 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001127#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001128#if ENABLE_HUSH_KILL
1129 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1130#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001131#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001132 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001133#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001134#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001136#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001137#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001139#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001140#if ENABLE_HUSH_READONLY
1141 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1142#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001143#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001144 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001145#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001146#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001148#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001150#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001151 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001152#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001153#if ENABLE_HUSH_TIMES
1154 BLTIN("times" , builtin_times , NULL),
1155#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001156#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001157 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001158#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001159 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001160#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001161 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001162#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001163#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001164 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001165#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001166#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001168#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001169#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001171#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001172#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001173 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001174#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001175};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001176/* These builtins won't be used if we are on NOMMU and need to re-exec
1177 * (it's cheaper to run an external program in this case):
1178 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001179static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001180#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001182#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001183#if BASH_TEST2
1184 BLTIN("[[" , builtin_test , NULL),
1185#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001186#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001188#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001189#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001190 BLTIN("printf" , builtin_printf , NULL),
1191#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001192 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001193#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001194 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001195#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001196};
1197
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001198
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001199/* Debug printouts.
1200 */
1201#if HUSH_DEBUG
1202/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001203# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001204# define debug_enter() (G.debug_indent++)
1205# define debug_leave() (G.debug_indent--)
1206#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001207# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001208# define debug_enter() ((void)0)
1209# define debug_leave() ((void)0)
1210#endif
1211
1212#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001213# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001214#endif
1215
1216#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001217# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001218#endif
1219
1220#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001221#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001222#endif
1223
1224#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001225# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001226#endif
1227
1228#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001229# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001230# define DEBUG_JOBS 1
1231#else
1232# define DEBUG_JOBS 0
1233#endif
1234
1235#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001236# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237# define DEBUG_EXPAND 1
1238#else
1239# define DEBUG_EXPAND 0
1240#endif
1241
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001242#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001243# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001244#endif
1245
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001246#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001247# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248# define DEBUG_GLOB 1
1249#else
1250# define DEBUG_GLOB 0
1251#endif
1252
Denys Vlasenko2db74612017-07-07 22:07:28 +02001253#ifndef debug_printf_redir
1254# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1255#endif
1256
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001258# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259#endif
1260
1261#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001262# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001263#endif
1264
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001265#ifndef debug_printf_prompt
1266# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1267#endif
1268
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001270# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001271# define DEBUG_CLEAN 1
1272#else
1273# define DEBUG_CLEAN 0
1274#endif
1275
1276#if DEBUG_EXPAND
1277static void debug_print_strings(const char *prefix, char **vv)
1278{
1279 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001280 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001281 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001282 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001283}
1284#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001285# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001286#endif
1287
1288
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001289/* Leak hunting. Use hush_leaktool.sh for post-processing.
1290 */
1291#if LEAK_HUNTING
1292static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001293{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001294 void *ptr = xmalloc((size + 0xff) & ~0xff);
1295 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1296 return ptr;
1297}
1298static void *xxrealloc(int lineno, void *ptr, size_t size)
1299{
1300 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1301 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1302 return ptr;
1303}
1304static char *xxstrdup(int lineno, const char *str)
1305{
1306 char *ptr = xstrdup(str);
1307 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1308 return ptr;
1309}
1310static void xxfree(void *ptr)
1311{
1312 fdprintf(2, "free %p\n", ptr);
1313 free(ptr);
1314}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001315# define xmalloc(s) xxmalloc(__LINE__, s)
1316# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1317# define xstrdup(s) xxstrdup(__LINE__, s)
1318# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001319#endif
1320
1321
1322/* Syntax and runtime errors. They always abort scripts.
1323 * In interactive use they usually discard unparsed and/or unexecuted commands
1324 * and return to the prompt.
1325 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1326 */
1327#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001328# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001329# define syntax_error(lineno, msg) syntax_error(msg)
1330# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1331# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1332# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1333# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001334#endif
1335
Denys Vlasenko39701202017-08-02 19:44:05 +02001336static void die_if_script(void)
1337{
1338 if (!G_interactive_fd) {
1339 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1340 xfunc_error_retval = G.last_exitcode;
1341 xfunc_die();
1342 }
1343}
1344
1345static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001346{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001347 va_list p;
1348
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001349#if HUSH_DEBUG >= 2
1350 bb_error_msg("hush.c:%u", lineno);
1351#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001352 va_start(p, fmt);
1353 bb_verror_msg(fmt, p, NULL);
1354 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001355 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001356}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001357
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001358static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001359{
1360 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001361 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001362 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001363 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001364 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001365}
1366
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001367static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001368{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001369 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001370 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001371}
1372
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001373static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001374{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001375 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001376//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1377// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001378}
1379
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001380static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001381{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001382 char msg[2] = { ch, '\0' };
1383 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001384}
1385
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001386static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001387{
1388 char msg[2];
1389 msg[0] = ch;
1390 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001391#if HUSH_DEBUG >= 2
1392 bb_error_msg("hush.c:%u", lineno);
1393#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001394 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001395 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001396}
1397
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001398#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001399# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400# undef syntax_error
1401# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001402# undef syntax_error_unterm_ch
1403# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001404# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001405#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001406# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001407# define syntax_error(msg) syntax_error(__LINE__, msg)
1408# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1409# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1410# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1411# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001412#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001413
Denis Vlasenko552433b2009-04-04 19:29:21 +00001414
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001415#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001416static void cmdedit_update_prompt(void);
1417#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001418# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001419#endif
1420
1421
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001422/* Utility functions
1423 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001424/* Replace each \x with x in place, return ptr past NUL. */
1425static char *unbackslash(char *src)
1426{
Denys Vlasenko71885402009-09-24 01:44:13 +02001427 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001428 while (1) {
1429 if (*src == '\\')
1430 src++;
1431 if ((*dst++ = *src++) == '\0')
1432 break;
1433 }
1434 return dst;
1435}
1436
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001437static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001438{
1439 int i;
1440 unsigned count1;
1441 unsigned count2;
1442 char **v;
1443
1444 v = strings;
1445 count1 = 0;
1446 if (v) {
1447 while (*v) {
1448 count1++;
1449 v++;
1450 }
1451 }
1452 count2 = 0;
1453 v = add;
1454 while (*v) {
1455 count2++;
1456 v++;
1457 }
1458 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1459 v[count1 + count2] = NULL;
1460 i = count2;
1461 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001462 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001463 return v;
1464}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001465#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001466static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1467{
1468 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1469 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1470 return ptr;
1471}
1472#define add_strings_to_strings(strings, add, need_to_dup) \
1473 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1474#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001475
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001476/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001477static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001478{
1479 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001480 v[0] = add;
1481 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001482 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001483}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001484#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001485static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1486{
1487 char **ptr = add_string_to_strings(strings, add);
1488 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1489 return ptr;
1490}
1491#define add_string_to_strings(strings, add) \
1492 xx_add_string_to_strings(__LINE__, strings, add)
1493#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001494
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001495static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001496{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001497 char **v;
1498
1499 if (!strings)
1500 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001501 v = strings;
1502 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001503 free(*v);
1504 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001505 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001506 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507}
1508
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001509static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001510{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001511 int newfd;
1512 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001513 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1514 if (newfd >= 0) {
1515 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1516 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1517 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001518 if (errno == EBUSY)
1519 goto repeat;
1520 if (errno == EINTR)
1521 goto repeat;
1522 }
1523 return newfd;
1524}
1525
Denys Vlasenko657e9002017-07-30 23:34:04 +02001526static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001527{
1528 int newfd;
1529 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001530 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001531 if (newfd < 0) {
1532 if (errno == EBUSY)
1533 goto repeat;
1534 if (errno == EINTR)
1535 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001536 /* fd was not open? */
1537 if (errno == EBADF)
1538 return fd;
1539 xfunc_die();
1540 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001541 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1542 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001543 close(fd);
1544 return newfd;
1545}
1546
1547
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001548/* Manipulating the list of open FILEs */
1549static FILE *remember_FILE(FILE *fp)
1550{
1551 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001552 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001553 n->next = G.FILE_list;
1554 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001555 n->fp = fp;
1556 n->fd = fileno(fp);
1557 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001558 }
1559 return fp;
1560}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001561static void fclose_and_forget(FILE *fp)
1562{
1563 struct FILE_list **pp = &G.FILE_list;
1564 while (*pp) {
1565 struct FILE_list *cur = *pp;
1566 if (cur->fp == fp) {
1567 *pp = cur->next;
1568 free(cur);
1569 break;
1570 }
1571 pp = &cur->next;
1572 }
1573 fclose(fp);
1574}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001575static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001576{
1577 struct FILE_list *fl = G.FILE_list;
1578 while (fl) {
1579 if (fd == fl->fd) {
1580 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001581 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001582 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001583 return 1;
1584 }
1585 fl = fl->next;
1586 }
1587 return 0;
1588}
1589static void restore_redirected_FILEs(void)
1590{
1591 struct FILE_list *fl = G.FILE_list;
1592 while (fl) {
1593 int should_be = fileno(fl->fp);
1594 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001595 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001596 xmove_fd(fl->fd, should_be);
1597 fl->fd = should_be;
1598 }
1599 fl = fl->next;
1600 }
1601}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001602#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001603static void close_all_FILE_list(void)
1604{
1605 struct FILE_list *fl = G.FILE_list;
1606 while (fl) {
1607 /* fclose would also free FILE object.
1608 * It is disastrous if we share memory with a vforked parent.
1609 * I'm not sure we never come here after vfork.
1610 * Therefore just close fd, nothing more.
1611 */
1612 /*fclose(fl->fp); - unsafe */
1613 close(fl->fd);
1614 fl = fl->next;
1615 }
1616}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001617#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001618static int fd_in_FILEs(int fd)
1619{
1620 struct FILE_list *fl = G.FILE_list;
1621 while (fl) {
1622 if (fl->fd == fd)
1623 return 1;
1624 fl = fl->next;
1625 }
1626 return 0;
1627}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628
1629
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001630/* Helpers for setting new $n and restoring them back
1631 */
1632typedef struct save_arg_t {
1633 char *sv_argv0;
1634 char **sv_g_argv;
1635 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001636 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001637} save_arg_t;
1638
1639static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1640{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001641 sv->sv_argv0 = argv[0];
1642 sv->sv_g_argv = G.global_argv;
1643 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001644 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001645
1646 argv[0] = G.global_argv[0]; /* retain $0 */
1647 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001648 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001649
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001650 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001651}
1652
1653static void restore_G_args(save_arg_t *sv, char **argv)
1654{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001655#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001656 if (G.global_args_malloced) {
1657 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001658 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001659 while (*++pp) /* note: does not free $0 */
1660 free(*pp);
1661 free(G.global_argv);
1662 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001663#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001664 argv[0] = sv->sv_argv0;
1665 G.global_argv = sv->sv_g_argv;
1666 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001667 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001668}
1669
1670
Denis Vlasenkod5762932009-03-31 11:22:57 +00001671/* Basic theory of signal handling in shell
1672 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001673 * This does not describe what hush does, rather, it is current understanding
1674 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001675 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1676 *
1677 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1678 * is finished or backgrounded. It is the same in interactive and
1679 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001680 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001681 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001682 * backgrounds (i.e. stops) or kills all members of currently running
1683 * pipe.
1684 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001685 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001686 * or by SIGINT in interactive shell.
1687 *
1688 * Trap handlers will execute even within trap handlers. (right?)
1689 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001690 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1691 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001692 *
1693 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001694 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001695 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001696 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001697 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001698 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001699 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001700 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001701 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001702 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001703 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001704 *
1705 * SIGQUIT: ignore
1706 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001707 * SIGHUP (interactive):
1708 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001709 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001710 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1711 * that all pipe members are stopped. Try this in bash:
1712 * while :; do :; done - ^Z does not background it
1713 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001714 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001715 * of the command line, show prompt. NB: ^C does not send SIGINT
1716 * to interactive shell while shell is waiting for a pipe,
1717 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001718 * Example 1: this waits 5 sec, but does not execute ls:
1719 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1720 * Example 2: this does not wait and does not execute ls:
1721 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1722 * Example 3: this does not wait 5 sec, but executes ls:
1723 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001724 * Example 4: this does not wait and does not execute ls:
1725 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001726 *
1727 * (What happens to signals which are IGN on shell start?)
1728 * (What happens with signal mask on shell start?)
1729 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001730 * Old implementation
1731 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001732 * We use in-kernel pending signal mask to determine which signals were sent.
1733 * We block all signals which we don't want to take action immediately,
1734 * i.e. we block all signals which need to have special handling as described
1735 * above, and all signals which have traps set.
1736 * After each pipe execution, we extract any pending signals via sigtimedwait()
1737 * and act on them.
1738 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001739 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001740 * sigset_t blocked_set: current blocked signal set
1741 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001742 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001743 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001744 * "trap 'cmd' SIGxxx":
1745 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001746 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001747 * unblock signals with special interactive handling
1748 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001749 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001750 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001751 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001752 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001753 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001754 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001755 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001756 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001757 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001758 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001759 * Standard says "When a subshell is entered, traps that are not being ignored
1760 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001761 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001762 *
1763 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001764 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001765 * masked signals are not visible!
1766 *
1767 * New implementation
1768 * ==================
1769 * We record each signal we are interested in by installing signal handler
1770 * for them - a bit like emulating kernel pending signal mask in userspace.
1771 * We are interested in: signals which need to have special handling
1772 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001773 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001774 * After each pipe execution, we extract any pending signals
1775 * and act on them.
1776 *
1777 * unsigned special_sig_mask: a mask of shell-special signals.
1778 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1779 * char *traps[sig] if trap for sig is set (even if it's '').
1780 * sigset_t pending_set: set of sigs we received.
1781 *
1782 * "trap - SIGxxx":
1783 * if sig is in special_sig_mask, set handler back to:
1784 * record_pending_signo, or to IGN if it's a tty stop signal
1785 * if sig is in fatal_sig_mask, set handler back to sigexit.
1786 * else: set handler back to SIG_DFL
1787 * "trap 'cmd' SIGxxx":
1788 * set handler to record_pending_signo.
1789 * "trap '' SIGxxx":
1790 * set handler to SIG_IGN.
1791 * after [v]fork, if we plan to be a shell:
1792 * set signals with special interactive handling to SIG_DFL
1793 * (because child shell is not interactive),
1794 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1795 * after [v]fork, if we plan to exec:
1796 * POSIX says fork clears pending signal mask in child - no need to clear it.
1797 *
1798 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1799 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1800 *
1801 * Note (compat):
1802 * Standard says "When a subshell is entered, traps that are not being ignored
1803 * are set to the default actions". bash interprets it so that traps which
1804 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001805 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001806enum {
1807 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001808 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001809 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001810 | (1 << SIGHUP)
1811 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001812 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001813#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001814 | (1 << SIGTTIN)
1815 | (1 << SIGTTOU)
1816 | (1 << SIGTSTP)
1817#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001818 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001819};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001820
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001821static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001822{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001823 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001824#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001825 if (sig == SIGCHLD) {
1826 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001827//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001828 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001829#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001830}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001831
Denys Vlasenko0806e402011-05-12 23:06:20 +02001832static sighandler_t install_sighandler(int sig, sighandler_t handler)
1833{
1834 struct sigaction old_sa;
1835
1836 /* We could use signal() to install handlers... almost:
1837 * except that we need to mask ALL signals while handlers run.
1838 * I saw signal nesting in strace, race window isn't small.
1839 * SA_RESTART is also needed, but in Linux, signal()
1840 * sets SA_RESTART too.
1841 */
1842 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1843 /* sigfillset(&G.sa.sa_mask); - already done */
1844 /* G.sa.sa_flags = SA_RESTART; - already done */
1845 G.sa.sa_handler = handler;
1846 sigaction(sig, &G.sa, &old_sa);
1847 return old_sa.sa_handler;
1848}
1849
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001850static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001851
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001852static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001853static void restore_ttypgrp_and__exit(void)
1854{
1855 /* xfunc has failed! die die die */
1856 /* no EXIT traps, this is an escape hatch! */
1857 G.exiting = 1;
1858 hush_exit(xfunc_error_retval);
1859}
1860
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001861#if ENABLE_HUSH_JOB
1862
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001863/* Needed only on some libc:
1864 * It was observed that on exit(), fgetc'ed buffered data
1865 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1866 * With the net effect that even after fork(), not vfork(),
1867 * exit() in NOEXECed applet in "sh SCRIPT":
1868 * noexec_applet_here
1869 * echo END_OF_SCRIPT
1870 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1871 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001872 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001873 * and in `cmd` handling.
1874 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1875 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001876static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001877static void fflush_and__exit(void)
1878{
1879 fflush_all();
1880 _exit(xfunc_error_retval);
1881}
1882
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001883/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001884# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001885/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001886# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001887
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001888/* Restores tty foreground process group, and exits.
1889 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001890 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001891 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001892 * We also call it if xfunc is exiting.
1893 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001894static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001895static void sigexit(int sig)
1896{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001897 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001898 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001899 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1900 /* Disable all signals: job control, SIGPIPE, etc.
1901 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1902 */
1903 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001904 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001905 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001906
1907 /* Not a signal, just exit */
1908 if (sig <= 0)
1909 _exit(- sig);
1910
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001911 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001912}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001913#else
1914
Denys Vlasenko8391c482010-05-22 17:50:43 +02001915# define disable_restore_tty_pgrp_on_exit() ((void)0)
1916# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001917
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001918#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001919
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001920static sighandler_t pick_sighandler(unsigned sig)
1921{
1922 sighandler_t handler = SIG_DFL;
1923 if (sig < sizeof(unsigned)*8) {
1924 unsigned sigmask = (1 << sig);
1925
1926#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001927 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001928 if (G_fatal_sig_mask & sigmask)
1929 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001930 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001931#endif
1932 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001933 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001934 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001935 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001936 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001937 * in an endless loop when we try to do some
1938 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001939 */
1940 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1941 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001942 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001943 }
1944 return handler;
1945}
1946
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001947/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001948static void hush_exit(int exitcode)
1949{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001950#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1951 save_history(G.line_input_state);
1952#endif
1953
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001954 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001955 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001956 char *argv[3];
1957 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001958 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001959 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001960 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001961 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001962 * "trap" will still show it, if executed
1963 * in the handler */
1964 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001965 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001966
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001967#if ENABLE_FEATURE_CLEAN_UP
1968 {
1969 struct variable *cur_var;
1970 if (G.cwd != bb_msg_unknown)
1971 free((char*)G.cwd);
1972 cur_var = G.top_var;
1973 while (cur_var) {
1974 struct variable *tmp = cur_var;
1975 if (!cur_var->max_len)
1976 free(cur_var->varstr);
1977 cur_var = cur_var->next;
1978 free(tmp);
1979 }
1980 }
1981#endif
1982
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001983 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001984#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001985 sigexit(- (exitcode & 0xff));
1986#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001987 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001988#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001989}
1990
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001991
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001992//TODO: return a mask of ALL handled sigs?
1993static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001994{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001995 int last_sig = 0;
1996
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001997 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001998 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001999
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002000 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002001 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002002 sig = 0;
2003 do {
2004 sig++;
2005 if (sigismember(&G.pending_set, sig)) {
2006 sigdelset(&G.pending_set, sig);
2007 goto got_sig;
2008 }
2009 } while (sig < NSIG);
2010 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002011 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002012 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002013 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002014 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002015 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002016 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002017 char *argv[3];
2018 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002019 argv[1] = xstrdup(G_traps[sig]);
2020 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002021 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002022 save_rcode = G.last_exitcode;
2023 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002024 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002025//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002026 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002027 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002028 } /* else: "" trap, ignoring signal */
2029 continue;
2030 }
2031 /* not a trap: special action */
2032 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002033 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002034 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002035 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002036 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002037 break;
2038#if ENABLE_HUSH_JOB
2039 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002040//TODO: why are we doing this? ash and dash don't do this,
2041//they have no handler for SIGHUP at all,
2042//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002043 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002044 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002045 /* bash is observed to signal whole process groups,
2046 * not individual processes */
2047 for (job = G.job_list; job; job = job->next) {
2048 if (job->pgrp <= 0)
2049 continue;
2050 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2051 if (kill(- job->pgrp, SIGHUP) == 0)
2052 kill(- job->pgrp, SIGCONT);
2053 }
2054 sigexit(SIGHUP);
2055 }
2056#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002057#if ENABLE_HUSH_FAST
2058 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002059 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002060 G.count_SIGCHLD++;
2061//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2062 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002063 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002064 * This simplifies wait builtin a bit.
2065 */
2066 break;
2067#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002068 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002069 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002070 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002071 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002072 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002073 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002074 * in interactive shell, because TERM is ignored.
2075 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002076 break;
2077 }
2078 }
2079 return last_sig;
2080}
2081
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002082
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002083static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002084{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002085 if (force || G.cwd == NULL) {
2086 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2087 * we must not try to free(bb_msg_unknown) */
2088 if (G.cwd == bb_msg_unknown)
2089 G.cwd = NULL;
2090 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2091 if (!G.cwd)
2092 G.cwd = bb_msg_unknown;
2093 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002094 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002095}
2096
Denis Vlasenko83506862007-11-23 13:11:42 +00002097
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002098/*
2099 * Shell and environment variable support
2100 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002101static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002102{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002103 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002105
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002106 pp = &G.top_var;
2107 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002109 return pp;
2110 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002111 }
2112 return NULL;
2113}
2114
Denys Vlasenko03dad222010-01-12 23:29:57 +01002115static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002116{
Denys Vlasenko29082232010-07-16 13:52:32 +02002117 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002118 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002119
2120 if (G.expanded_assignments) {
2121 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002122 while (*cpp) {
2123 char *cp = *cpp;
2124 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2125 return cp + len + 1;
2126 cpp++;
2127 }
2128 }
2129
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002130 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002131 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002132 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002133
Denys Vlasenkodea47882009-10-09 15:40:49 +02002134 if (strcmp(name, "PPID") == 0)
2135 return utoa(G.root_ppid);
2136 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002137#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002138 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002139 return utoa(next_random(&G.random_gen));
2140#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141 return NULL;
2142}
2143
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002144static void handle_changed_special_names(const char *name, unsigned name_len)
2145{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002146 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2147 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2148 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002149 cmdedit_update_prompt();
2150 return;
2151 }
2152
2153 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2154 && name_len == 6
2155 ) {
2156#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002157 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002158 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002159 return;
2160 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002161#endif
2162#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002163 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002164 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002165 return;
2166 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002167#endif
2168 }
2169}
2170
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002171/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002172 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002173 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002174#define SETFLAG_EXPORT (1 << 0)
2175#define SETFLAG_UNEXPORT (1 << 1)
2176#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002177#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002178static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002179{
Denys Vlasenko61407802018-04-04 21:14:28 +02002180 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002181 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002182 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002183 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002184 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002185 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002186
Denis Vlasenko950bd722009-04-21 11:23:56 +00002187 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002188 if (HUSH_DEBUG && !eq_sign)
2189 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002190
Denis Vlasenko950bd722009-04-21 11:23:56 +00002191 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002192 cur_pp = &G.top_var;
2193 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002194 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002195 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002196 continue;
2197 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002198
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002200 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002201 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002203//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2204//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205 return -1;
2206 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002207 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002208 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2209 *eq_sign = '\0';
2210 unsetenv(str);
2211 *eq_sign = '=';
2212 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002213 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002214 /* bash 3.2.33(1) and exported vars:
2215 * # export z=z
2216 * # f() { local z=a; env | grep ^z; }
2217 * # f
2218 * z=a
2219 * # env | grep ^z
2220 * z=z
2221 */
2222 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002223 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002224 /* New variable is local ("local VAR=VAL" or
2225 * "VAR=VAL cmd")
2226 * and existing one is global, or local
2227 * on a lower level that new one.
2228 * Remove it from global variable list:
2229 */
2230 *cur_pp = cur->next;
2231 if (G.shadowed_vars_pp) {
2232 /* Save in "shadowed" list */
2233 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2234 cur->flg_export ? "exported " : "",
2235 cur->varstr, cur->var_nest_level, str, local_lvl
2236 );
2237 cur->next = *G.shadowed_vars_pp;
2238 *G.shadowed_vars_pp = cur;
2239 } else {
2240 /* Came from pseudo_exec_argv(), no need to save: delete it */
2241 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2242 cur->flg_export ? "exported " : "",
2243 cur->varstr, cur->var_nest_level, str, local_lvl
2244 );
2245 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2246 free_me = cur->varstr; /* then free it later */
2247 free(cur);
2248 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002249 break;
2250 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002251
Denis Vlasenko950bd722009-04-21 11:23:56 +00002252 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002253 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002254 free_and_exp:
2255 free(str);
2256 goto exp;
2257 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002258
2259 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002260 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002261 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002262 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002263 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002264 strcpy(cur->varstr, str);
2265 goto free_and_exp;
2266 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002267 /* Can't reuse */
2268 cur->max_len = 0;
2269 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002270 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002271 /* max_len == 0 signifies "malloced" var, which we can
2272 * (and have to) free. But we can't free(cur->varstr) here:
2273 * if cur->flg_export is 1, it is in the environment.
2274 * We should either unsetenv+free, or wait until putenv,
2275 * then putenv(new)+free(old).
2276 */
2277 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002278 goto set_str_and_exp;
2279 }
2280
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002281 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002282 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002283 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002284 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002285 cur->next = *cur_pp;
2286 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002287
2288 set_str_and_exp:
2289 cur->varstr = str;
2290 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002291#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002292 if (flags & SETFLAG_MAKE_RO) {
2293 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002294 }
2295#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002296 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002297 cur->flg_export = 1;
2298 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002299 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002300 cur->flg_export = 0;
2301 /* unsetenv was already done */
2302 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002303 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002304 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002305 i = putenv(cur->varstr);
2306 /* only now we can free old exported malloced string */
2307 free(free_me);
2308 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002309 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002311 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002312
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002313 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002314
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 return 0;
2316}
2317
Denys Vlasenko6db47842009-09-05 20:15:17 +02002318/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002319static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002320{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002321 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002322}
2323
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002324static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002325{
2326 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002327 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328
Denys Vlasenko61407802018-04-04 21:14:28 +02002329 cur_pp = &G.top_var;
2330 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002331 if (strncmp(cur->varstr, name, name_len) == 0
2332 && cur->varstr[name_len] == '='
2333 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002334 if (cur->flg_read_only) {
2335 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002336 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002337 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002338
Denys Vlasenko61407802018-04-04 21:14:28 +02002339 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002340 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2341 bb_unsetenv(cur->varstr);
2342 if (!cur->max_len)
2343 free(cur->varstr);
2344 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002345
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002346 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002347 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002348 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002349 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002350
2351 /* Handle "unset PS1" et al even if did not find the variable to unset */
2352 handle_changed_special_names(name, name_len);
2353
Mike Frysingerd690f682009-03-30 06:50:54 +00002354 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002355}
2356
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002357#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002358static int unset_local_var(const char *name)
2359{
2360 return unset_local_var_len(name, strlen(name));
2361}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002362#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002363
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002364#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002365static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002366{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002367 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002368 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002369}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002370#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002371
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002372
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002373/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002374 * Helpers for "var1=val1 var2=val2 cmd" feature
2375 */
2376static void add_vars(struct variable *var)
2377{
2378 struct variable *next;
2379
2380 while (var) {
2381 next = var->next;
2382 var->next = G.top_var;
2383 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002384 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002385 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002386 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002387 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002388 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002389 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002390 var = next;
2391 }
2392}
2393
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002394/* We put strings[i] into variable table and possibly putenv them.
2395 * If variable is read only, we can free the strings[i]
2396 * which attempts to overwrite it.
2397 * The strings[] vector itself is freed.
2398 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002399static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002400{
2401 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002402
2403 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002404 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002405
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002406 s = strings;
2407 while (*s) {
2408 struct variable *var_p;
2409 struct variable **var_pp;
2410 char *eq;
2411
2412 eq = strchr(*s, '=');
2413 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002414 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002415 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002416 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002417 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002418 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002419 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002420 /*
2421 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2422 * If VAR is readonly, leaving it in the list
2423 * after asssignment error (msg above)
2424 * causes doubled error message later, on unset.
2425 */
2426 debug_printf_env("removing/freeing '%s' element\n", *s);
2427 free(*s);
2428 p = s;
2429 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002430 goto next;
2431 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002432 /* below, set_local_var() with nest level will
2433 * "shadow" (remove) this variable from
2434 * global linked list.
2435 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002436 }
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002437 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002438 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2439 } else if (HUSH_DEBUG) {
2440 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002441 }
2442 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002443 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002444 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002445 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002446}
2447
2448
2449/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002450 * Unicode helper
2451 */
2452static void reinit_unicode_for_hush(void)
2453{
2454 /* Unicode support should be activated even if LANG is set
2455 * _during_ shell execution, not only if it was set when
2456 * shell was started. Therefore, re-check LANG every time:
2457 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002458 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2459 || ENABLE_UNICODE_USING_LOCALE
2460 ) {
2461 const char *s = get_local_var_value("LC_ALL");
2462 if (!s) s = get_local_var_value("LC_CTYPE");
2463 if (!s) s = get_local_var_value("LANG");
2464 reinit_unicode(s);
2465 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002466}
2467
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002468/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002469 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002470 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002471
2472#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002473/* To test correct lineedit/interactive behavior, type from command line:
2474 * echo $P\
2475 * \
2476 * AT\
2477 * H\
2478 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002479 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002480 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002481# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002482static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002484 G.PS1 = get_local_var_value("PS1");
2485 if (G.PS1 == NULL)
2486 G.PS1 = "";
2487 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002488 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002489 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002490}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002491# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002492static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002493{
2494 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002495
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002496 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002497
2498 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2499 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002500 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002501 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2502 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002503 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002504 /* bash uses $PWD value, even if it is set by user.
2505 * It uses current dir only if PWD is unset.
2506 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002507 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002508 }
2509 prompt_str = G.PS1;
2510 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002511 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002512 return prompt_str;
2513}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002514static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002515{
2516 int r;
2517 const char *prompt_str;
2518
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002519 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002520# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002521 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002522 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002523 if (G.flag_SIGINT) {
2524 /* There was ^C'ed, make it look prettier: */
2525 bb_putchar('\n');
2526 G.flag_SIGINT = 0;
2527 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002528 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002529 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002530 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002531 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002532 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002533 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002534 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002535 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002536 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002537 if (r != 0 && !G.flag_SIGINT)
2538 break;
2539 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002540 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2541 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002542 G.last_exitcode = 128 + SIGINT;
2543 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002544 if (r < 0) {
2545 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002546 i->p = NULL;
2547 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002548 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002549 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002550 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002551 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002552# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002553 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002554 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002555 if (i->last_char == '\0' || i->last_char == '\n') {
2556 /* Why check_and_run_traps here? Try this interactively:
2557 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2558 * $ <[enter], repeatedly...>
2559 * Without check_and_run_traps, handler never runs.
2560 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002561 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002562 fputs(prompt_str, stdout);
2563 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002564 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002565//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002566 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002567 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2568 * no ^C masking happens during fgetc, no special code for ^C:
2569 * it generates SIGINT as usual.
2570 */
2571 check_and_run_traps();
2572 if (G.flag_SIGINT)
2573 G.last_exitcode = 128 + SIGINT;
2574 if (r != '\0')
2575 break;
2576 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002577 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002578# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002579}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580/* This is the magic location that prints prompts
2581 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002582static int fgetc_interactive(struct in_str *i)
2583{
2584 int ch;
2585 /* If it's interactive stdin, get new line. */
2586 if (G_interactive_fd && i->file == stdin) {
2587 /* Returns first char (or EOF), the rest is in i->p[] */
2588 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002589 G.promptmode = 1; /* PS2 */
2590 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002591 } else {
2592 /* Not stdin: script file, sourced file, etc */
2593 do ch = fgetc(i->file); while (ch == '\0');
2594 }
2595 return ch;
2596}
2597#else
2598static inline int fgetc_interactive(struct in_str *i)
2599{
2600 int ch;
2601 do ch = fgetc(i->file); while (ch == '\0');
2602 return ch;
2603}
2604#endif /* INTERACTIVE */
2605
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002606static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607{
2608 int ch;
2609
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002610 if (!i->file) {
2611 /* string-based in_str */
2612 ch = (unsigned char)*i->p;
2613 if (ch != '\0') {
2614 i->p++;
2615 i->last_char = ch;
2616 return ch;
2617 }
2618 return EOF;
2619 }
2620
2621 /* FILE-based in_str */
2622
Denys Vlasenko4074d492016-09-30 01:49:53 +02002623#if ENABLE_FEATURE_EDITING
2624 /* This can be stdin, check line editing char[] buffer */
2625 if (i->p && *i->p != '\0') {
2626 ch = (unsigned char)*i->p++;
2627 goto out;
2628 }
2629#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002630 /* peek_buf[] is an int array, not char. Can contain EOF. */
2631 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002632 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002633 int ch2 = i->peek_buf[1];
2634 i->peek_buf[0] = ch2;
2635 if (ch2 == 0) /* very likely, avoid redundant write */
2636 goto out;
2637 i->peek_buf[1] = 0;
2638 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002640
Denys Vlasenko4074d492016-09-30 01:49:53 +02002641 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002642 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002643 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002644 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002645#if ENABLE_HUSH_LINENO_VAR
2646 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002647 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002648 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2649 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002650#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002651 return ch;
2652}
2653
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002654static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002655{
2656 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002657
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002658 if (!i->file) {
2659 /* string-based in_str */
2660 /* Doesn't report EOF on NUL. None of the callers care. */
2661 return (unsigned char)*i->p;
2662 }
2663
2664 /* FILE-based in_str */
2665
Denys Vlasenko4074d492016-09-30 01:49:53 +02002666#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002667 /* This can be stdin, check line editing char[] buffer */
2668 if (i->p && *i->p != '\0')
2669 return (unsigned char)*i->p;
2670#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002671 /* peek_buf[] is an int array, not char. Can contain EOF. */
2672 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002673 if (ch != 0)
2674 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002675
Denys Vlasenko4074d492016-09-30 01:49:53 +02002676 /* Need to get a new char */
2677 ch = fgetc_interactive(i);
2678 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2679
2680 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2681#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2682 if (i->p) {
2683 i->p -= 1;
2684 return ch;
2685 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002686#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002687 i->peek_buf[0] = ch;
2688 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002689 return ch;
2690}
2691
Denys Vlasenko4074d492016-09-30 01:49:53 +02002692/* Only ever called if i_peek() was called, and did not return EOF.
2693 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2694 * not end-of-line. Therefore we never need to read a new editing line here.
2695 */
2696static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002697{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002698 int ch;
2699
2700 /* There are two cases when i->p[] buffer exists.
2701 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002702 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002703 * In both cases, we know that i->p[0] exists and not NUL, and
2704 * the peek2 result is in i->p[1].
2705 */
2706 if (i->p)
2707 return (unsigned char)i->p[1];
2708
2709 /* Now we know it is a file-based in_str. */
2710
2711 /* peek_buf[] is an int array, not char. Can contain EOF. */
2712 /* Is there 2nd char? */
2713 ch = i->peek_buf[1];
2714 if (ch == 0) {
2715 /* We did not read it yet, get it now */
2716 do ch = fgetc(i->file); while (ch == '\0');
2717 i->peek_buf[1] = ch;
2718 }
2719
2720 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2721 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002722}
2723
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002724static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2725{
2726 for (;;) {
2727 int ch, ch2;
2728
2729 ch = i_getch(input);
2730 if (ch != '\\')
2731 return ch;
2732 ch2 = i_peek(input);
2733 if (ch2 != '\n')
2734 return ch;
2735 /* backslash+newline, skip it */
2736 i_getch(input);
2737 }
2738}
2739
2740/* Note: this function _eats_ \<newline> pairs, safe to use plain
2741 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2742 */
2743static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2744{
2745 for (;;) {
2746 int ch, ch2;
2747
2748 ch = i_peek(input);
2749 if (ch != '\\')
2750 return ch;
2751 ch2 = i_peek2(input);
2752 if (ch2 != '\n')
2753 return ch;
2754 /* backslash+newline, skip it */
2755 i_getch(input);
2756 i_getch(input);
2757 }
2758}
2759
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002760static void setup_file_in_str(struct in_str *i, FILE *f)
2761{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002762 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002763 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002764 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002765}
2766
2767static void setup_string_in_str(struct in_str *i, const char *s)
2768{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002769 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002770 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002771 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772}
2773
2774
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002775/*
2776 * o_string support
2777 */
2778#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002779
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002780static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002781{
2782 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002783 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002784 if (o->data)
2785 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002786}
2787
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002788static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002789{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002790 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002791 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002792}
2793
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002794static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2795{
2796 free(o->data);
2797}
2798
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002799static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002800{
2801 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002802 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002803 o->data = xrealloc(o->data, 1 + o->maxlen);
2804 }
2805}
2806
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002807static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002808{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002809 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002810 if (o->length < o->maxlen) {
2811 /* likely. avoid o_grow_by() call */
2812 add:
2813 o->data[o->length] = ch;
2814 o->length++;
2815 o->data[o->length] = '\0';
2816 return;
2817 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002818 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002819 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002820}
2821
Denys Vlasenko657086a2016-09-29 18:07:42 +02002822#if 0
2823/* Valid only if we know o_string is not empty */
2824static void o_delchr(o_string *o)
2825{
2826 o->length--;
2827 o->data[o->length] = '\0';
2828}
2829#endif
2830
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002831static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002832{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002833 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002834 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002835 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002836}
2837
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002838static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002839{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002840 o_addblock(o, str, strlen(str));
2841}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002842
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002843#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002844static void nommu_addchr(o_string *o, int ch)
2845{
2846 if (o)
2847 o_addchr(o, ch);
2848}
2849#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002850# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002851#endif
2852
2853static void o_addstr_with_NUL(o_string *o, const char *str)
2854{
2855 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002856}
2857
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002858/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002859 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002860 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2861 * Apparently, on unquoted $v bash still does globbing
2862 * ("v='*.txt'; echo $v" prints all .txt files),
2863 * but NOT brace expansion! Thus, there should be TWO independent
2864 * quoting mechanisms on $v expansion side: one protects
2865 * $v from brace expansion, and other additionally protects "$v" against globbing.
2866 * We have only second one.
2867 */
2868
Denys Vlasenko9e800222010-10-03 14:28:04 +02002869#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002870# define MAYBE_BRACES "{}"
2871#else
2872# define MAYBE_BRACES ""
2873#endif
2874
Eric Andersen25f27032001-04-26 23:22:31 +00002875/* My analysis of quoting semantics tells me that state information
2876 * is associated with a destination, not a source.
2877 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002878static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002879{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002880 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002881 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002882 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002883 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002884 o_grow_by(o, sz);
2885 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002886 o->data[o->length] = '\\';
2887 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002888 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002889 o->data[o->length] = ch;
2890 o->length++;
2891 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002892}
2893
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002894static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002895{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002896 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002897 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2898 && strchr("*?[\\" MAYBE_BRACES, ch)
2899 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002900 sz++;
2901 o->data[o->length] = '\\';
2902 o->length++;
2903 }
2904 o_grow_by(o, sz);
2905 o->data[o->length] = ch;
2906 o->length++;
2907 o->data[o->length] = '\0';
2908}
2909
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002910static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002911{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002912 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 char ch;
2914 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002915 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002916 if (ordinary_cnt > len) /* paranoia */
2917 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002918 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002919 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002920 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002921 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002922 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002923
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002924 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002925 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002926 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002927 sz++;
2928 o->data[o->length] = '\\';
2929 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002930 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002931 o_grow_by(o, sz);
2932 o->data[o->length] = ch;
2933 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002934 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002935 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002936}
2937
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002938static void o_addQblock(o_string *o, const char *str, int len)
2939{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002940 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002941 o_addblock(o, str, len);
2942 return;
2943 }
2944 o_addqblock(o, str, len);
2945}
2946
Denys Vlasenko38292b62010-09-05 14:49:40 +02002947static void o_addQstr(o_string *o, const char *str)
2948{
2949 o_addQblock(o, str, strlen(str));
2950}
2951
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002952/* A special kind of o_string for $VAR and `cmd` expansion.
2953 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002954 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002955 * list[i] contains an INDEX (int!) into this string data.
2956 * It means that if list[] needs to grow, data needs to be moved higher up
2957 * but list[i]'s need not be modified.
2958 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002959 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002960 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2961 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002962#if DEBUG_EXPAND || DEBUG_GLOB
2963static void debug_print_list(const char *prefix, o_string *o, int n)
2964{
2965 char **list = (char**)o->data;
2966 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2967 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002968
2969 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002970 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002971 prefix, list, n, string_start, o->length, o->maxlen,
2972 !!(o->o_expflags & EXP_FLAG_GLOB),
2973 o->has_quoted_part,
2974 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002975 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002976 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002977 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2978 o->data + (int)(uintptr_t)list[i] + string_start,
2979 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002980 i++;
2981 }
2982 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002983 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002984 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002985 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002986 }
2987}
2988#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002989# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002990#endif
2991
2992/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2993 * in list[n] so that it points past last stored byte so far.
2994 * It returns n+1. */
2995static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002996{
2997 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002998 int string_start;
2999 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003000
3001 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003002 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3003 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003004 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003005 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003006 /* list[n] points to string_start, make space for 16 more pointers */
3007 o->maxlen += 0x10 * sizeof(list[0]);
3008 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003009 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003010 memmove(list + n + 0x10, list + n, string_len);
3011 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003012 } else {
3013 debug_printf_list("list[%d]=%d string_start=%d\n",
3014 n, string_len, string_start);
3015 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003016 } else {
3017 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003018 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3019 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003020 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3021 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003022 o->has_empty_slot = 0;
3023 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003024 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003025 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003026 return n + 1;
3027}
3028
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003029/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003030static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003031{
3032 char **list = (char**)o->data;
3033 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3034
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003035 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003036}
3037
Denys Vlasenko9e800222010-10-03 14:28:04 +02003038#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003039/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3040 * first, it processes even {a} (no commas), second,
3041 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003042 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003043 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003044
3045/* Helper */
3046static int glob_needed(const char *s)
3047{
3048 while (*s) {
3049 if (*s == '\\') {
3050 if (!s[1])
3051 return 0;
3052 s += 2;
3053 continue;
3054 }
3055 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3056 return 1;
3057 s++;
3058 }
3059 return 0;
3060}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003061/* Return pointer to next closing brace or to comma */
3062static const char *next_brace_sub(const char *cp)
3063{
3064 unsigned depth = 0;
3065 cp++;
3066 while (*cp != '\0') {
3067 if (*cp == '\\') {
3068 if (*++cp == '\0')
3069 break;
3070 cp++;
3071 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003072 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003073 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003074 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003075 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003076 depth++;
3077 }
3078
3079 return *cp != '\0' ? cp : NULL;
3080}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003081/* Recursive brace globber. Note: may garble pattern[]. */
3082static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003083{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003084 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003085 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003086 const char *next;
3087 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003088 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003089 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003090
3091 debug_printf_glob("glob_brace('%s')\n", pattern);
3092
3093 begin = pattern;
3094 while (1) {
3095 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003096 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003097 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003098 /* Find the first sub-pattern and at the same time
3099 * find the rest after the closing brace */
3100 next = next_brace_sub(begin);
3101 if (next == NULL) {
3102 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003103 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003104 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003105 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003106 /* "{abc}" with no commas - illegal
3107 * brace expr, disregard and skip it */
3108 begin = next + 1;
3109 continue;
3110 }
3111 break;
3112 }
3113 if (*begin == '\\' && begin[1] != '\0')
3114 begin++;
3115 begin++;
3116 }
3117 debug_printf_glob("begin:%s\n", begin);
3118 debug_printf_glob("next:%s\n", next);
3119
3120 /* Now find the end of the whole brace expression */
3121 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003122 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003123 rest = next_brace_sub(rest);
3124 if (rest == NULL) {
3125 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003126 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003127 }
3128 debug_printf_glob("rest:%s\n", rest);
3129 }
3130 rest_len = strlen(++rest) + 1;
3131
3132 /* We are sure the brace expression is well-formed */
3133
3134 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003135 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003136
3137 /* We have a brace expression. BEGIN points to the opening {,
3138 * NEXT points past the terminator of the first element, and REST
3139 * points past the final }. We will accumulate result names from
3140 * recursive runs for each brace alternative in the buffer using
3141 * GLOB_APPEND. */
3142
3143 p = begin + 1;
3144 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003145 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003146 memcpy(
3147 mempcpy(
3148 mempcpy(new_pattern_buf,
3149 /* We know the prefix for all sub-patterns */
3150 pattern, begin - pattern),
3151 p, next - p),
3152 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003153
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003154 /* Note: glob_brace() may garble new_pattern_buf[].
3155 * That's why we re-copy prefix every time (1st memcpy above).
3156 */
3157 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003158 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003159 /* We saw the last entry */
3160 break;
3161 }
3162 p = next + 1;
3163 next = next_brace_sub(next);
3164 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003165 free(new_pattern_buf);
3166 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003167
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003168 simple_glob:
3169 {
3170 int gr;
3171 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003172
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003173 memset(&globdata, 0, sizeof(globdata));
3174 gr = glob(pattern, 0, NULL, &globdata);
3175 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3176 if (gr != 0) {
3177 if (gr == GLOB_NOMATCH) {
3178 globfree(&globdata);
3179 /* NB: garbles parameter */
3180 unbackslash(pattern);
3181 o_addstr_with_NUL(o, pattern);
3182 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3183 return o_save_ptr_helper(o, n);
3184 }
3185 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003186 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003187 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3188 * but we didn't specify it. Paranoia again. */
3189 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3190 }
3191 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3192 char **argv = globdata.gl_pathv;
3193 while (1) {
3194 o_addstr_with_NUL(o, *argv);
3195 n = o_save_ptr_helper(o, n);
3196 argv++;
3197 if (!*argv)
3198 break;
3199 }
3200 }
3201 globfree(&globdata);
3202 }
3203 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003204}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003205/* Performs globbing on last list[],
3206 * saving each result as a new list[].
3207 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003208static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003209{
3210 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003211
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003212 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003213 if (!o->data)
3214 return o_save_ptr_helper(o, n);
3215 pattern = o->data + o_get_last_ptr(o, n);
3216 debug_printf_glob("glob pattern '%s'\n", pattern);
3217 if (!glob_needed(pattern)) {
3218 /* unbackslash last string in o in place, fix length */
3219 o->length = unbackslash(pattern) - o->data;
3220 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3221 return o_save_ptr_helper(o, n);
3222 }
3223
3224 copy = xstrdup(pattern);
3225 /* "forget" pattern in o */
3226 o->length = pattern - o->data;
3227 n = glob_brace(copy, o, n);
3228 free(copy);
3229 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003230 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003231 return n;
3232}
3233
Denys Vlasenko238081f2010-10-03 14:26:26 +02003234#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003235
3236/* Helper */
3237static int glob_needed(const char *s)
3238{
3239 while (*s) {
3240 if (*s == '\\') {
3241 if (!s[1])
3242 return 0;
3243 s += 2;
3244 continue;
3245 }
3246 if (*s == '*' || *s == '[' || *s == '?')
3247 return 1;
3248 s++;
3249 }
3250 return 0;
3251}
3252/* Performs globbing on last list[],
3253 * saving each result as a new list[].
3254 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003255static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003256{
3257 glob_t globdata;
3258 int gr;
3259 char *pattern;
3260
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003261 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003262 if (!o->data)
3263 return o_save_ptr_helper(o, n);
3264 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003265 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003266 if (!glob_needed(pattern)) {
3267 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003268 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003269 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003270 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003271 return o_save_ptr_helper(o, n);
3272 }
3273
3274 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003275 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3276 * If we glob "*.\*" and don't find anything, we need
3277 * to fall back to using literal "*.*", but GLOB_NOCHECK
3278 * will return "*.\*"!
3279 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003280 gr = glob(pattern, 0, NULL, &globdata);
3281 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003282 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003283 if (gr == GLOB_NOMATCH) {
3284 globfree(&globdata);
3285 goto literal;
3286 }
3287 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003288 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003289 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3290 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003291 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003292 }
3293 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3294 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003295 /* "forget" pattern in o */
3296 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003297 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003298 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003299 n = o_save_ptr_helper(o, n);
3300 argv++;
3301 if (!*argv)
3302 break;
3303 }
3304 }
3305 globfree(&globdata);
3306 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003307 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003308 return n;
3309}
3310
Denys Vlasenko238081f2010-10-03 14:26:26 +02003311#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003312
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003313/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003314 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003315static int o_save_ptr(o_string *o, int n)
3316{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003317 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003318 /* If o->has_empty_slot, list[n] was already globbed
3319 * (if it was requested back then when it was filled)
3320 * so don't do that again! */
3321 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003322 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003323 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003324 return o_save_ptr_helper(o, n);
3325}
3326
3327/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003328static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003329{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003330 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003331 int string_start;
3332
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003333 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3334 if (DEBUG_EXPAND)
3335 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003336 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003337 list = (char**)o->data;
3338 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3339 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003340 while (n) {
3341 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003342 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003343 }
3344 return list;
3345}
3346
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003347static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003348
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003349/* Returns pi->next - next pipe in the list */
3350static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003351{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003352 struct pipe *next;
3353 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003354
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003355 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003356 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003357 struct command *command;
3358 struct redir_struct *r, *rnext;
3359
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003360 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003361 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003362 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363 if (DEBUG_CLEAN) {
3364 int a;
3365 char **p;
3366 for (a = 0, p = command->argv; *p; a++, p++) {
3367 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3368 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003369 }
3370 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003371 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003372 }
3373 /* not "else if": on syntax error, we may have both! */
3374 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003375 debug_printf_clean(" begin group (cmd_type:%d)\n",
3376 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003377 free_pipe_list(command->group);
3378 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003379 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003381 /* else is crucial here.
3382 * If group != NULL, child_func is meaningless */
3383#if ENABLE_HUSH_FUNCTIONS
3384 else if (command->child_func) {
3385 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3386 command->child_func->parent_cmd = NULL;
3387 }
3388#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003389#if !BB_MMU
3390 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003391 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003392#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003393 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003394 debug_printf_clean(" redirect %d%s",
3395 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003396 /* guard against the case >$FOO, where foo is unset or blank */
3397 if (r->rd_filename) {
3398 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3399 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003400 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003401 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003402 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003403 rnext = r->next;
3404 free(r);
3405 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003406 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003407 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003408 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003409 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003410#if ENABLE_HUSH_JOB
3411 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003412 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003413#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003414
3415 next = pi->next;
3416 free(pi);
3417 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003418}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003419
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003420static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003421{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003422 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003423#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003424 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003425#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003426 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003427 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003428 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003429}
3430
3431
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003432/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003433
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003434#ifndef debug_print_tree
3435static void debug_print_tree(struct pipe *pi, int lvl)
3436{
3437 static const char *const PIPE[] = {
3438 [PIPE_SEQ] = "SEQ",
3439 [PIPE_AND] = "AND",
3440 [PIPE_OR ] = "OR" ,
3441 [PIPE_BG ] = "BG" ,
3442 };
3443 static const char *RES[] = {
3444 [RES_NONE ] = "NONE" ,
3445# if ENABLE_HUSH_IF
3446 [RES_IF ] = "IF" ,
3447 [RES_THEN ] = "THEN" ,
3448 [RES_ELIF ] = "ELIF" ,
3449 [RES_ELSE ] = "ELSE" ,
3450 [RES_FI ] = "FI" ,
3451# endif
3452# if ENABLE_HUSH_LOOPS
3453 [RES_FOR ] = "FOR" ,
3454 [RES_WHILE] = "WHILE",
3455 [RES_UNTIL] = "UNTIL",
3456 [RES_DO ] = "DO" ,
3457 [RES_DONE ] = "DONE" ,
3458# endif
3459# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3460 [RES_IN ] = "IN" ,
3461# endif
3462# if ENABLE_HUSH_CASE
3463 [RES_CASE ] = "CASE" ,
3464 [RES_CASE_IN ] = "CASE_IN" ,
3465 [RES_MATCH] = "MATCH",
3466 [RES_CASE_BODY] = "CASE_BODY",
3467 [RES_ESAC ] = "ESAC" ,
3468# endif
3469 [RES_XXXX ] = "XXXX" ,
3470 [RES_SNTX ] = "SNTX" ,
3471 };
3472 static const char *const CMDTYPE[] = {
3473 "{}",
3474 "()",
3475 "[noglob]",
3476# if ENABLE_HUSH_FUNCTIONS
3477 "func()",
3478# endif
3479 };
3480
3481 int pin, prn;
3482
3483 pin = 0;
3484 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003485 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3486 lvl*2, "",
3487 pin,
3488 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3489 RES[pi->res_word],
3490 pi->followup, PIPE[pi->followup]
3491 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003492 prn = 0;
3493 while (prn < pi->num_cmds) {
3494 struct command *command = &pi->cmds[prn];
3495 char **argv = command->argv;
3496
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003497 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003498 lvl*2, "", prn,
3499 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003500#if ENABLE_HUSH_LINENO_VAR
3501 fdprintf(2, " LINENO:%u", command->lineno);
3502#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003503 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003504 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003505 CMDTYPE[command->cmd_type],
3506 argv
3507# if !BB_MMU
3508 , " group_as_string:", command->group_as_string
3509# else
3510 , "", ""
3511# endif
3512 );
3513 debug_print_tree(command->group, lvl+1);
3514 prn++;
3515 continue;
3516 }
3517 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003518 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003519 argv++;
3520 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003521 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003522 prn++;
3523 }
3524 pi = pi->next;
3525 pin++;
3526 }
3527}
3528#endif /* debug_print_tree */
3529
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003530static struct pipe *new_pipe(void)
3531{
Eric Andersen25f27032001-04-26 23:22:31 +00003532 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003533 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003534 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003535 return pi;
3536}
3537
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003538/* Command (member of a pipe) is complete, or we start a new pipe
3539 * if ctx->command is NULL.
3540 * No errors possible here.
3541 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003542static int done_command(struct parse_context *ctx)
3543{
3544 /* The command is really already in the pipe structure, so
3545 * advance the pipe counter and make a new, null command. */
3546 struct pipe *pi = ctx->pipe;
3547 struct command *command = ctx->command;
3548
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003549#if 0 /* Instead we emit error message at run time */
3550 if (ctx->pending_redirect) {
3551 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003552 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003553 ctx->pending_redirect = NULL;
3554 }
3555#endif
3556
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003557 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003558 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003559 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003560 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003561 }
3562 pi->num_cmds++;
3563 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003564 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003565 } else {
3566 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3567 }
3568
3569 /* Only real trickiness here is that the uncommitted
3570 * command structure is not counted in pi->num_cmds. */
3571 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003572 ctx->command = command = &pi->cmds[pi->num_cmds];
3573 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003574 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003575#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003576 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003577 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003578#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003579 return pi->num_cmds; /* used only for 0/nonzero check */
3580}
3581
3582static void done_pipe(struct parse_context *ctx, pipe_style type)
3583{
3584 int not_null;
3585
3586 debug_printf_parse("done_pipe entered, followup %d\n", type);
3587 /* Close previous command */
3588 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003589#if HAS_KEYWORDS
3590 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3591 ctx->ctx_inverted = 0;
3592 ctx->pipe->res_word = ctx->ctx_res_w;
3593#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003594 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3595 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003596 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3597 * in a backgrounded subshell.
3598 */
3599 struct pipe *pi;
3600 struct command *command;
3601
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003602 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003603 pi = ctx->list_head;
3604 while (pi != ctx->pipe) {
3605 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3606 goto no_conv;
3607 pi = pi->next;
3608 }
3609
3610 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3611 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3612 pi = xzalloc(sizeof(*pi));
3613 pi->followup = PIPE_BG;
3614 pi->num_cmds = 1;
3615 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3616 command = &pi->cmds[0];
3617 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3618 command->cmd_type = CMD_NORMAL;
3619 command->group = ctx->list_head;
3620#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003621 command->group_as_string = xstrndup(
3622 ctx->as_string.data,
3623 ctx->as_string.length - 1 /* do not copy last char, "&" */
3624 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003625#endif
3626 /* Replace all pipes in ctx with one newly created */
3627 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003628 } else {
3629 no_conv:
3630 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003631 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003632
3633 /* Without this check, even just <enter> on command line generates
3634 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003635 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003636 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003637#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003638 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003639#endif
3640#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003641 || ctx->ctx_res_w == RES_DONE
3642 || ctx->ctx_res_w == RES_FOR
3643 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003644#endif
3645#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003646 || ctx->ctx_res_w == RES_ESAC
3647#endif
3648 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003649 struct pipe *new_p;
3650 debug_printf_parse("done_pipe: adding new pipe: "
3651 "not_null:%d ctx->ctx_res_w:%d\n",
3652 not_null, ctx->ctx_res_w);
3653 new_p = new_pipe();
3654 ctx->pipe->next = new_p;
3655 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003656 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003657 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003658 * This is used to control execution.
3659 * RES_FOR and RES_IN are NOT sticky (needed to support
3660 * cases where variable or value happens to match a keyword):
3661 */
3662#if ENABLE_HUSH_LOOPS
3663 if (ctx->ctx_res_w == RES_FOR
3664 || ctx->ctx_res_w == RES_IN)
3665 ctx->ctx_res_w = RES_NONE;
3666#endif
3667#if ENABLE_HUSH_CASE
3668 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003669 ctx->ctx_res_w = RES_CASE_BODY;
3670 if (ctx->ctx_res_w == RES_CASE)
3671 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003672#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003673 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003674 /* Create the memory for command, roughly:
3675 * ctx->pipe->cmds = new struct command;
3676 * ctx->command = &ctx->pipe->cmds[0];
3677 */
3678 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003679 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003680 }
3681 debug_printf_parse("done_pipe return\n");
3682}
3683
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003684static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003685{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003686 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003687 if (MAYBE_ASSIGNMENT != 0)
3688 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003689 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003690 /* Create the memory for command, roughly:
3691 * ctx->pipe->cmds = new struct command;
3692 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003693 */
3694 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003695}
3696
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003697/* If a reserved word is found and processed, parse context is modified
3698 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003699 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003700#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003701struct reserved_combo {
3702 char literal[6];
3703 unsigned char res;
3704 unsigned char assignment_flag;
3705 int flag;
3706};
3707enum {
3708 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003709# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003710 FLAG_IF = (1 << RES_IF ),
3711 FLAG_THEN = (1 << RES_THEN ),
3712 FLAG_ELIF = (1 << RES_ELIF ),
3713 FLAG_ELSE = (1 << RES_ELSE ),
3714 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003715# endif
3716# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003717 FLAG_FOR = (1 << RES_FOR ),
3718 FLAG_WHILE = (1 << RES_WHILE),
3719 FLAG_UNTIL = (1 << RES_UNTIL),
3720 FLAG_DO = (1 << RES_DO ),
3721 FLAG_DONE = (1 << RES_DONE ),
3722 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003723# endif
3724# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003725 FLAG_MATCH = (1 << RES_MATCH),
3726 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003727# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003728 FLAG_START = (1 << RES_XXXX ),
3729};
3730
3731static const struct reserved_combo* match_reserved_word(o_string *word)
3732{
Eric Andersen25f27032001-04-26 23:22:31 +00003733 /* Mostly a list of accepted follow-up reserved words.
3734 * FLAG_END means we are done with the sequence, and are ready
3735 * to turn the compound list into a command.
3736 * FLAG_START means the word must start a new compound list.
3737 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003738 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003739# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003740 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3741 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3742 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3743 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3744 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3745 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003746# endif
3747# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003748 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3749 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3750 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3751 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3752 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3753 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003754# endif
3755# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003756 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3757 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003758# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003759 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003760 const struct reserved_combo *r;
3761
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003762 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003763 if (strcmp(word->data, r->literal) == 0)
3764 return r;
3765 }
3766 return NULL;
3767}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003768/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003769 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003770static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003771{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003772# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003773 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003774 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003775 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003776# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003777 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003778
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003779 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003780 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003781 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003782 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003783 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003784
3785 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003786# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003787 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3788 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003789 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003790 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003791# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003792 if (r->flag == 0) { /* '!' */
3793 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003794 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003795 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003796 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003797 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003798 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003799 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003801 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003802
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003803 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003804 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003805 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003806 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003807 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003808 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003809 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003810 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003811 } else {
3812 /* "{...} fi" is ok. "{...} if" is not
3813 * Example:
3814 * if { echo foo; } then { echo bar; } fi */
3815 if (ctx->command->group)
3816 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003817 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003818
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003819 ctx->ctx_res_w = r->res;
3820 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003821 ctx->is_assignment = r->assignment_flag;
3822 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003823
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003824 if (ctx->old_flag & FLAG_END) {
3825 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003826
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003827 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003828 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003829 old = ctx->stack;
3830 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003831 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003832# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003833 /* At this point, the compound command's string is in
3834 * ctx->as_string... except for the leading keyword!
3835 * Consider this example: "echo a | if true; then echo a; fi"
3836 * ctx->as_string will contain "true; then echo a; fi",
3837 * with "if " remaining in old->as_string!
3838 */
3839 {
3840 char *str;
3841 int len = old->as_string.length;
3842 /* Concatenate halves */
3843 o_addstr(&old->as_string, ctx->as_string.data);
3844 o_free_unsafe(&ctx->as_string);
3845 /* Find where leading keyword starts in first half */
3846 str = old->as_string.data + len;
3847 if (str > old->as_string.data)
3848 str--; /* skip whitespace after keyword */
3849 while (str > old->as_string.data && isalpha(str[-1]))
3850 str--;
3851 /* Ugh, we're done with this horrid hack */
3852 old->command->group_as_string = xstrdup(str);
3853 debug_printf_parse("pop, remembering as:'%s'\n",
3854 old->command->group_as_string);
3855 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003856# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003857 *ctx = *old; /* physical copy */
3858 free(old);
3859 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003860 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003861}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003862#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003863
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003864/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003865 * Normal return is 0. Syntax errors return 1.
3866 * Note: on return, word is reset, but not o_free'd!
3867 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003868static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003869{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003870 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003871
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003872 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3873 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003874 debug_printf_parse("done_word return 0: true null, ignored\n");
3875 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003876 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003877
Eric Andersen25f27032001-04-26 23:22:31 +00003878 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003879 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3880 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003881 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003882 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003883 * If the redirection operator is "<<" or "<<-", the word
3884 * that follows the redirection operator shall be
3885 * subjected to quote removal; it is unspecified whether
3886 * any of the other expansions occur. For the other
3887 * redirection operators, the word that follows the
3888 * redirection operator shall be subjected to tilde
3889 * expansion, parameter expansion, command substitution,
3890 * arithmetic expansion, and quote removal.
3891 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003892 * on the word by a non-interactive shell; an interactive
3893 * shell may perform it, but shall do so only when
3894 * the expansion would result in one word."
3895 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003896//bash does not do parameter/command substitution or arithmetic expansion
3897//for _heredoc_ redirection word: these constructs look for exact eof marker
3898// as written:
3899// <<EOF$t
3900// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003901// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3902
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003903 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003904 /* Cater for >\file case:
3905 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3906 * Same with heredocs:
3907 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3908 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003909 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3910 unbackslash(ctx->pending_redirect->rd_filename);
3911 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003912 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003913 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3914 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003915 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003916 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003917 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003918 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003919#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003920# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003921 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003922 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003923 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003924 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003925 /* ctx->ctx_res_w = RES_MATCH; */
3926 ctx->ctx_dsemicolon = 0;
3927 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003928# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003929 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003930# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003931 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3932 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003933# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003934# if ENABLE_HUSH_CASE
3935 && ctx->ctx_res_w != RES_CASE
3936# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003937 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003938 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003939 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003940 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003941 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003942# if ENABLE_HUSH_LINENO_VAR
3943/* Case:
3944 * "while ...; do
3945 * cmd ..."
3946 * If we don't close the pipe _now_, immediately after "do", lineno logic
3947 * sees "cmd" as starting at "do" - i.e., at the previous line.
3948 */
3949 if (0
3950 IF_HUSH_IF(|| reserved->res == RES_THEN)
3951 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3952 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3953 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3954 ) {
3955 done_pipe(ctx, PIPE_SEQ);
3956 }
3957# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003958 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003959 debug_printf_parse("done_word return %d\n",
3960 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003961 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003962 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003963# if defined(CMD_SINGLEWORD_NOGLOB)
3964 if (0
3965# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003966 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003967# endif
3968 /* In bash, local/export/readonly are special, args
3969 * are assignments and therefore expansion of them
3970 * should be "one-word" expansion:
3971 * $ export i=`echo 'a b'` # one arg: "i=a b"
3972 * compare with:
3973 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3974 * ls: cannot access i=a: No such file or directory
3975 * ls: cannot access b: No such file or directory
3976 * Note: bash 3.2.33(1) does this only if export word
3977 * itself is not quoted:
3978 * $ export i=`echo 'aaa bbb'`; echo "$i"
3979 * aaa bbb
3980 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3981 * aaa
3982 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003983 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3984 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3985 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003986 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003987 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3988 }
3989 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003990# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003991 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003992#endif /* HAS_KEYWORDS */
3993
Denis Vlasenkobb929512009-04-16 10:59:40 +00003994 if (command->group) {
3995 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003996 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003997 debug_printf_parse("done_word return 1: syntax error, "
3998 "groups and arglists don't mix\n");
3999 return 1;
4000 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004001
4002 /* If this word wasn't an assignment, next ones definitely
4003 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004004 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4005 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004006 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004007 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004008 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004009 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004010 command->assignment_cnt++;
4011 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4012 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004013 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4014 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004015 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004016 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4017 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004018 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004019 }
Eric Andersen25f27032001-04-26 23:22:31 +00004020
Denis Vlasenko06810332007-05-21 23:30:54 +00004021#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004022 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004023 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004024 || !is_well_formed_var_name(command->argv[0], '\0')
4025 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004026 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004027 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004028 return 1;
4029 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004030 /* Force FOR to have just one word (variable name) */
4031 /* NB: basically, this makes hush see "for v in ..."
4032 * syntax as if it is "for v; in ...". FOR and IN become
4033 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004034 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004035 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004036#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004037#if ENABLE_HUSH_CASE
4038 /* Force CASE to have just one word */
4039 if (ctx->ctx_res_w == RES_CASE) {
4040 done_pipe(ctx, PIPE_SEQ);
4041 }
4042#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004043
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004044 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004045
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004046 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004047 return 0;
4048}
4049
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004050
4051/* Peek ahead in the input to find out if we have a "&n" construct,
4052 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004053 * Return:
4054 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4055 * REDIRFD_SYNTAX_ERR if syntax error,
4056 * REDIRFD_TO_FILE if no & was seen,
4057 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004058 */
4059#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004060#define parse_redir_right_fd(as_string, input) \
4061 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004062#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004063static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004064{
4065 int ch, d, ok;
4066
4067 ch = i_peek(input);
4068 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004069 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004070
4071 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004072 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004073 ch = i_peek(input);
4074 if (ch == '-') {
4075 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004076 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004077 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004078 }
4079 d = 0;
4080 ok = 0;
4081 while (ch != EOF && isdigit(ch)) {
4082 d = d*10 + (ch-'0');
4083 ok = 1;
4084 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004085 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004086 ch = i_peek(input);
4087 }
4088 if (ok) return d;
4089
4090//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4091
4092 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004093 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004094}
4095
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004096/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 */
4098static int parse_redirect(struct parse_context *ctx,
4099 int fd,
4100 redir_type style,
4101 struct in_str *input)
4102{
4103 struct command *command = ctx->command;
4104 struct redir_struct *redir;
4105 struct redir_struct **redirp;
4106 int dup_num;
4107
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004108 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004109 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004110 /* Check for a '>&1' type redirect */
4111 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4112 if (dup_num == REDIRFD_SYNTAX_ERR)
4113 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004114 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004115 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004116 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004117 if (dup_num) { /* <<-... */
4118 ch = i_getch(input);
4119 nommu_addchr(&ctx->as_string, ch);
4120 ch = i_peek(input);
4121 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004122 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004123
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004124 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004125 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004126 if (ch == '|') {
4127 /* >|FILE redirect ("clobbering" >).
4128 * Since we do not support "set -o noclobber" yet,
4129 * >| and > are the same for now. Just eat |.
4130 */
4131 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004132 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133 }
4134 }
4135
4136 /* Create a new redir_struct and append it to the linked list */
4137 redirp = &command->redirects;
4138 while ((redir = *redirp) != NULL) {
4139 redirp = &(redir->next);
4140 }
4141 *redirp = redir = xzalloc(sizeof(*redir));
4142 /* redir->next = NULL; */
4143 /* redir->rd_filename = NULL; */
4144 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004145 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004146
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004147 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4148 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004149
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004150 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004151 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004152 /* Erik had a check here that the file descriptor in question
4153 * is legit; I postpone that to "run time"
4154 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004155 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4156 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004158#if 0 /* Instead we emit error message at run time */
4159 if (ctx->pending_redirect) {
4160 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004161 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004162 }
4163#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004164 /* Set ctx->pending_redirect, so we know what to do at the
4165 * end of the next parsed word. */
4166 ctx->pending_redirect = redir;
4167 }
4168 return 0;
4169}
4170
Eric Andersen25f27032001-04-26 23:22:31 +00004171/* If a redirect is immediately preceded by a number, that number is
4172 * supposed to tell which file descriptor to redirect. This routine
4173 * looks for such preceding numbers. In an ideal world this routine
4174 * needs to handle all the following classes of redirects...
4175 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4176 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4177 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4178 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004179 *
4180 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4181 * "2.7 Redirection
4182 * ... If n is quoted, the number shall not be recognized as part of
4183 * the redirection expression. For example:
4184 * echo \2>a
4185 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004186 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004187 *
4188 * A -1 return means no valid number was found,
4189 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004190 */
4191static int redirect_opt_num(o_string *o)
4192{
4193 int num;
4194
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004195 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004196 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004197 num = bb_strtou(o->data, NULL, 10);
4198 if (errno || num < 0)
4199 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004200 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004201 return num;
4202}
4203
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004204#if BB_MMU
4205#define fetch_till_str(as_string, input, word, skip_tabs) \
4206 fetch_till_str(input, word, skip_tabs)
4207#endif
4208static char *fetch_till_str(o_string *as_string,
4209 struct in_str *input,
4210 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004211 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004212{
4213 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004214 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004215 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004216 int ch;
4217
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004218 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004219
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004220 while (1) {
4221 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004222 if (ch != EOF)
4223 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004224 if (ch == '\n' || ch == EOF) {
4225 check_heredoc_end:
4226 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4227 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4228 heredoc.data[past_EOL] = '\0';
4229 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4230 return heredoc.data;
4231 }
4232 if (ch == '\n') {
4233 /* This is a new line.
4234 * Remember position and backslash-escaping status.
4235 */
4236 o_addchr(&heredoc, ch);
4237 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004238 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004239 past_EOL = heredoc.length;
4240 /* Get 1st char of next line, possibly skipping leading tabs */
4241 do {
4242 ch = i_getch(input);
4243 if (ch != EOF)
4244 nommu_addchr(as_string, ch);
4245 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4246 /* If this immediately ended the line,
4247 * go back to end-of-line checks.
4248 */
4249 if (ch == '\n')
4250 goto check_heredoc_end;
4251 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004252 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004253 }
4254 if (ch == EOF) {
4255 o_free_unsafe(&heredoc);
4256 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004257 }
4258 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004259 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004260 if (prev == '\\' && ch == '\\')
4261 /* Correctly handle foo\\<eol> (not a line cont.) */
4262 prev = 0; /* not \ */
4263 else
4264 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004265 }
4266}
4267
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004268/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4269 * and load them all. There should be exactly heredoc_cnt of them.
4270 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004271static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4272{
4273 struct pipe *pi = ctx->list_head;
4274
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004275 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004276 int i;
4277 struct command *cmd = pi->cmds;
4278
4279 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4280 pi->num_cmds,
4281 cmd->argv ? cmd->argv[0] : "NONE");
4282 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004283 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004284
4285 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4286 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004287 while (redir) {
4288 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 char *p;
4290
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004291 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004292 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004293 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004294 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004295 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004296 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004297 return 1;
4298 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004299 free(redir->rd_filename);
4300 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004301 heredoc_cnt--;
4302 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004303 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004304 }
4305 cmd++;
4306 }
4307 pi = pi->next;
4308 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004309#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004310 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004311 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004312 bb_error_msg_and_die("heredoc BUG 2");
4313#endif
4314 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004315}
4316
4317
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004318static int run_list(struct pipe *pi);
4319#if BB_MMU
4320#define parse_stream(pstring, input, end_trigger) \
4321 parse_stream(input, end_trigger)
4322#endif
4323static struct pipe *parse_stream(char **pstring,
4324 struct in_str *input,
4325 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004326
Eric Andersen25f27032001-04-26 23:22:31 +00004327
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004328static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004329 struct in_str *input, int ch)
4330{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004331 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004332 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004333 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004334#if BB_MMU
4335# define as_string NULL
4336#else
4337 char *as_string = NULL;
4338#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004339 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004340 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004341 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004342
4343 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004344#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004345 if (ch == '(' && !ctx->word.has_quoted_part) {
4346 if (ctx->word.length)
4347 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004348 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004349 if (!command->argv)
4350 goto skip; /* (... */
4351 if (command->argv[1]) { /* word word ... (... */
4352 syntax_error_unexpected_ch('(');
4353 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004354 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004355 /* it is "word(..." or "word (..." */
4356 do
4357 ch = i_getch(input);
4358 while (ch == ' ' || ch == '\t');
4359 if (ch != ')') {
4360 syntax_error_unexpected_ch(ch);
4361 return 1;
4362 }
4363 nommu_addchr(&ctx->as_string, ch);
4364 do
4365 ch = i_getch(input);
4366 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004367 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004368 syntax_error_unexpected_ch(ch);
4369 return 1;
4370 }
4371 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004372 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004373 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004374 }
4375#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004376
4377#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004378 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004379 || ctx->word.length /* word{... */
4380 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004381 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004382 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004383 debug_printf_parse("parse_group return 1: "
4384 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004385 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004386 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004387#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004388
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004389 IF_HUSH_FUNCTIONS(skip:)
4390
Denis Vlasenko240c2552009-04-03 03:45:05 +00004391 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004392 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004393 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004394 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4395 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004396 } else {
4397 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004398 ch = i_peek(input);
4399 if (ch != ' ' && ch != '\t' && ch != '\n'
4400 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4401 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004402 syntax_error_unexpected_ch(ch);
4403 return 1;
4404 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004405 if (ch != '(') {
4406 ch = i_getch(input);
4407 nommu_addchr(&ctx->as_string, ch);
4408 }
Eric Andersen25f27032001-04-26 23:22:31 +00004409 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004410
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004411 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004412#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004413 if (as_string)
4414 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004415#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004416
4417 /* empty ()/{} or parse error? */
4418 if (!pipe_list || pipe_list == ERR_PTR) {
4419 /* parse_stream already emitted error msg */
4420 if (!BB_MMU)
4421 free(as_string);
4422 debug_printf_parse("parse_group return 1: "
4423 "parse_stream returned %p\n", pipe_list);
4424 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004425 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004426#if !BB_MMU
4427 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4428 command->group_as_string = as_string;
4429 debug_printf_parse("end of group, remembering as:'%s'\n",
4430 command->group_as_string);
4431#endif
4432
4433#if ENABLE_HUSH_FUNCTIONS
4434 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4435 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4436 struct command *cmd2;
4437
4438 cmd2 = xzalloc(sizeof(*cmd2));
4439 cmd2->cmd_type = CMD_SUBSHELL;
4440 cmd2->group = pipe_list;
4441# if !BB_MMU
4442//UNTESTED!
4443 cmd2->group_as_string = command->group_as_string;
4444 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4445# endif
4446
4447 pipe_list = new_pipe();
4448 pipe_list->cmds = cmd2;
4449 pipe_list->num_cmds = 1;
4450 }
4451#endif
4452
4453 command->group = pipe_list;
4454
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004455 debug_printf_parse("parse_group return 0\n");
4456 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004457 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004458#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004459}
4460
Denys Vlasenko0b883582016-12-23 16:49:07 +01004461#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004462/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004463static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004464/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004465static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004466{
4467 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004468 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004469 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004470 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004471 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004472 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004473 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004474 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004475 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004476 }
4477}
4478/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004479static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004480{
4481 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004482 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004483 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004484 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004485 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004486 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004487 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004488 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004489 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004490 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004491 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004492 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004493 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004494 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004495 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4496 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004497 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004498 continue;
4499 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004500 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004501 }
4502}
4503/* Process `cmd` - copy contents until "`" is seen. Complicated by
4504 * \` quoting.
4505 * "Within the backquoted style of command substitution, backslash
4506 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4507 * The search for the matching backquote shall be satisfied by the first
4508 * backquote found without a preceding backslash; during this search,
4509 * if a non-escaped backquote is encountered within a shell comment,
4510 * a here-document, an embedded command substitution of the $(command)
4511 * form, or a quoted string, undefined results occur. A single-quoted
4512 * or double-quoted string that begins, but does not end, within the
4513 * "`...`" sequence produces undefined results."
4514 * Example Output
4515 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4516 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004517static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004518{
4519 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004520 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004521 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004522 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004523 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004524 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4525 ch = i_getch(input);
4526 if (ch != '`'
4527 && ch != '$'
4528 && ch != '\\'
4529 && (!in_dquote || ch != '"')
4530 ) {
4531 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004532 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004533 }
4534 if (ch == EOF) {
4535 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004536 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004537 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004538 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004539 }
4540}
4541/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4542 * quoting and nested ()s.
4543 * "With the $(command) style of command substitution, all characters
4544 * following the open parenthesis to the matching closing parenthesis
4545 * constitute the command. Any valid shell script can be used for command,
4546 * except a script consisting solely of redirections which produces
4547 * unspecified results."
4548 * Example Output
4549 * echo $(echo '(TEST)' BEST) (TEST) BEST
4550 * echo $(echo 'TEST)' BEST) TEST) BEST
4551 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004552 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004553 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004554 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004555 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4556 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004557 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004558#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004559static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004560{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004561 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004562 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004563# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004564 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004565# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004566 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4567
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004568 G.promptmode = 1; /* PS2 */
4569 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4570
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004572 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004573 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004574 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004575 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004576 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004577 if (ch == end_ch
4578# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004579 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004580# endif
4581 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004582 if (!dbl)
4583 break;
4584 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004585 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004586 i_getch(input); /* eat second ')' */
4587 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004588 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004589 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004590 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004591 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004592 if (ch == '(' || ch == '{') {
4593 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004594 if (!add_till_closing_bracket(dest, input, ch))
4595 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004596 o_addchr(dest, ch);
4597 continue;
4598 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004599 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004600 if (!add_till_single_quote(dest, input))
4601 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004602 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004603 continue;
4604 }
4605 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004606 if (!add_till_double_quote(dest, input))
4607 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004608 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004609 continue;
4610 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004611 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004612 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4613 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004614 o_addchr(dest, ch);
4615 continue;
4616 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004617 if (ch == '\\') {
4618 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004619 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004620 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004621 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004622 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004623 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004624#if 0
4625 if (ch == '\n') {
4626 /* "backslash+newline", ignore both */
4627 o_delchr(dest); /* undo insertion of '\' */
4628 continue;
4629 }
4630#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004631 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004632 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004633 continue;
4634 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004635 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004636 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004637 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004638}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004639#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004640
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004641/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004642#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004643#define parse_dollar(as_string, dest, input, quote_mask) \
4644 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004645#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004646#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004647static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004648 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004649 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004650{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004651 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004652
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004653 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004654 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004655 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004656 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004657 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004658 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004659 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004660 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004661 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004662 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004663 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004664 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004665 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004666 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004667 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004668 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004669 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004670 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004671 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004673 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004674 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004675 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004676 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004678 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004679 o_addchr(dest, ch | quote_mask);
4680 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004681 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004682 case '$': /* pid */
4683 case '!': /* last bg pid */
4684 case '?': /* last exit code */
4685 case '#': /* number of args */
4686 case '*': /* args */
4687 case '@': /* args */
4688 goto make_one_char_var;
4689 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004690 char len_single_ch;
4691
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004692 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4693
Denys Vlasenko74369502010-05-21 19:52:01 +02004694 ch = i_getch(input); /* eat '{' */
4695 nommu_addchr(as_string, ch);
4696
Denys Vlasenko46e64982016-09-29 19:50:55 +02004697 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004698 /* It should be ${?}, or ${#var},
4699 * or even ${?+subst} - operator acting on a special variable,
4700 * or the beginning of variable name.
4701 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004702 if (ch == EOF
4703 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4704 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004705 bad_dollar_syntax:
4706 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004707 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4708 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004709 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004710 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004711 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004712 ch |= quote_mask;
4713
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004714 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004715 * However, this regresses some of our testsuite cases
4716 * which check invalid constructs like ${%}.
4717 * Oh well... let's check that the var name part is fine... */
4718
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004719 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004720 unsigned pos;
4721
Denys Vlasenko74369502010-05-21 19:52:01 +02004722 o_addchr(dest, ch);
4723 debug_printf_parse(": '%c'\n", ch);
4724
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004725 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004726 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004727 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004728 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004729
Denys Vlasenko74369502010-05-21 19:52:01 +02004730 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004731 unsigned end_ch;
4732 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004733 /* handle parameter expansions
4734 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4735 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004736 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4737 if (len_single_ch != '#'
4738 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4739 || i_peek(input) != '}'
4740 ) {
4741 goto bad_dollar_syntax;
4742 }
4743 /* else: it's "length of C" ${#C} op,
4744 * where C is a single char
4745 * special var name, e.g. ${#!}.
4746 */
4747 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004748 /* Eat everything until closing '}' (or ':') */
4749 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004750 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004751 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004752 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004753 ) {
4754 /* It's ${var:N[:M]} thing */
4755 end_ch = '}' * 0x100 + ':';
4756 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004757 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004758 && ch == '/'
4759 ) {
4760 /* It's ${var/[/]pattern[/repl]} thing */
4761 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4762 i_getch(input);
4763 nommu_addchr(as_string, '/');
4764 ch = '\\';
4765 }
4766 end_ch = '}' * 0x100 + '/';
4767 }
4768 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004769 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004770 if (!BB_MMU)
4771 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004772#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004773 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004774 if (last_ch == 0) /* error? */
4775 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004776#else
4777#error Simple code to only allow ${var} is not implemented
4778#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004779 if (as_string) {
4780 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004781 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004782 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004783
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004784 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4785 && (end_ch & 0xff00)
4786 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004787 /* close the first block: */
4788 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004789 /* while parsing N from ${var:N[:M]}
4790 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004791 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004792 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004793 end_ch = '}';
4794 goto again;
4795 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004796 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004797 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004798 /* it's ${var:N} - emulate :999999999 */
4799 o_addstr(dest, "999999999");
4800 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004801 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004802 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004803 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004804 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004805 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004806 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4807 break;
4808 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004809#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004810 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004811 unsigned pos;
4812
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004813 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004814 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004815# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004816 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004817 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004818 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4820 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004821 if (!BB_MMU)
4822 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004823 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4824 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004825 if (as_string) {
4826 o_addstr(as_string, dest->data + pos);
4827 o_addchr(as_string, ')');
4828 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004829 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004830 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004831 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004832 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004833# endif
4834# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004835 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4836 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004837 if (!BB_MMU)
4838 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004839 if (!add_till_closing_bracket(dest, input, ')'))
4840 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004841 if (as_string) {
4842 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004843 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004844 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004845 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004846# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004847 break;
4848 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004849#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004850 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004851 goto make_var;
4852#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004853 /* TODO: $_ and $-: */
4854 /* $_ Shell or shell script name; or last argument of last command
4855 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4856 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004857 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004858 ch = i_getch(input);
4859 nommu_addchr(as_string, ch);
4860 ch = i_peek_and_eat_bkslash_nl(input);
4861 if (isalnum(ch)) { /* it's $_name or $_123 */
4862 ch = '_';
4863 goto make_var1;
4864 }
4865 /* else: it's $_ */
4866#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004867 default:
4868 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004869 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004870 debug_printf_parse("parse_dollar return 1 (ok)\n");
4871 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004872#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004873}
4874
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004875#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004876# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004877#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4878 encode_string(dest, input, dquote_end, process_bkslash)
4879# else
4880/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4881#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4882 encode_string(dest, input, dquote_end)
4883# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004884#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004885
4886#else /* !MMU */
4887
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004888# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004889/* all parameters are needed, no macro tricks */
4890# else
4891#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4892 encode_string(as_string, dest, input, dquote_end)
4893# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004894#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004895static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004896 o_string *dest,
4897 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004898 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004899 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004900{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004901#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004902 const int process_bkslash = 1;
4903#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004904 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004905 int next;
4906
4907 again:
4908 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004909 if (ch != EOF)
4910 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004911 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004912 debug_printf_parse("encode_string return 1 (ok)\n");
4913 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004914 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004915 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004916 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004917 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004918 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004919 }
4920 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004921 if (ch != '\n') {
4922 next = i_peek(input);
4923 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004924 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004925 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004926 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004927 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004928 /* Testcase: in interactive shell a file with
4929 * echo "unterminated string\<eof>
4930 * is sourced.
4931 */
4932 syntax_error_unterm_ch('"');
4933 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004934 }
4935 /* bash:
4936 * "The backslash retains its special meaning [in "..."]
4937 * only when followed by one of the following characters:
4938 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004939 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004940 * NB: in (unquoted) heredoc, above does not apply to ",
4941 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004942 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004943 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004944 ch = i_getch(input); /* eat next */
4945 if (ch == '\n')
4946 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004947 } /* else: ch remains == '\\', and we double it below: */
4948 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004949 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004950 goto again;
4951 }
4952 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004953 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4954 debug_printf_parse("encode_string return 0: "
4955 "parse_dollar returned 0 (error)\n");
4956 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004957 }
4958 goto again;
4959 }
4960#if ENABLE_HUSH_TICK
4961 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004962 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004963 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4964 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004965 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4966 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004967 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4968 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004969 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004970 }
4971#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004972 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004973 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004974#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004975}
4976
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004977/*
4978 * Scan input until EOF or end_trigger char.
4979 * Return a list of pipes to execute, or NULL on EOF
4980 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004981 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004982 * reset parsing machinery and start parsing anew,
4983 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004984 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004985static struct pipe *parse_stream(char **pstring,
4986 struct in_str *input,
4987 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004988{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004989 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004990 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004991
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004992 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004993 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004994 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004995 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004996 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004997 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004998
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004999 initialize_context(&ctx);
5000
5001 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5002 * Preventing this:
5003 */
5004 o_addchr(&ctx.word, '\0');
5005 ctx.word.length = 0;
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005006
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005007 /* We used to separate words on $IFS here. This was wrong.
5008 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005009 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005010 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005011
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005012 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005013 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005014 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005015 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005016 int ch;
5017 int next;
5018 int redir_fd;
5019 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005020
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005021 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005022 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005023 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005024 if (ch == EOF) {
5025 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005026
5027 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005028 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005029 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005030 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005031 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005032 syntax_error_unterm_ch('(');
5033 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005034 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005035 if (end_trigger == '}') {
5036 syntax_error_unterm_ch('{');
5037 goto parse_error;
5038 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005039
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005040 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005041 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005042 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005043 o_free(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005044 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005045 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005046 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005047 /* (this makes bare "&" cmd a no-op.
5048 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005049 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005050 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005051 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005052 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005053 pi = NULL;
5054 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005055#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005056 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005057 if (pstring)
5058 *pstring = ctx.as_string.data;
5059 else
5060 o_free_unsafe(&ctx.as_string);
5061#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005062 debug_leave();
5063 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005064 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005065 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005066 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005067
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005068 if (ch == '\'') {
5069 ctx.word.has_quoted_part = 1;
5070 next = i_getch(input);
5071 if (next == '\'' && !ctx.pending_redirect)
5072 goto insert_empty_quoted_str_marker;
5073
5074 ch = next;
5075 while (1) {
5076 if (ch == EOF) {
5077 syntax_error_unterm_ch('\'');
5078 goto parse_error;
5079 }
5080 nommu_addchr(&ctx.as_string, ch);
5081 if (ch == '\'')
5082 break;
5083 if (ch == SPECIAL_VAR_SYMBOL) {
5084 /* Convert raw ^C to corresponding special variable reference */
5085 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5086 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5087 }
5088 o_addqchr(&ctx.word, ch);
5089 ch = i_getch(input);
5090 }
5091 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005092 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005093
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005094 next = '\0';
5095 if (ch != '\n' && ch != '\\') {
5096 /* Not on '\': do not break the case of "echo z\\":
5097 * on 2nd '\', i_peek_and_eat_bkslash_nl()
5098 * would stop and try to read next line,
5099 * not letting the command to execute.
5100 */
5101 next = i_peek_and_eat_bkslash_nl(input);
5102 }
5103
5104 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005105 "\\$\"" IF_HUSH_TICK("`") /* always special */
5106 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005107 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005108 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005109 || ctx.word.length /* word{... - non-special */
5110 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005111 || (next != ';' /* }; - special */
5112 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005113 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005114 && next != '&' /* }& and }&& ... - special */
5115 && next != '|' /* }|| ... - special */
5116 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005117 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005118 ) {
5119 /* They are not special, skip "{}" */
5120 is_special += 2;
5121 }
5122 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005123 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005124
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005125 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005126 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005127 o_addQchr(&ctx.word, ch);
5128 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5129 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005130 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005131 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005132 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005133 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5134 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005135 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005136 continue;
5137 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005138
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005139 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005140#if ENABLE_HUSH_LINENO_VAR
5141/* Case:
5142 * "while ...; do<whitespace><newline>
5143 * cmd ..."
5144 * would think that "cmd" starts in <whitespace> -
5145 * i.e., at the previous line.
5146 * We need to skip all whitespace before newlines.
5147 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005148 while (ch != '\n') {
5149 next = i_peek(input);
5150 if (next != ' ' && next != '\t' && next != '\n')
5151 break; /* next char is not ws */
5152 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005153 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005154 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005155#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005156 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005157 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005158 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005159 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005160 /* Is this a case when newline is simply ignored?
5161 * Some examples:
5162 * "cmd | <newline> cmd ..."
5163 * "case ... in <newline> word) ..."
5164 */
5165 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005166 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005167 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005168 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005169 * Without check #1, interactive shell
5170 * ignores even bare <newline>,
5171 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005172 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005173 * ps2> _ <=== wrong, should be ps1
5174 * Without check #2, "cmd & <newline>"
5175 * is similarly mistreated.
5176 * (BTW, this makes "cmd & cmd"
5177 * and "cmd && cmd" non-orthogonal.
5178 * Really, ask yourself, why
5179 * "cmd && <newline>" doesn't start
5180 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005181 * The only reason is that it might be
5182 * a "cmd1 && <nl> cmd2 &" construct,
5183 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005184 */
5185 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005186 if (pi->num_cmds != 0 /* check #1 */
5187 && pi->followup != PIPE_BG /* check #2 */
5188 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005189 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005190 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005191 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005192 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005193 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005194 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5195 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005196 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005197 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005198 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005199 heredoc_cnt = 0;
5200 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005201 ctx.is_assignment = MAYBE_ASSIGNMENT;
5202 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005203 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005204 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005205 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005206 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005207 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005208
5209 /* "cmd}" or "cmd }..." without semicolon or &:
5210 * } is an ordinary char in this case, even inside { cmd; }
5211 * Pathological example: { ""}; } should exec "}" cmd
5212 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005213 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005214 if (ctx.word.length != 0 /* word} */
5215 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005216 ) {
5217 goto ordinary_char;
5218 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005219 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5220 /* Generally, there should be semicolon: "cmd; }"
5221 * However, bash allows to omit it if "cmd" is
5222 * a group. Examples:
5223 * { { echo 1; } }
5224 * {(echo 1)}
5225 * { echo 0 >&2 | { echo 1; } }
5226 * { while false; do :; done }
5227 * { case a in b) ;; esac }
5228 */
5229 if (ctx.command->group)
5230 goto term_group;
5231 goto ordinary_char;
5232 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005233 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005234 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005235 goto skip_end_trigger;
5236 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005237 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005238 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005239 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005240 && (ch != ';' || heredoc_cnt == 0)
5241#if ENABLE_HUSH_CASE
5242 && (ch != ')'
5243 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005244 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005245 )
5246#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005247 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005248 if (heredoc_cnt) {
5249 /* This is technically valid:
5250 * { cat <<HERE; }; echo Ok
5251 * heredoc
5252 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005253 * HERE
5254 * but we don't support this.
5255 * We require heredoc to be in enclosing {}/(),
5256 * if any.
5257 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005258 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005259 goto parse_error;
5260 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005261 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005262 goto parse_error;
5263 }
5264 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005265 ctx.is_assignment = MAYBE_ASSIGNMENT;
5266 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005267 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005268 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005269 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005270 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005271 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005272#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005273 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005274 if (pstring)
5275 *pstring = ctx.as_string.data;
5276 else
5277 o_free_unsafe(&ctx.as_string);
5278#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005279 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5280 /* Example: bare "{ }", "()" */
5281 G.last_exitcode = 2; /* bash compat */
5282 syntax_error_unexpected_ch(ch);
5283 goto parse_error2;
5284 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005285 debug_printf_parse("parse_stream return %p: "
5286 "end_trigger char found\n",
5287 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005288 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005289 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005290 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005291 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005292
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005293 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005294 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005295
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005296 /* Catch <, > before deciding whether this word is
5297 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5298 switch (ch) {
5299 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005300 redir_fd = redirect_opt_num(&ctx.word);
5301 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005302 goto parse_error;
5303 }
5304 redir_style = REDIRECT_OVERWRITE;
5305 if (next == '>') {
5306 redir_style = REDIRECT_APPEND;
5307 ch = i_getch(input);
5308 nommu_addchr(&ctx.as_string, ch);
5309 }
5310#if 0
5311 else if (next == '(') {
5312 syntax_error(">(process) not supported");
5313 goto parse_error;
5314 }
5315#endif
5316 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5317 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005318 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005319 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005320 redir_fd = redirect_opt_num(&ctx.word);
5321 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005322 goto parse_error;
5323 }
5324 redir_style = REDIRECT_INPUT;
5325 if (next == '<') {
5326 redir_style = REDIRECT_HEREDOC;
5327 heredoc_cnt++;
5328 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5329 ch = i_getch(input);
5330 nommu_addchr(&ctx.as_string, ch);
5331 } else if (next == '>') {
5332 redir_style = REDIRECT_IO;
5333 ch = i_getch(input);
5334 nommu_addchr(&ctx.as_string, ch);
5335 }
5336#if 0
5337 else if (next == '(') {
5338 syntax_error("<(process) not supported");
5339 goto parse_error;
5340 }
5341#endif
5342 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5343 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005344 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005345 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005346 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005347 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005348 /* note: we do not add it to &ctx.as_string */
5349/* TODO: in bash:
5350 * comment inside $() goes to the next \n, even inside quoted string (!):
5351 * cmd "$(cmd2 #comment)" - syntax error
5352 * cmd "`cmd2 #comment`" - ok
5353 * We accept both (comment ends where command subst ends, in both cases).
5354 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005355 while (1) {
5356 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005357 if (ch == '\n') {
5358 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005359 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005360 }
5361 ch = i_getch(input);
5362 if (ch == EOF)
5363 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005364 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005365 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005366 }
5367 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005368 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005369 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005370
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005371 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005372 /* check that we are not in word in "a=1 2>word b=1": */
5373 && !ctx.pending_redirect
5374 ) {
5375 /* ch is a special char and thus this word
5376 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005377 ctx.is_assignment = NOT_ASSIGNMENT;
5378 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005379 }
5380
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005381 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5382
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005383 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005384 case SPECIAL_VAR_SYMBOL:
5385 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005386 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5387 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005388 /* fall through */
5389 case '#':
5390 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005391 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005392 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005393 case '\\':
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005394 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005395 ch = i_getch(input);
5396 if (ch == EOF) {
Denys Vlasenkobcf56112018-04-10 14:40:23 +02005397 /* Ignore this '\'. Testcase: eval 'echo Ok\' */
5398#if !BB_MMU
5399 /* Remove trailing '\' from ctx.as_string */
5400 ctx.as_string.data[--ctx.as_string.length] = '\0';
5401#endif
5402 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005403 }
Denys Vlasenkobcf56112018-04-10 14:40:23 +02005404 o_addchr(&ctx.word, '\\');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005405 /* Example: echo Hello \2>file
Denys Vlasenkobcf56112018-04-10 14:40:23 +02005406 * we need to know that word 2 is quoted
5407 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005408 ctx.word.has_quoted_part = 1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005409 nommu_addchr(&ctx.as_string, ch);
5410 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005411 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005412 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005413 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005414 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005415 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005416 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005417 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005418 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005419 case '"':
5420 ctx.word.has_quoted_part = 1;
5421 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005422 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005423 insert_empty_quoted_str_marker:
5424 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005425 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5426 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005427 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005428 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005429 if (ctx.is_assignment == NOT_ASSIGNMENT)
5430 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5431 if (!encode_string(&ctx.as_string, &ctx.word, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005432 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005433 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005434 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005435#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005436 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005437 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005438
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005439 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5440 o_addchr(&ctx.word, '`');
5441 USE_FOR_NOMMU(pos = ctx.word.length;)
5442 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005443 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005444# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005445 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005446 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005447# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005448 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5449 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005450 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005451 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005452#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005453 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005454#if ENABLE_HUSH_CASE
5455 case_semi:
5456#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005457 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005458 goto parse_error;
5459 }
5460 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005461#if ENABLE_HUSH_CASE
5462 /* Eat multiple semicolons, detect
5463 * whether it means something special */
5464 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005465 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005466 if (ch != ';')
5467 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005468 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005469 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005470 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005471 ctx.ctx_dsemicolon = 1;
5472 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005473 break;
5474 }
5475 }
5476#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005477 new_cmd:
5478 /* We just finished a cmd. New one may start
5479 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005480 ctx.is_assignment = MAYBE_ASSIGNMENT;
5481 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005482 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005483 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005484 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005485 goto parse_error;
5486 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005487 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005488 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005489 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005490 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005491 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005492 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005493 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005494 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005495 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005496 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005497 goto parse_error;
5498 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005499#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005500 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005501 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005502#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005503 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005504 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005505 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005506 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005507 } else {
5508 /* we could pick up a file descriptor choice here
5509 * with redirect_opt_num(), but bash doesn't do it.
5510 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005511 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005512 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005513 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005514 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005515#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005516 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005517 if (ctx.ctx_res_w == RES_MATCH
5518 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005519 && ctx.word.length == 0 /* not word(... */
5520 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005521 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005522 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005523 }
5524#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005525 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005526 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005527 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005528 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005529 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005530 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005531#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005532 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005533 goto case_semi;
5534#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005535 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005536 /* proper use of this character is caught by end_trigger:
5537 * if we see {, we call parse_group(..., end_trigger='}')
5538 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005539 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005540 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005541 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005542 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005543 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005544 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005545 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005546 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005547
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005548 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005549 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005550 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005551 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005552 struct parse_context *pctx;
5553 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005554
5555 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005556 * Sample for finding leaks on syntax error recovery path.
5557 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005558 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005559 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005560 * while if (true | { true;}); then echo ok; fi; do break; done
5561 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005562 */
5563 pctx = &ctx;
5564 do {
5565 /* Update pipe/command counts,
5566 * otherwise freeing may miss some */
5567 done_pipe(pctx, PIPE_SEQ);
5568 debug_printf_clean("freeing list %p from ctx %p\n",
5569 pctx->list_head, pctx);
5570 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005571 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005572 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005573#if !BB_MMU
5574 o_free_unsafe(&pctx->as_string);
5575#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005576 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005577 if (pctx != &ctx) {
5578 free(pctx);
5579 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005580 IF_HAS_KEYWORDS(pctx = p2;)
5581 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005582
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005583 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005584#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005585 if (pstring)
5586 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005587#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005588 debug_leave();
5589 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005590 }
Eric Andersen25f27032001-04-26 23:22:31 +00005591}
5592
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005593
5594/*** Execution routines ***/
5595
5596/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005597#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005598/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5599#define expand_string_to_string(str, do_unbackslash) \
5600 expand_string_to_string(str)
5601#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005602static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005603#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005604static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005605#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005606
5607/* expand_strvec_to_strvec() takes a list of strings, expands
5608 * all variable references within and returns a pointer to
5609 * a list of expanded strings, possibly with larger number
5610 * of strings. (Think VAR="a b"; echo $VAR).
5611 * This new list is allocated as a single malloc block.
5612 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005613 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005614 * Caller can deallocate entire list by single free(list). */
5615
Denys Vlasenko238081f2010-10-03 14:26:26 +02005616/* A horde of its helpers come first: */
5617
5618static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5619{
5620 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005621 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005622
Denys Vlasenko9e800222010-10-03 14:28:04 +02005623#if ENABLE_HUSH_BRACE_EXPANSION
5624 if (c == '{' || c == '}') {
5625 /* { -> \{, } -> \} */
5626 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005627 /* And now we want to add { or } and continue:
5628 * o_addchr(o, c);
5629 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005630 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005631 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005632 }
5633#endif
5634 o_addchr(o, c);
5635 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005636 /* \z -> \\\z; \<eol> -> \\<eol> */
5637 o_addchr(o, '\\');
5638 if (len) {
5639 len--;
5640 o_addchr(o, '\\');
5641 o_addchr(o, *str++);
5642 }
5643 }
5644 }
5645}
5646
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005647/* Store given string, finalizing the word and starting new one whenever
5648 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005649 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5650 * Return in *ended_with_ifs:
5651 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5652 */
5653static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005654{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005655 int last_is_ifs = 0;
5656
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005657 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005658 int word_len;
5659
5660 if (!*str) /* EOL - do not finalize word */
5661 break;
5662 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005663 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005664 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005665 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005666 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005667 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005668 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005669 * Example: "v='\*'; echo b$v" prints "b\*"
5670 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005671 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005672 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005673 /*/ Why can't we do it easier? */
5674 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5675 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5676 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005677 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005678 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005679 if (!*str) /* EOL - do not finalize word */
5680 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005681 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005682
5683 /* We know str here points to at least one IFS char */
5684 last_is_ifs = 1;
5685 str += strspn(str, G.ifs); /* skip IFS chars */
5686 if (!*str) /* EOL - do not finalize word */
5687 break;
5688
5689 /* Start new word... but not always! */
5690 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005691 if (output->has_quoted_part
5692 /* Case "v=' a'; echo $v":
5693 * here nothing precedes the space in $v expansion,
5694 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005695 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005696 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005697 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005698 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005699 o_addchr(output, '\0');
5700 debug_print_list("expand_on_ifs", output, n);
5701 n = o_save_ptr(output, n);
5702 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005703 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005704
5705 if (ended_with_ifs)
5706 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005707 debug_print_list("expand_on_ifs[1]", output, n);
5708 return n;
5709}
5710
5711/* Helper to expand $((...)) and heredoc body. These act as if
5712 * they are in double quotes, with the exception that they are not :).
5713 * Just the rules are similar: "expand only $var and `cmd`"
5714 *
5715 * Returns malloced string.
5716 * As an optimization, we return NULL if expansion is not needed.
5717 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005718#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005719/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5720#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5721 encode_then_expand_string(str)
5722#endif
5723static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005724{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005725#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005726 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005727#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005728 char *exp_str;
5729 struct in_str input;
5730 o_string dest = NULL_O_STRING;
5731
5732 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005733 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005734#if ENABLE_HUSH_TICK
5735 && !strchr(str, '`')
5736#endif
5737 ) {
5738 return NULL;
5739 }
5740
5741 /* We need to expand. Example:
5742 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5743 */
5744 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005745 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005746//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005747 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005748 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5750 o_free_unsafe(&dest);
5751 return exp_str;
5752}
5753
Denys Vlasenko0b883582016-12-23 16:49:07 +01005754#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005755static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005756{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005757 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005758 arith_t res;
5759 char *exp_str;
5760
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005761 math_state.lookupvar = get_local_var_value;
5762 math_state.setvar = set_local_var_from_halves;
5763 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005764 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005765 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005766 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005767 if (errmsg_p)
5768 *errmsg_p = math_state.errmsg;
5769 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005770 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005771 return res;
5772}
5773#endif
5774
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005775#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005776/* ${var/[/]pattern[/repl]} helpers */
5777static char *strstr_pattern(char *val, const char *pattern, int *size)
5778{
5779 while (1) {
5780 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5781 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5782 if (end) {
5783 *size = end - val;
5784 return val;
5785 }
5786 if (*val == '\0')
5787 return NULL;
5788 /* Optimization: if "*pat" did not match the start of "string",
5789 * we know that "tring", "ring" etc will not match too:
5790 */
5791 if (pattern[0] == '*')
5792 return NULL;
5793 val++;
5794 }
5795}
5796static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5797{
5798 char *result = NULL;
5799 unsigned res_len = 0;
5800 unsigned repl_len = strlen(repl);
5801
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005802 /* Null pattern never matches, including if "var" is empty */
5803 if (!pattern[0])
5804 return result; /* NULL, no replaces happened */
5805
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005806 while (1) {
5807 int size;
5808 char *s = strstr_pattern(val, pattern, &size);
5809 if (!s)
5810 break;
5811
5812 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005813 strcpy(mempcpy(result + res_len, val, s - val), repl);
5814 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005815 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5816
5817 val = s + size;
5818 if (exp_op == '/')
5819 break;
5820 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005821 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005822 result = xrealloc(result, res_len + strlen(val) + 1);
5823 strcpy(result + res_len, val);
5824 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5825 }
5826 debug_printf_varexp("result:'%s'\n", result);
5827 return result;
5828}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005829#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005830
5831/* Helper:
5832 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5833 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005834static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005835{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005836 const char *val;
5837 char *to_be_freed;
5838 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005839 char *var;
5840 char first_char;
5841 char exp_op;
5842 char exp_save = exp_save; /* for compiler */
5843 char *exp_saveptr; /* points to expansion operator */
5844 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005845 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005846
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005847 val = NULL;
5848 to_be_freed = NULL;
5849 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005850 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005851 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005852 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005853 arg0 = arg[0];
5854 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005855 exp_op = 0;
5856
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005857 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5858 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5859 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5860 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005861 ) {
5862 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005863 var++;
5864 exp_op = 'L';
5865 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005866 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005867 if (exp_saveptr /* if 2nd char is one of expansion operators */
5868 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5869 ) {
5870 /* ${?:0}, ${#[:]%0} etc */
5871 exp_saveptr = var + 1;
5872 } else {
5873 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5874 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5875 }
5876 exp_op = exp_save = *exp_saveptr;
5877 if (exp_op) {
5878 exp_word = exp_saveptr + 1;
5879 if (exp_op == ':') {
5880 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005881//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005882 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005883 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005884 ) {
5885 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5886 exp_op = ':';
5887 exp_word--;
5888 }
5889 }
5890 *exp_saveptr = '\0';
5891 } /* else: it's not an expansion op, but bare ${var} */
5892 }
5893
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005894 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005895 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005896 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005897 int n = xatoi_positive(var);
5898 if (n < G.global_argc)
5899 val = G.global_argv[n];
5900 /* else val remains NULL: $N with too big N */
5901 } else {
5902 switch (var[0]) {
5903 case '$': /* pid */
5904 val = utoa(G.root_pid);
5905 break;
5906 case '!': /* bg pid */
5907 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5908 break;
5909 case '?': /* exitcode */
5910 val = utoa(G.last_exitcode);
5911 break;
5912 case '#': /* argc */
5913 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5914 break;
5915 default:
5916 val = get_local_var_value(var);
5917 }
5918 }
5919
5920 /* Handle any expansions */
5921 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005922 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005923 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005924 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005925 debug_printf_expand("%s\n", val);
5926 } else if (exp_op) {
5927 if (exp_op == '%' || exp_op == '#') {
5928 /* Standard-mandated substring removal ops:
5929 * ${parameter%word} - remove smallest suffix pattern
5930 * ${parameter%%word} - remove largest suffix pattern
5931 * ${parameter#word} - remove smallest prefix pattern
5932 * ${parameter##word} - remove largest prefix pattern
5933 *
5934 * Word is expanded to produce a glob pattern.
5935 * Then var's value is matched to it and matching part removed.
5936 */
5937 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005938 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005939 char *exp_exp_word;
5940 char *loc;
5941 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005942 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005943 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005944 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005945 /*
5946 * process_bkslash:1 unbackslash:1 breaks this:
5947 * a='a\\'; echo ${a%\\\\} # correct output is: a
5948 * process_bkslash:1 unbackslash:0 breaks this:
5949 * a='a}'; echo ${a%\}} # correct output is: a
5950 */
5951 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952 if (exp_exp_word)
5953 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005954 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005955 /* HACK ALERT. We depend here on the fact that
5956 * G.global_argv and results of utoa and get_local_var_value
5957 * are actually in writable memory:
5958 * scan_and_match momentarily stores NULs there. */
5959 t = (char*)val;
5960 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005961 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005962 free(exp_exp_word);
5963 if (loc) { /* match was found */
5964 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005965 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005966 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005967 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005968 }
5969 }
5970 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005971#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005972 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005973 /* It's ${var/[/]pattern[/repl]} thing.
5974 * Note that in encoded form it has TWO parts:
5975 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005976 * and if // is used, it is encoded as \:
5977 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005978 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005979 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005980 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005981 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005982 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02005983 * >az >bz
5984 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
5985 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
5986 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
5987 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005988 * (note that a*z _pattern_ is never globbed!)
5989 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005990 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005991 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005992 if (!pattern)
5993 pattern = xstrdup(exp_word);
5994 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5995 *p++ = SPECIAL_VAR_SYMBOL;
5996 exp_word = p;
5997 p = strchr(p, SPECIAL_VAR_SYMBOL);
5998 *p = '\0';
Denys Vlasenkode026252018-04-05 17:04:53 +02005999 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006000 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6001 /* HACK ALERT. We depend here on the fact that
6002 * G.global_argv and results of utoa and get_local_var_value
6003 * are actually in writable memory:
6004 * replace_pattern momentarily stores NULs there. */
6005 t = (char*)val;
6006 to_be_freed = replace_pattern(t,
6007 pattern,
6008 (repl ? repl : exp_word),
6009 exp_op);
6010 if (to_be_freed) /* at least one replace happened */
6011 val = to_be_freed;
6012 free(pattern);
6013 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006014 } else {
6015 /* Empty variable always gives nothing */
6016 // "v=''; echo ${v/*/w}" prints "", not "w"
6017 /* Just skip "replace" part */
6018 *p++ = SPECIAL_VAR_SYMBOL;
6019 p = strchr(p, SPECIAL_VAR_SYMBOL);
6020 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006021 }
6022 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006023#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006024 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006025#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006026 /* It's ${var:N[:M]} bashism.
6027 * Note that in encoded form it has TWO parts:
6028 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6029 */
6030 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006031 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006032
Denys Vlasenko063847d2010-09-15 13:33:02 +02006033 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6034 if (errmsg)
6035 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006036 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6037 *p++ = SPECIAL_VAR_SYMBOL;
6038 exp_word = p;
6039 p = strchr(p, SPECIAL_VAR_SYMBOL);
6040 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006041 len = expand_and_evaluate_arith(exp_word, &errmsg);
6042 if (errmsg)
6043 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006044 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006045 if (beg < 0) {
6046 /* negative beg counts from the end */
6047 beg = (arith_t)strlen(val) + beg;
6048 if (beg < 0) /* ${v: -999999} is "" */
6049 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006050 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006051 debug_printf_varexp("from val:'%s'\n", val);
6052 if (len < 0) {
6053 /* in bash, len=-n means strlen()-n */
6054 len = (arith_t)strlen(val) - beg + len;
6055 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006056 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006057 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006058 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006059 arith_err:
6060 val = NULL;
6061 } else {
6062 /* Paranoia. What if user entered 9999999999999
6063 * which fits in arith_t but not int? */
6064 if (len >= INT_MAX)
6065 len = INT_MAX;
6066 val = to_be_freed = xstrndup(val + beg, len);
6067 }
6068 debug_printf_varexp("val:'%s'\n", val);
6069#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006070 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006071 val = NULL;
6072#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006073 } else { /* one of "-=+?" */
6074 /* Standard-mandated substitution ops:
6075 * ${var?word} - indicate error if unset
6076 * If var is unset, word (or a message indicating it is unset
6077 * if word is null) is written to standard error
6078 * and the shell exits with a non-zero exit status.
6079 * Otherwise, the value of var is substituted.
6080 * ${var-word} - use default value
6081 * If var is unset, word is substituted.
6082 * ${var=word} - assign and use default value
6083 * If var is unset, word is assigned to var.
6084 * In all cases, final value of var is substituted.
6085 * ${var+word} - use alternative value
6086 * If var is unset, null is substituted.
6087 * Otherwise, word is substituted.
6088 *
6089 * Word is subjected to tilde expansion, parameter expansion,
6090 * command substitution, and arithmetic expansion.
6091 * If word is not needed, it is not expanded.
6092 *
6093 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6094 * but also treat null var as if it is unset.
6095 */
6096 int use_word = (!val || ((exp_save == ':') && !val[0]));
6097 if (exp_op == '+')
6098 use_word = !use_word;
6099 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6100 (exp_save == ':') ? "true" : "false", use_word);
6101 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006102 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006103 if (to_be_freed)
6104 exp_word = to_be_freed;
6105 if (exp_op == '?') {
6106 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006107 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006108 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006109 exp_word[0]
6110 ? exp_word
6111 : "parameter null or not set"
6112 /* ash has more specific messages, a-la: */
6113 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006114 );
6115//TODO: how interactive bash aborts expansion mid-command?
6116 } else {
6117 val = exp_word;
6118 }
6119
6120 if (exp_op == '=') {
6121 /* ${var=[word]} or ${var:=[word]} */
6122 if (isdigit(var[0]) || var[0] == '#') {
6123 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006124 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006125 val = NULL;
6126 } else {
6127 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006128 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 }
6130 }
6131 }
6132 } /* one of "-=+?" */
6133
6134 *exp_saveptr = exp_save;
6135 } /* if (exp_op) */
6136
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006137 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138
6139 *pp = p;
6140 *to_be_freed_pp = to_be_freed;
6141 return val;
6142}
6143
6144/* Expand all variable references in given string, adding words to list[]
6145 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6146 * to be filled). This routine is extremely tricky: has to deal with
6147 * variables/parameters with whitespace, $* and $@, and constructs like
6148 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006149static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006150{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006151 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006152 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006154 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006155 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006156 char *p;
6157
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006158 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6159 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160 debug_print_list("expand_vars_to_list", output, n);
6161 n = o_save_ptr(output, n);
6162 debug_print_list("expand_vars_to_list[0]", output, n);
6163
6164 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6165 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006166 char *to_be_freed = NULL;
6167 const char *val = NULL;
6168#if ENABLE_HUSH_TICK
6169 o_string subst_result = NULL_O_STRING;
6170#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006171#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 char arith_buf[sizeof(arith_t)*3 + 2];
6173#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006174
6175 if (ended_in_ifs) {
6176 o_addchr(output, '\0');
6177 n = o_save_ptr(output, n);
6178 ended_in_ifs = 0;
6179 }
6180
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006181 o_addblock(output, arg, p - arg);
6182 debug_print_list("expand_vars_to_list[1]", output, n);
6183 arg = ++p;
6184 p = strchr(p, SPECIAL_VAR_SYMBOL);
6185
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006186 /* Fetch special var name (if it is indeed one of them)
6187 * and quote bit, force the bit on if singleword expansion -
6188 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006189 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006190
6191 /* Is this variable quoted and thus expansion can't be null?
6192 * "$@" is special. Even if quoted, it can still
6193 * expand to nothing (not even an empty string),
6194 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006195 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006196 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197
6198 switch (first_ch & 0x7f) {
6199 /* Highest bit in first_ch indicates that var is double-quoted */
6200 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006201 case '@': {
6202 int i;
6203 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006204 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006205 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006206 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006207 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006208 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006209 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006210 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6211 if (G.global_argv[i++][0] && G.global_argv[i]) {
6212 /* this argv[] is not empty and not last:
6213 * put terminating NUL, start new word */
6214 o_addchr(output, '\0');
6215 debug_print_list("expand_vars_to_list[2]", output, n);
6216 n = o_save_ptr(output, n);
6217 debug_print_list("expand_vars_to_list[3]", output, n);
6218 }
6219 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006220 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006221 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006223 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006224 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006225 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006226 while (1) {
6227 o_addQstr(output, G.global_argv[i]);
6228 if (++i >= G.global_argc)
6229 break;
6230 o_addchr(output, '\0');
6231 debug_print_list("expand_vars_to_list[4]", output, n);
6232 n = o_save_ptr(output, n);
6233 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006234 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006235 while (1) {
6236 o_addQstr(output, G.global_argv[i]);
6237 if (!G.global_argv[++i])
6238 break;
6239 if (G.ifs[0])
6240 o_addchr(output, G.ifs[0]);
6241 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006242 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006243 }
6244 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006245 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006246 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6247 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006248 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006249 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006250 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006251 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006252 case SPECIAL_VAR_QUOTED_SVS:
6253 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6254 arg++;
6255 val = SPECIAL_VAR_SYMBOL_STR;
6256 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006257#if ENABLE_HUSH_TICK
6258 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006259 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006260 arg++;
6261 /* Can't just stuff it into output o_string,
6262 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006263 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006264 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6265 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006266 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6268 val = subst_result.data;
6269 goto store_val;
6270#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006271#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006272 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6273 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006274
6275 arg++; /* skip '+' */
6276 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6277 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006278 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006279 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6280 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006281 val = arith_buf;
6282 break;
6283 }
6284#endif
6285 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006286 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006287 IF_HUSH_TICK(store_val:)
6288 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006289 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6290 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006291 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006292 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006293 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294 }
6295 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006296 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006297 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6298 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006299 }
6300 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006301 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6302
6303 if (val && val[0]) {
6304 o_addQstr(output, val);
6305 }
6306 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006307
6308 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6309 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 if (*p != SPECIAL_VAR_SYMBOL)
6311 *p = SPECIAL_VAR_SYMBOL;
6312
6313#if ENABLE_HUSH_TICK
6314 o_free(&subst_result);
6315#endif
6316 arg = ++p;
6317 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6318
6319 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006320 if (ended_in_ifs) {
6321 o_addchr(output, '\0');
6322 n = o_save_ptr(output, n);
6323 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 debug_print_list("expand_vars_to_list[a]", output, n);
6325 /* this part is literal, and it was already pre-quoted
6326 * if needed (much earlier), do not use o_addQstr here! */
6327 o_addstr_with_NUL(output, arg);
6328 debug_print_list("expand_vars_to_list[b]", output, n);
6329 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006330 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006331 ) {
6332 n--;
6333 /* allow to reuse list[n] later without re-growth */
6334 output->has_empty_slot = 1;
6335 } else {
6336 o_addchr(output, '\0');
6337 }
6338
6339 return n;
6340}
6341
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006342static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343{
6344 int n;
6345 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006346 o_string output = NULL_O_STRING;
6347
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006348 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349
6350 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006351 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006352 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006353 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006354 }
6355 debug_print_list("expand_variables", &output, n);
6356
6357 /* output.data (malloced in one block) gets returned in "list" */
6358 list = o_finalize_list(&output, n);
6359 debug_print_strings("expand_variables[1]", list);
6360 return list;
6361}
6362
6363static char **expand_strvec_to_strvec(char **argv)
6364{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006365 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006366}
6367
Denys Vlasenko11752d42018-04-03 08:20:58 +02006368#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6370{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006371 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006372}
6373#endif
6374
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006375/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006376 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006377 *
6378 * NB: should NOT do globbing!
6379 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6380 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006381static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006382{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006383#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006384 const int do_unbackslash = 1;
6385#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006386 char *argv[2], **list;
6387
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006388 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006389 /* This is generally an optimization, but it also
6390 * handles "", which otherwise trips over !list[0] check below.
6391 * (is this ever happens that we actually get str="" here?)
6392 */
6393 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6394 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006395 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006396 return xstrdup(str);
6397 }
6398
6399 argv[0] = (char*)str;
6400 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006401 list = expand_variables(argv, do_unbackslash
6402 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6403 : EXP_FLAG_SINGLEWORD
6404 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006405 if (HUSH_DEBUG)
6406 if (!list[0] || list[1])
6407 bb_error_msg_and_die("BUG in varexp2");
6408 /* actually, just move string 2*sizeof(char*) bytes back */
6409 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006410 if (do_unbackslash)
6411 unbackslash((char*)list);
6412 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006413 return (char*)list;
6414}
6415
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006416#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006417static char* expand_strvec_to_string(char **argv)
6418{
6419 char **list;
6420
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006421 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006422 /* Convert all NULs to spaces */
6423 if (list[0]) {
6424 int n = 1;
6425 while (list[n]) {
6426 if (HUSH_DEBUG)
6427 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6428 bb_error_msg_and_die("BUG in varexp3");
6429 /* bash uses ' ' regardless of $IFS contents */
6430 list[n][-1] = ' ';
6431 n++;
6432 }
6433 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006434 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006435 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6436 return (char*)list;
6437}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006438#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006439
6440static char **expand_assignments(char **argv, int count)
6441{
6442 int i;
6443 char **p;
6444
6445 G.expanded_assignments = p = NULL;
6446 /* Expand assignments into one string each */
6447 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006448 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006449 }
6450 G.expanded_assignments = NULL;
6451 return p;
6452}
6453
6454
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006455static void switch_off_special_sigs(unsigned mask)
6456{
6457 unsigned sig = 0;
6458 while ((mask >>= 1) != 0) {
6459 sig++;
6460 if (!(mask & 1))
6461 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006462#if ENABLE_HUSH_TRAP
6463 if (G_traps) {
6464 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006465 /* trap is '', has to remain SIG_IGN */
6466 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006467 free(G_traps[sig]);
6468 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006469 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006470#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006471 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006472 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006473 }
6474}
6475
Denys Vlasenkob347df92011-08-09 22:49:15 +02006476#if BB_MMU
6477/* never called */
6478void re_execute_shell(char ***to_free, const char *s,
6479 char *g_argv0, char **g_argv,
6480 char **builtin_argv) NORETURN;
6481
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006482static void reset_traps_to_defaults(void)
6483{
6484 /* This function is always called in a child shell
6485 * after fork (not vfork, NOMMU doesn't use this function).
6486 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006487 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488 unsigned mask;
6489
6490 /* Child shells are not interactive.
6491 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6492 * Testcase: (while :; do :; done) + ^Z should background.
6493 * Same goes for SIGTERM, SIGHUP, SIGINT.
6494 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006495 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006496 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006497 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006498
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006499 /* Switch off special sigs */
6500 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006501# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006502 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006503# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006504 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006505 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6506 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006507
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006508# if ENABLE_HUSH_TRAP
6509 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006510 return;
6511
6512 /* Reset all sigs to default except ones with empty traps */
6513 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006514 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006515 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006516 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006517 continue; /* empty trap: has to remain SIG_IGN */
6518 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006519 free(G_traps[sig]);
6520 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006521 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006522 if (sig == 0)
6523 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006524 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006525 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006526# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006527}
6528
6529#else /* !BB_MMU */
6530
6531static void re_execute_shell(char ***to_free, const char *s,
6532 char *g_argv0, char **g_argv,
6533 char **builtin_argv) NORETURN;
6534static void re_execute_shell(char ***to_free, const char *s,
6535 char *g_argv0, char **g_argv,
6536 char **builtin_argv)
6537{
6538# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6539 /* delims + 2 * (number of bytes in printed hex numbers) */
6540 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6541 char *heredoc_argv[4];
6542 struct variable *cur;
6543# if ENABLE_HUSH_FUNCTIONS
6544 struct function *funcp;
6545# endif
6546 char **argv, **pp;
6547 unsigned cnt;
6548 unsigned long long empty_trap_mask;
6549
6550 if (!g_argv0) { /* heredoc */
6551 argv = heredoc_argv;
6552 argv[0] = (char *) G.argv0_for_re_execing;
6553 argv[1] = (char *) "-<";
6554 argv[2] = (char *) s;
6555 argv[3] = NULL;
6556 pp = &argv[3]; /* used as pointer to empty environment */
6557 goto do_exec;
6558 }
6559
6560 cnt = 0;
6561 pp = builtin_argv;
6562 if (pp) while (*pp++)
6563 cnt++;
6564
6565 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006566 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567 int sig;
6568 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006569 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006570 empty_trap_mask |= 1LL << sig;
6571 }
6572 }
6573
6574 sprintf(param_buf, NOMMU_HACK_FMT
6575 , (unsigned) G.root_pid
6576 , (unsigned) G.root_ppid
6577 , (unsigned) G.last_bg_pid
6578 , (unsigned) G.last_exitcode
6579 , cnt
6580 , empty_trap_mask
6581 IF_HUSH_LOOPS(, G.depth_of_loop)
6582 );
6583# undef NOMMU_HACK_FMT
6584 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6585 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6586 */
6587 cnt += 6;
6588 for (cur = G.top_var; cur; cur = cur->next) {
6589 if (!cur->flg_export || cur->flg_read_only)
6590 cnt += 2;
6591 }
6592# if ENABLE_HUSH_FUNCTIONS
6593 for (funcp = G.top_func; funcp; funcp = funcp->next)
6594 cnt += 3;
6595# endif
6596 pp = g_argv;
6597 while (*pp++)
6598 cnt++;
6599 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6600 *pp++ = (char *) G.argv0_for_re_execing;
6601 *pp++ = param_buf;
6602 for (cur = G.top_var; cur; cur = cur->next) {
6603 if (strcmp(cur->varstr, hush_version_str) == 0)
6604 continue;
6605 if (cur->flg_read_only) {
6606 *pp++ = (char *) "-R";
6607 *pp++ = cur->varstr;
6608 } else if (!cur->flg_export) {
6609 *pp++ = (char *) "-V";
6610 *pp++ = cur->varstr;
6611 }
6612 }
6613# if ENABLE_HUSH_FUNCTIONS
6614 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6615 *pp++ = (char *) "-F";
6616 *pp++ = funcp->name;
6617 *pp++ = funcp->body_as_string;
6618 }
6619# endif
6620 /* We can pass activated traps here. Say, -Tnn:trap_string
6621 *
6622 * However, POSIX says that subshells reset signals with traps
6623 * to SIG_DFL.
6624 * I tested bash-3.2 and it not only does that with true subshells
6625 * of the form ( list ), but with any forked children shells.
6626 * I set trap "echo W" WINCH; and then tried:
6627 *
6628 * { echo 1; sleep 20; echo 2; } &
6629 * while true; do echo 1; sleep 20; echo 2; break; done &
6630 * true | { echo 1; sleep 20; echo 2; } | cat
6631 *
6632 * In all these cases sending SIGWINCH to the child shell
6633 * did not run the trap. If I add trap "echo V" WINCH;
6634 * _inside_ group (just before echo 1), it works.
6635 *
6636 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006637 */
6638 *pp++ = (char *) "-c";
6639 *pp++ = (char *) s;
6640 if (builtin_argv) {
6641 while (*++builtin_argv)
6642 *pp++ = *builtin_argv;
6643 *pp++ = (char *) "";
6644 }
6645 *pp++ = g_argv0;
6646 while (*g_argv)
6647 *pp++ = *g_argv++;
6648 /* *pp = NULL; - is already there */
6649 pp = environ;
6650
6651 do_exec:
6652 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006653 /* Don't propagate SIG_IGN to the child */
6654 if (SPECIAL_JOBSTOP_SIGS != 0)
6655 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006656 execve(bb_busybox_exec_path, argv, pp);
6657 /* Fallback. Useful for init=/bin/hush usage etc */
6658 if (argv[0][0] == '/')
6659 execve(argv[0], argv, pp);
6660 xfunc_error_retval = 127;
6661 bb_error_msg_and_die("can't re-execute the shell");
6662}
6663#endif /* !BB_MMU */
6664
6665
6666static int run_and_free_list(struct pipe *pi);
6667
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006668/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006669 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6670 * end_trigger controls how often we stop parsing
6671 * NUL: parse all, execute, return
6672 * ';': parse till ';' or newline, execute, repeat till EOF
6673 */
6674static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006675{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006676 /* Why we need empty flag?
6677 * An obscure corner case "false; ``; echo $?":
6678 * empty command in `` should still set $? to 0.
6679 * But we can't just set $? to 0 at the start,
6680 * this breaks "false; echo `echo $?`" case.
6681 */
6682 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006683 while (1) {
6684 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006685
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006686#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02006687 if (end_trigger == ';') {
6688 G.promptmode = 0; /* PS1 */
6689 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
6690 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006691#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006692 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006693 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6694 /* If we are in "big" script
6695 * (not in `cmd` or something similar)...
6696 */
6697 if (pipe_list == ERR_PTR && end_trigger == ';') {
6698 /* Discard cached input (rest of line) */
6699 int ch = inp->last_char;
6700 while (ch != EOF && ch != '\n') {
6701 //bb_error_msg("Discarded:'%c'", ch);
6702 ch = i_getch(inp);
6703 }
6704 /* Force prompt */
6705 inp->p = NULL;
6706 /* This stream isn't empty */
6707 empty = 0;
6708 continue;
6709 }
6710 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006711 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006712 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006713 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006714 debug_print_tree(pipe_list, 0);
6715 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6716 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006717 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006718 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006719 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006720 }
Eric Andersen25f27032001-04-26 23:22:31 +00006721}
6722
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006723static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006724{
6725 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006726 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6727
Eric Andersen25f27032001-04-26 23:22:31 +00006728 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006729 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006730 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006731}
6732
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006733static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006734{
Eric Andersen25f27032001-04-26 23:22:31 +00006735 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006736 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006737
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006738 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006739 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006740 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006741 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006742}
6743
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744#if ENABLE_HUSH_TICK
6745static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6746{
6747 pid_t pid;
6748 int channel[2];
6749# if !BB_MMU
6750 char **to_free = NULL;
6751# endif
6752
6753 xpipe(channel);
6754 pid = BB_MMU ? xfork() : xvfork();
6755 if (pid == 0) { /* child */
6756 disable_restore_tty_pgrp_on_exit();
6757 /* Process substitution is not considered to be usual
6758 * 'command execution'.
6759 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6760 */
6761 bb_signals(0
6762 + (1 << SIGTSTP)
6763 + (1 << SIGTTIN)
6764 + (1 << SIGTTOU)
6765 , SIG_IGN);
6766 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6767 close(channel[0]); /* NB: close _first_, then move fd! */
6768 xmove_fd(channel[1], 1);
6769 /* Prevent it from trying to handle ctrl-z etc */
6770 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006771# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006772 /* Awful hack for `trap` or $(trap).
6773 *
6774 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6775 * contains an example where "trap" is executed in a subshell:
6776 *
6777 * save_traps=$(trap)
6778 * ...
6779 * eval "$save_traps"
6780 *
6781 * Standard does not say that "trap" in subshell shall print
6782 * parent shell's traps. It only says that its output
6783 * must have suitable form, but then, in the above example
6784 * (which is not supposed to be normative), it implies that.
6785 *
6786 * bash (and probably other shell) does implement it
6787 * (traps are reset to defaults, but "trap" still shows them),
6788 * but as a result, "trap" logic is hopelessly messed up:
6789 *
6790 * # trap
6791 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6792 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6793 * # true | trap <--- trap is in subshell - no output (ditto)
6794 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6795 * trap -- 'echo Ho' SIGWINCH
6796 * # echo `(trap)` <--- in subshell in subshell - output
6797 * trap -- 'echo Ho' SIGWINCH
6798 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6799 * trap -- 'echo Ho' SIGWINCH
6800 *
6801 * The rules when to forget and when to not forget traps
6802 * get really complex and nonsensical.
6803 *
6804 * Our solution: ONLY bare $(trap) or `trap` is special.
6805 */
6806 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006807 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006808 && skip_whitespace(s + 4)[0] == '\0'
6809 ) {
6810 static const char *const argv[] = { NULL, NULL };
6811 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006812 fflush_all(); /* important */
6813 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006814 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006815# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006816# if BB_MMU
6817 reset_traps_to_defaults();
6818 parse_and_run_string(s);
6819 _exit(G.last_exitcode);
6820# else
6821 /* We re-execute after vfork on NOMMU. This makes this script safe:
6822 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6823 * huge=`cat BIG` # was blocking here forever
6824 * echo OK
6825 */
6826 re_execute_shell(&to_free,
6827 s,
6828 G.global_argv[0],
6829 G.global_argv + 1,
6830 NULL);
6831# endif
6832 }
6833
6834 /* parent */
6835 *pid_p = pid;
6836# if ENABLE_HUSH_FAST
6837 G.count_SIGCHLD++;
6838//bb_error_msg("[%d] fork in generate_stream_from_string:"
6839// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6840// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6841# endif
6842 enable_restore_tty_pgrp_on_exit();
6843# if !BB_MMU
6844 free(to_free);
6845# endif
6846 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006847 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006848}
6849
6850/* Return code is exit status of the process that is run. */
6851static int process_command_subs(o_string *dest, const char *s)
6852{
6853 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006854 pid_t pid;
6855 int status, ch, eol_cnt;
6856
6857 fp = generate_stream_from_string(s, &pid);
6858
6859 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006860 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006861 while ((ch = getc(fp)) != EOF) {
6862 if (ch == '\0')
6863 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006864 if (ch == '\n') {
6865 eol_cnt++;
6866 continue;
6867 }
6868 while (eol_cnt) {
6869 o_addchr(dest, '\n');
6870 eol_cnt--;
6871 }
6872 o_addQchr(dest, ch);
6873 }
6874
6875 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006876 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006877 /* We need to extract exitcode. Test case
6878 * "true; echo `sleep 1; false` $?"
6879 * should print 1 */
6880 safe_waitpid(pid, &status, 0);
6881 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6882 return WEXITSTATUS(status);
6883}
6884#endif /* ENABLE_HUSH_TICK */
6885
6886
6887static void setup_heredoc(struct redir_struct *redir)
6888{
6889 struct fd_pair pair;
6890 pid_t pid;
6891 int len, written;
6892 /* the _body_ of heredoc (misleading field name) */
6893 const char *heredoc = redir->rd_filename;
6894 char *expanded;
6895#if !BB_MMU
6896 char **to_free;
6897#endif
6898
6899 expanded = NULL;
6900 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006901 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006902 if (expanded)
6903 heredoc = expanded;
6904 }
6905 len = strlen(heredoc);
6906
6907 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6908 xpiped_pair(pair);
6909 xmove_fd(pair.rd, redir->rd_fd);
6910
6911 /* Try writing without forking. Newer kernels have
6912 * dynamically growing pipes. Must use non-blocking write! */
6913 ndelay_on(pair.wr);
6914 while (1) {
6915 written = write(pair.wr, heredoc, len);
6916 if (written <= 0)
6917 break;
6918 len -= written;
6919 if (len == 0) {
6920 close(pair.wr);
6921 free(expanded);
6922 return;
6923 }
6924 heredoc += written;
6925 }
6926 ndelay_off(pair.wr);
6927
6928 /* Okay, pipe buffer was not big enough */
6929 /* Note: we must not create a stray child (bastard? :)
6930 * for the unsuspecting parent process. Child creates a grandchild
6931 * and exits before parent execs the process which consumes heredoc
6932 * (that exec happens after we return from this function) */
6933#if !BB_MMU
6934 to_free = NULL;
6935#endif
6936 pid = xvfork();
6937 if (pid == 0) {
6938 /* child */
6939 disable_restore_tty_pgrp_on_exit();
6940 pid = BB_MMU ? xfork() : xvfork();
6941 if (pid != 0)
6942 _exit(0);
6943 /* grandchild */
6944 close(redir->rd_fd); /* read side of the pipe */
6945#if BB_MMU
6946 full_write(pair.wr, heredoc, len); /* may loop or block */
6947 _exit(0);
6948#else
6949 /* Delegate blocking writes to another process */
6950 xmove_fd(pair.wr, STDOUT_FILENO);
6951 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6952#endif
6953 }
6954 /* parent */
6955#if ENABLE_HUSH_FAST
6956 G.count_SIGCHLD++;
6957//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6958#endif
6959 enable_restore_tty_pgrp_on_exit();
6960#if !BB_MMU
6961 free(to_free);
6962#endif
6963 close(pair.wr);
6964 free(expanded);
6965 wait(NULL); /* wait till child has died */
6966}
6967
Denys Vlasenko2db74612017-07-07 22:07:28 +02006968struct squirrel {
6969 int orig_fd;
6970 int moved_to;
6971 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6972 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6973};
6974
Denys Vlasenko621fc502017-07-24 12:42:17 +02006975static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6976{
6977 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6978 sq[i].orig_fd = orig;
6979 sq[i].moved_to = moved;
6980 sq[i+1].orig_fd = -1; /* end marker */
6981 return sq;
6982}
6983
Denys Vlasenko2db74612017-07-07 22:07:28 +02006984static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6985{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006986 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006987 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006988
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006989 i = 0;
6990 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006991 /* If we collide with an already moved fd... */
6992 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006993 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006994 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6995 if (sq[i].moved_to < 0) /* what? */
6996 xfunc_die();
6997 return sq;
6998 }
6999 if (fd == sq[i].orig_fd) {
7000 /* Example: echo Hello >/dev/null 1>&2 */
7001 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7002 return sq;
7003 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007004 }
7005
Denys Vlasenko2db74612017-07-07 22:07:28 +02007006 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007007 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007008 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7009 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007010 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007011 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007012}
7013
Denys Vlasenko657e9002017-07-30 23:34:04 +02007014static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7015{
7016 int i;
7017
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007018 i = 0;
7019 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007020 /* If we collide with an already moved fd... */
7021 if (fd == sq[i].orig_fd) {
7022 /* Examples:
7023 * "echo 3>FILE 3>&- 3>FILE"
7024 * "echo 3>&- 3>FILE"
7025 * No need for last redirect to insert
7026 * another "need to close 3" indicator.
7027 */
7028 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7029 return sq;
7030 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007031 }
7032
7033 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7034 return append_squirrel(sq, i, fd, -1);
7035}
7036
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007037/* fd: redirect wants this fd to be used (e.g. 3>file).
7038 * Move all conflicting internally used fds,
7039 * and remember them so that we can restore them later.
7040 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007041static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007042{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007043 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7044 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007045
7046#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007047 if (fd == G.interactive_fd) {
7048 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007049 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007050 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7051 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007052 }
7053#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007054 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7055 * (1) Redirect in a forked child. No need to save FILEs' fds,
7056 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007057 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7058 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007059 * "fileno(fd) = new_fd" can't be done.
7060 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007061 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007062 return 0;
7063
Denys Vlasenko2db74612017-07-07 22:07:28 +02007064 /* If this one of script's fds? */
7065 if (save_FILEs_on_redirect(fd, avoid_fd))
7066 return 1; /* yes. "we closed fd" */
7067
7068 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7069 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7070 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007071}
7072
Denys Vlasenko2db74612017-07-07 22:07:28 +02007073static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007074{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007075 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007076 int i;
7077 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007078 if (sq[i].moved_to >= 0) {
7079 /* We simply die on error */
7080 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7081 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7082 } else {
7083 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7084 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7085 close(sq[i].orig_fd);
7086 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007087 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007088 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007089 }
7090
Denys Vlasenko2db74612017-07-07 22:07:28 +02007091 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007092
7093 restore_redirected_FILEs();
7094}
7095
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007096#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007097static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007098{
7099 if (G_interactive_fd)
7100 close(G_interactive_fd);
7101 close_all_FILE_list();
7102}
7103#endif
7104
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007105static int internally_opened_fd(int fd, struct squirrel *sq)
7106{
7107 int i;
7108
7109#if ENABLE_HUSH_INTERACTIVE
7110 if (fd == G.interactive_fd)
7111 return 1;
7112#endif
7113 /* If this one of script's fds? */
7114 if (fd_in_FILEs(fd))
7115 return 1;
7116
7117 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7118 if (fd == sq[i].moved_to)
7119 return 1;
7120 }
7121 return 0;
7122}
7123
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007124/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7125 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007126static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007127{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007128 struct redir_struct *redir;
7129
7130 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007131 int newfd;
7132 int closed;
7133
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007134 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007135 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007136 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007137 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7138 * of the heredoc */
7139 debug_printf_parse("set heredoc '%s'\n",
7140 redir->rd_filename);
7141 setup_heredoc(redir);
7142 continue;
7143 }
7144
7145 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007146 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007147 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007148 int mode;
7149
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007150 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007151 /*
7152 * Examples:
7153 * "cmd >" (no filename)
7154 * "cmd > <file" (2nd redirect starts too early)
7155 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007156 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007157 continue;
7158 }
7159 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007160 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007161 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007162 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007163 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007164 /* Error message from open_or_warn can be lost
7165 * if stderr has been redirected, but bash
7166 * and ash both lose it as well
7167 * (though zsh doesn't!)
7168 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007169 return 1;
7170 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007171 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007172 /* open() gave us precisely the fd we wanted.
7173 * This means that this fd was not busy
7174 * (not opened to anywhere).
7175 * Remember to close it on restore:
7176 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007177 *sqp = add_squirrel_closed(*sqp, newfd);
7178 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007179 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007180 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007181 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7182 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007183 }
7184
Denys Vlasenko657e9002017-07-30 23:34:04 +02007185 if (newfd == redir->rd_fd)
7186 continue;
7187
7188 /* if "N>FILE": move newfd to redir->rd_fd */
7189 /* if "N>&M": dup newfd to redir->rd_fd */
7190 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7191
7192 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7193 if (newfd == REDIRFD_CLOSE) {
7194 /* "N>&-" means "close me" */
7195 if (!closed) {
7196 /* ^^^ optimization: saving may already
7197 * have closed it. If not... */
7198 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007199 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007200 /* Sometimes we do another close on restore, getting EBADF.
7201 * Consider "echo 3>FILE 3>&-"
7202 * first redirect remembers "need to close 3",
7203 * and second redirect closes 3! Restore code then closes 3 again.
7204 */
7205 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007206 /* if newfd is a script fd or saved fd, simulate EBADF */
7207 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7208 //errno = EBADF;
7209 //bb_perror_msg_and_die("can't duplicate file descriptor");
7210 newfd = -1; /* same effect as code above */
7211 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007212 xdup2(newfd, redir->rd_fd);
7213 if (redir->rd_dup == REDIRFD_TO_FILE)
7214 /* "rd_fd > FILE" */
7215 close(newfd);
7216 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007217 }
7218 }
7219 return 0;
7220}
7221
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007222static char *find_in_path(const char *arg)
7223{
7224 char *ret = NULL;
7225 const char *PATH = get_local_var_value("PATH");
7226
7227 if (!PATH)
7228 return NULL;
7229
7230 while (1) {
7231 const char *end = strchrnul(PATH, ':');
7232 int sz = end - PATH; /* must be int! */
7233
7234 free(ret);
7235 if (sz != 0) {
7236 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7237 } else {
7238 /* We have xxx::yyyy in $PATH,
7239 * it means "use current dir" */
7240 ret = xstrdup(arg);
7241 }
7242 if (access(ret, F_OK) == 0)
7243 break;
7244
7245 if (*end == '\0') {
7246 free(ret);
7247 return NULL;
7248 }
7249 PATH = end + 1;
7250 }
7251
7252 return ret;
7253}
7254
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007255static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007256 const struct built_in_command *x,
7257 const struct built_in_command *end)
7258{
7259 while (x != end) {
7260 if (strcmp(name, x->b_cmd) != 0) {
7261 x++;
7262 continue;
7263 }
7264 debug_printf_exec("found builtin '%s'\n", name);
7265 return x;
7266 }
7267 return NULL;
7268}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007269static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007270{
7271 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7272}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007273static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007274{
7275 const struct built_in_command *x = find_builtin1(name);
7276 if (x)
7277 return x;
7278 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7279}
7280
7281#if ENABLE_HUSH_FUNCTIONS
7282static struct function **find_function_slot(const char *name)
7283{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007284 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007285 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007286
7287 while ((funcp = *funcpp) != NULL) {
7288 if (strcmp(name, funcp->name) == 0) {
7289 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007290 break;
7291 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007292 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007293 }
7294 return funcpp;
7295}
7296
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007297static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007298{
7299 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007300 return funcp;
7301}
7302
7303/* Note: takes ownership on name ptr */
7304static struct function *new_function(char *name)
7305{
7306 struct function **funcpp = find_function_slot(name);
7307 struct function *funcp = *funcpp;
7308
7309 if (funcp != NULL) {
7310 struct command *cmd = funcp->parent_cmd;
7311 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7312 if (!cmd) {
7313 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7314 free(funcp->name);
7315 /* Note: if !funcp->body, do not free body_as_string!
7316 * This is a special case of "-F name body" function:
7317 * body_as_string was not malloced! */
7318 if (funcp->body) {
7319 free_pipe_list(funcp->body);
7320# if !BB_MMU
7321 free(funcp->body_as_string);
7322# endif
7323 }
7324 } else {
7325 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7326 cmd->argv[0] = funcp->name;
7327 cmd->group = funcp->body;
7328# if !BB_MMU
7329 cmd->group_as_string = funcp->body_as_string;
7330# endif
7331 }
7332 } else {
7333 debug_printf_exec("remembering new function '%s'\n", name);
7334 funcp = *funcpp = xzalloc(sizeof(*funcp));
7335 /*funcp->next = NULL;*/
7336 }
7337
7338 funcp->name = name;
7339 return funcp;
7340}
7341
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007342# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007343static void unset_func(const char *name)
7344{
7345 struct function **funcpp = find_function_slot(name);
7346 struct function *funcp = *funcpp;
7347
7348 if (funcp != NULL) {
7349 debug_printf_exec("freeing function '%s'\n", funcp->name);
7350 *funcpp = funcp->next;
7351 /* funcp is unlinked now, deleting it.
7352 * Note: if !funcp->body, the function was created by
7353 * "-F name body", do not free ->body_as_string
7354 * and ->name as they were not malloced. */
7355 if (funcp->body) {
7356 free_pipe_list(funcp->body);
7357 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007358# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007359 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007360# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007361 }
7362 free(funcp);
7363 }
7364}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007365# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007366
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007367static void remove_nested_vars(void)
7368{
7369 struct variable *cur;
7370 struct variable **cur_pp;
7371
7372 cur_pp = &G.top_var;
7373 while ((cur = *cur_pp) != NULL) {
7374 if (cur->var_nest_level <= G.var_nest_level) {
7375 cur_pp = &cur->next;
7376 continue;
7377 }
7378 /* Unexport */
7379 if (cur->flg_export) {
7380 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7381 bb_unsetenv(cur->varstr);
7382 }
7383 /* Remove from global list */
7384 *cur_pp = cur->next;
7385 /* Free */
7386 if (!cur->max_len) {
7387 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7388 free(cur->varstr);
7389 }
7390 free(cur);
7391 }
7392}
7393
7394static void enter_var_nest_level(void)
7395{
7396 G.var_nest_level++;
7397 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7398
7399 /* Try: f() { echo -n .; f; }; f
7400 * struct variable::var_nest_level is uint16_t,
7401 * thus limiting recursion to < 2^16.
7402 * In any case, with 8 Mbyte stack SEGV happens
7403 * not too long after 2^16 recursions anyway.
7404 */
7405 if (G.var_nest_level > 0xff00)
7406 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7407}
7408
7409static void leave_var_nest_level(void)
7410{
7411 G.var_nest_level--;
7412 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7413 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7414 bb_error_msg_and_die("BUG: nesting underflow");
7415
7416 remove_nested_vars();
7417}
7418
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007419# if BB_MMU
7420#define exec_function(to_free, funcp, argv) \
7421 exec_function(funcp, argv)
7422# endif
7423static void exec_function(char ***to_free,
7424 const struct function *funcp,
7425 char **argv) NORETURN;
7426static void exec_function(char ***to_free,
7427 const struct function *funcp,
7428 char **argv)
7429{
7430# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007431 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007432
7433 argv[0] = G.global_argv[0];
7434 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007435 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007436
7437// Example when we are here: "cmd | func"
7438// func will run with saved-redirect fds open.
7439// $ f() { echo /proc/self/fd/*; }
7440// $ true | f
7441// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7442// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7443// Same in script:
7444// $ . ./SCRIPT
7445// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7446// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7447// They are CLOEXEC so external programs won't see them, but
7448// for "more correctness" we might want to close those extra fds here:
7449//? close_saved_fds_and_FILE_fds();
7450
Denys Vlasenko332e4112018-04-04 22:32:59 +02007451 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007452 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007453 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007454 IF_HUSH_LOCAL(G.func_nest_level++;)
7455
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007456 /* On MMU, funcp->body is always non-NULL */
7457 n = run_list(funcp->body);
7458 fflush_all();
7459 _exit(n);
7460# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007461//? close_saved_fds_and_FILE_fds();
7462
7463//TODO: check whether "true | func_with_return" works
7464
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007465 re_execute_shell(to_free,
7466 funcp->body_as_string,
7467 G.global_argv[0],
7468 argv + 1,
7469 NULL);
7470# endif
7471}
7472
7473static int run_function(const struct function *funcp, char **argv)
7474{
7475 int rc;
7476 save_arg_t sv;
7477 smallint sv_flg;
7478
7479 save_and_replace_G_args(&sv, argv);
7480
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007481 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007482 sv_flg = G_flag_return_in_progress;
7483 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007484
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007485 /* Make "local" variables properly shadow previous ones */
7486 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007487 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007488
7489 /* On MMU, funcp->body is always non-NULL */
7490# if !BB_MMU
7491 if (!funcp->body) {
7492 /* Function defined by -F */
7493 parse_and_run_string(funcp->body_as_string);
7494 rc = G.last_exitcode;
7495 } else
7496# endif
7497 {
7498 rc = run_list(funcp->body);
7499 }
7500
Denys Vlasenko332e4112018-04-04 22:32:59 +02007501 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007502 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007503
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007504 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007505
7506 restore_G_args(&sv, argv);
7507
7508 return rc;
7509}
7510#endif /* ENABLE_HUSH_FUNCTIONS */
7511
7512
7513#if BB_MMU
7514#define exec_builtin(to_free, x, argv) \
7515 exec_builtin(x, argv)
7516#else
7517#define exec_builtin(to_free, x, argv) \
7518 exec_builtin(to_free, argv)
7519#endif
7520static void exec_builtin(char ***to_free,
7521 const struct built_in_command *x,
7522 char **argv) NORETURN;
7523static void exec_builtin(char ***to_free,
7524 const struct built_in_command *x,
7525 char **argv)
7526{
7527#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007528 int rcode;
7529 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007530//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007531 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007532 fflush_all();
7533 _exit(rcode);
7534#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007535 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007536 /* On NOMMU, we must never block!
7537 * Example: { sleep 99 | read line; } & echo Ok
7538 */
7539 re_execute_shell(to_free,
7540 argv[0],
7541 G.global_argv[0],
7542 G.global_argv + 1,
7543 argv);
7544#endif
7545}
7546
7547
7548static void execvp_or_die(char **argv) NORETURN;
7549static void execvp_or_die(char **argv)
7550{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007551 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007552 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007553 /* Don't propagate SIG_IGN to the child */
7554 if (SPECIAL_JOBSTOP_SIGS != 0)
7555 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007556 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007557 e = 2;
7558 if (errno == EACCES) e = 126;
7559 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007560 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007561 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007562}
7563
7564#if ENABLE_HUSH_MODE_X
7565static void dump_cmd_in_x_mode(char **argv)
7566{
7567 if (G_x_mode && argv) {
7568 /* We want to output the line in one write op */
7569 char *buf, *p;
7570 int len;
7571 int n;
7572
7573 len = 3;
7574 n = 0;
7575 while (argv[n])
7576 len += strlen(argv[n++]) + 1;
7577 buf = xmalloc(len);
7578 buf[0] = '+';
7579 p = buf + 1;
7580 n = 0;
7581 while (argv[n])
7582 p += sprintf(p, " %s", argv[n++]);
7583 *p++ = '\n';
7584 *p = '\0';
7585 fputs(buf, stderr);
7586 free(buf);
7587 }
7588}
7589#else
7590# define dump_cmd_in_x_mode(argv) ((void)0)
7591#endif
7592
Denys Vlasenko57000292018-01-12 14:41:45 +01007593#if ENABLE_HUSH_COMMAND
7594static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7595{
7596 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007597
Denys Vlasenko57000292018-01-12 14:41:45 +01007598 if (!opt_vV)
7599 return;
7600
7601 to_free = NULL;
7602 if (!explanation) {
7603 char *path = getenv("PATH");
7604 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007605 if (!explanation)
7606 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007607 if (opt_vV != 'V')
7608 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7609 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007610 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007611 free(to_free);
7612 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007613 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007614}
7615#else
7616# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7617#endif
7618
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007619#if BB_MMU
7620#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7621 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7622#define pseudo_exec(nommu_save, command, argv_expanded) \
7623 pseudo_exec(command, argv_expanded)
7624#endif
7625
7626/* Called after [v]fork() in run_pipe, or from builtin_exec.
7627 * Never returns.
7628 * Don't exit() here. If you don't exec, use _exit instead.
7629 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007630 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007631 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007632static void pseudo_exec_argv(nommu_save_t *nommu_save,
7633 char **argv, int assignment_cnt,
7634 char **argv_expanded) NORETURN;
7635static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7636 char **argv, int assignment_cnt,
7637 char **argv_expanded)
7638{
Denys Vlasenko57000292018-01-12 14:41:45 +01007639 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007640 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007641 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007642 IF_HUSH_COMMAND(char opt_vV = 0;)
7643 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007644
7645 new_env = expand_assignments(argv, assignment_cnt);
7646 dump_cmd_in_x_mode(new_env);
7647
7648 if (!argv[assignment_cnt]) {
7649 /* Case when we are here: ... | var=val | ...
7650 * (note that we do not exit early, i.e., do not optimize out
7651 * expand_assignments(): think about ... | var=`sleep 1` | ...
7652 */
7653 free_strings(new_env);
7654 _exit(EXIT_SUCCESS);
7655 }
7656
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007657 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007658#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007659 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007660#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007661 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007662 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007663#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007664 set_vars_and_save_old(new_env);
7665 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007666
7667 if (argv_expanded) {
7668 argv = argv_expanded;
7669 } else {
7670 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7671#if !BB_MMU
7672 nommu_save->argv = argv;
7673#endif
7674 }
7675 dump_cmd_in_x_mode(argv);
7676
7677#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7678 if (strchr(argv[0], '/') != NULL)
7679 goto skip;
7680#endif
7681
Denys Vlasenko75481d32017-07-31 05:27:09 +02007682#if ENABLE_HUSH_FUNCTIONS
7683 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007684 funcp = find_function(argv[0]);
7685 if (funcp)
7686 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007687#endif
7688
Denys Vlasenko57000292018-01-12 14:41:45 +01007689#if ENABLE_HUSH_COMMAND
7690 /* "command BAR": run BAR without looking it up among functions
7691 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7692 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7693 */
7694 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7695 char *p;
7696
7697 argv++;
7698 p = *argv;
7699 if (p[0] != '-' || !p[1])
7700 continue; /* bash allows "command command command [-OPT] BAR" */
7701
7702 for (;;) {
7703 p++;
7704 switch (*p) {
7705 case '\0':
7706 argv++;
7707 p = *argv;
7708 if (p[0] != '-' || !p[1])
7709 goto after_opts;
7710 continue; /* next arg is also -opts, process it too */
7711 case 'v':
7712 case 'V':
7713 opt_vV = *p;
7714 continue;
7715 default:
7716 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7717 }
7718 }
7719 }
7720 after_opts:
7721# if ENABLE_HUSH_FUNCTIONS
7722 if (opt_vV && find_function(argv[0]))
7723 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7724# endif
7725#endif
7726
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007727 /* Check if the command matches any of the builtins.
7728 * Depending on context, this might be redundant. But it's
7729 * easier to waste a few CPU cycles than it is to figure out
7730 * if this is one of those cases.
7731 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007732 /* Why "BB_MMU ? :" difference in logic? -
7733 * On NOMMU, it is more expensive to re-execute shell
7734 * just in order to run echo or test builtin.
7735 * It's better to skip it here and run corresponding
7736 * non-builtin later. */
7737 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7738 if (x) {
7739 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7740 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007741 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742
7743#if ENABLE_FEATURE_SH_STANDALONE
7744 /* Check if the command matches any busybox applets */
7745 {
7746 int a = find_applet_by_name(argv[0]);
7747 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007748 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007749# if BB_MMU /* see above why on NOMMU it is not allowed */
7750 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007751 /* Do not leak open fds from opened script files etc.
7752 * Testcase: interactive "ls -l /proc/self/fd"
7753 * should not show tty fd open.
7754 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007755 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007756//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007757//This casuses test failures in
7758//redir_children_should_not_see_saved_fd_2.tests
7759//redir_children_should_not_see_saved_fd_3.tests
7760//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007761 /* Without this, "rm -i FILE" can't be ^C'ed: */
7762 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007763 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007764 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007765 }
7766# endif
7767 /* Re-exec ourselves */
7768 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007769 /* Don't propagate SIG_IGN to the child */
7770 if (SPECIAL_JOBSTOP_SIGS != 0)
7771 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007772 execv(bb_busybox_exec_path, argv);
7773 /* If they called chroot or otherwise made the binary no longer
7774 * executable, fall through */
7775 }
7776 }
7777#endif
7778
7779#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7780 skip:
7781#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007782 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007783 execvp_or_die(argv);
7784}
7785
7786/* Called after [v]fork() in run_pipe
7787 */
7788static void pseudo_exec(nommu_save_t *nommu_save,
7789 struct command *command,
7790 char **argv_expanded) NORETURN;
7791static void pseudo_exec(nommu_save_t *nommu_save,
7792 struct command *command,
7793 char **argv_expanded)
7794{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007795#if ENABLE_HUSH_FUNCTIONS
7796 if (command->cmd_type == CMD_FUNCDEF) {
7797 /* Ignore funcdefs in pipes:
7798 * true | f() { cmd }
7799 */
7800 _exit(0);
7801 }
7802#endif
7803
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007804 if (command->argv) {
7805 pseudo_exec_argv(nommu_save, command->argv,
7806 command->assignment_cnt, argv_expanded);
7807 }
7808
7809 if (command->group) {
7810 /* Cases when we are here:
7811 * ( list )
7812 * { list } &
7813 * ... | ( list ) | ...
7814 * ... | { list } | ...
7815 */
7816#if BB_MMU
7817 int rcode;
7818 debug_printf_exec("pseudo_exec: run_list\n");
7819 reset_traps_to_defaults();
7820 rcode = run_list(command->group);
7821 /* OK to leak memory by not calling free_pipe_list,
7822 * since this process is about to exit */
7823 _exit(rcode);
7824#else
7825 re_execute_shell(&nommu_save->argv_from_re_execing,
7826 command->group_as_string,
7827 G.global_argv[0],
7828 G.global_argv + 1,
7829 NULL);
7830#endif
7831 }
7832
7833 /* Case when we are here: ... | >file */
7834 debug_printf_exec("pseudo_exec'ed null command\n");
7835 _exit(EXIT_SUCCESS);
7836}
7837
7838#if ENABLE_HUSH_JOB
7839static const char *get_cmdtext(struct pipe *pi)
7840{
7841 char **argv;
7842 char *p;
7843 int len;
7844
7845 /* This is subtle. ->cmdtext is created only on first backgrounding.
7846 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7847 * On subsequent bg argv is trashed, but we won't use it */
7848 if (pi->cmdtext)
7849 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007850
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007851 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007852 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007853 pi->cmdtext = xzalloc(1);
7854 return pi->cmdtext;
7855 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007856 len = 0;
7857 do {
7858 len += strlen(*argv) + 1;
7859 } while (*++argv);
7860 p = xmalloc(len);
7861 pi->cmdtext = p;
7862 argv = pi->cmds[0].argv;
7863 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007864 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007865 *p++ = ' ';
7866 } while (*++argv);
7867 p[-1] = '\0';
7868 return pi->cmdtext;
7869}
7870
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007871static void remove_job_from_table(struct pipe *pi)
7872{
7873 struct pipe *prev_pipe;
7874
7875 if (pi == G.job_list) {
7876 G.job_list = pi->next;
7877 } else {
7878 prev_pipe = G.job_list;
7879 while (prev_pipe->next != pi)
7880 prev_pipe = prev_pipe->next;
7881 prev_pipe->next = pi->next;
7882 }
7883 G.last_jobid = 0;
7884 if (G.job_list)
7885 G.last_jobid = G.job_list->jobid;
7886}
7887
7888static void delete_finished_job(struct pipe *pi)
7889{
7890 remove_job_from_table(pi);
7891 free_pipe(pi);
7892}
7893
7894static void clean_up_last_dead_job(void)
7895{
7896 if (G.job_list && !G.job_list->alive_cmds)
7897 delete_finished_job(G.job_list);
7898}
7899
Denys Vlasenko16096292017-07-10 10:00:28 +02007900static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007901{
7902 struct pipe *job, **jobp;
7903 int i;
7904
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007905 clean_up_last_dead_job();
7906
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007907 /* Find the end of the list, and find next job ID to use */
7908 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007909 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007910 while ((job = *jobp) != NULL) {
7911 if (job->jobid > i)
7912 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007913 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007914 }
7915 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007916
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007917 /* Create a new job struct at the end */
7918 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007919 job->next = NULL;
7920 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7921 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7922 for (i = 0; i < pi->num_cmds; i++) {
7923 job->cmds[i].pid = pi->cmds[i].pid;
7924 /* all other fields are not used and stay zero */
7925 }
7926 job->cmdtext = xstrdup(get_cmdtext(pi));
7927
7928 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007929 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007930 G.last_jobid = job->jobid;
7931}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007932#endif /* JOB */
7933
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007934static int job_exited_or_stopped(struct pipe *pi)
7935{
7936 int rcode, i;
7937
7938 if (pi->alive_cmds != pi->stopped_cmds)
7939 return -1;
7940
7941 /* All processes in fg pipe have exited or stopped */
7942 rcode = 0;
7943 i = pi->num_cmds;
7944 while (--i >= 0) {
7945 rcode = pi->cmds[i].cmd_exitcode;
7946 /* usually last process gives overall exitstatus,
7947 * but with "set -o pipefail", last *failed* process does */
7948 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7949 break;
7950 }
7951 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7952 return rcode;
7953}
7954
Denys Vlasenko7e675362016-10-28 21:57:31 +02007955static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007956{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007957#if ENABLE_HUSH_JOB
7958 struct pipe *pi;
7959#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007960 int i, dead;
7961
7962 dead = WIFEXITED(status) || WIFSIGNALED(status);
7963
7964#if DEBUG_JOBS
7965 if (WIFSTOPPED(status))
7966 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7967 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7968 if (WIFSIGNALED(status))
7969 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7970 childpid, WTERMSIG(status), WEXITSTATUS(status));
7971 if (WIFEXITED(status))
7972 debug_printf_jobs("pid %d exited, exitcode %d\n",
7973 childpid, WEXITSTATUS(status));
7974#endif
7975 /* Were we asked to wait for a fg pipe? */
7976 if (fg_pipe) {
7977 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007978
Denys Vlasenko7e675362016-10-28 21:57:31 +02007979 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007980 int rcode;
7981
Denys Vlasenko7e675362016-10-28 21:57:31 +02007982 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7983 if (fg_pipe->cmds[i].pid != childpid)
7984 continue;
7985 if (dead) {
7986 int ex;
7987 fg_pipe->cmds[i].pid = 0;
7988 fg_pipe->alive_cmds--;
7989 ex = WEXITSTATUS(status);
7990 /* bash prints killer signal's name for *last*
7991 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7992 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7993 */
7994 if (WIFSIGNALED(status)) {
7995 int sig = WTERMSIG(status);
7996 if (i == fg_pipe->num_cmds-1)
7997 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7998 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7999 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8000 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8001 * Maybe we need to use sig | 128? */
8002 ex = sig + 128;
8003 }
8004 fg_pipe->cmds[i].cmd_exitcode = ex;
8005 } else {
8006 fg_pipe->stopped_cmds++;
8007 }
8008 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8009 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008010 rcode = job_exited_or_stopped(fg_pipe);
8011 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008012/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8013 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8014 * and "killall -STOP cat" */
8015 if (G_interactive_fd) {
8016#if ENABLE_HUSH_JOB
8017 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008018 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008019#endif
8020 return rcode;
8021 }
8022 if (fg_pipe->alive_cmds == 0)
8023 return rcode;
8024 }
8025 /* There are still running processes in the fg_pipe */
8026 return -1;
8027 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008028 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008029 }
8030
8031#if ENABLE_HUSH_JOB
8032 /* We were asked to wait for bg or orphaned children */
8033 /* No need to remember exitcode in this case */
8034 for (pi = G.job_list; pi; pi = pi->next) {
8035 for (i = 0; i < pi->num_cmds; i++) {
8036 if (pi->cmds[i].pid == childpid)
8037 goto found_pi_and_prognum;
8038 }
8039 }
8040 /* Happens when shell is used as init process (init=/bin/sh) */
8041 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8042 return -1; /* this wasn't a process from fg_pipe */
8043
8044 found_pi_and_prognum:
8045 if (dead) {
8046 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008047 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008048 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008049 rcode = 128 + WTERMSIG(status);
8050 pi->cmds[i].cmd_exitcode = rcode;
8051 if (G.last_bg_pid == pi->cmds[i].pid)
8052 G.last_bg_pid_exitcode = rcode;
8053 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008054 pi->alive_cmds--;
8055 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008056 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008057 printf(JOB_STATUS_FORMAT, pi->jobid,
8058 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008059 delete_finished_job(pi);
8060 } else {
8061/*
8062 * bash deletes finished jobs from job table only in interactive mode,
8063 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8064 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8065 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8066 * We only retain one "dead" job, if it's the single job on the list.
8067 * This covers most of real-world scenarios where this is useful.
8068 */
8069 if (pi != G.job_list)
8070 delete_finished_job(pi);
8071 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008072 }
8073 } else {
8074 /* child stopped */
8075 pi->stopped_cmds++;
8076 }
8077#endif
8078 return -1; /* this wasn't a process from fg_pipe */
8079}
8080
8081/* Check to see if any processes have exited -- if they have,
8082 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008083 *
8084 * If non-NULL fg_pipe: wait for its completion or stop.
8085 * Return its exitcode or zero if stopped.
8086 *
8087 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8088 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8089 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8090 * or 0 if no children changed status.
8091 *
8092 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8093 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8094 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008095 */
8096static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8097{
8098 int attributes;
8099 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008100 int rcode = 0;
8101
8102 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8103
8104 attributes = WUNTRACED;
8105 if (fg_pipe == NULL)
8106 attributes |= WNOHANG;
8107
8108 errno = 0;
8109#if ENABLE_HUSH_FAST
8110 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8111//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8112//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8113 /* There was neither fork nor SIGCHLD since last waitpid */
8114 /* Avoid doing waitpid syscall if possible */
8115 if (!G.we_have_children) {
8116 errno = ECHILD;
8117 return -1;
8118 }
8119 if (fg_pipe == NULL) { /* is WNOHANG set? */
8120 /* We have children, but they did not exit
8121 * or stop yet (we saw no SIGCHLD) */
8122 return 0;
8123 }
8124 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8125 }
8126#endif
8127
8128/* Do we do this right?
8129 * bash-3.00# sleep 20 | false
8130 * <ctrl-Z pressed>
8131 * [3]+ Stopped sleep 20 | false
8132 * bash-3.00# echo $?
8133 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8134 * [hush 1.14.0: yes we do it right]
8135 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008136 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008137 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008138#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008139 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008140 i = G.count_SIGCHLD;
8141#endif
8142 childpid = waitpid(-1, &status, attributes);
8143 if (childpid <= 0) {
8144 if (childpid && errno != ECHILD)
8145 bb_perror_msg("waitpid");
8146#if ENABLE_HUSH_FAST
8147 else { /* Until next SIGCHLD, waitpid's are useless */
8148 G.we_have_children = (childpid == 0);
8149 G.handled_SIGCHLD = i;
8150//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8151 }
8152#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008153 /* ECHILD (no children), or 0 (no change in children status) */
8154 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008155 break;
8156 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008157 rcode = process_wait_result(fg_pipe, childpid, status);
8158 if (rcode >= 0) {
8159 /* fg_pipe exited or stopped */
8160 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008161 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008162 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008163 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008164 rcode = WEXITSTATUS(status);
8165 if (WIFSIGNALED(status))
8166 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008167 if (WIFSTOPPED(status))
8168 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8169 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008170 rcode++;
8171 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008172 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008173 /* This wasn't one of our processes, or */
8174 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008175 } /* while (waitpid succeeds)... */
8176
8177 return rcode;
8178}
8179
8180#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008181static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008182{
8183 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008184 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008185 if (G_saved_tty_pgrp) {
8186 /* Job finished, move the shell to the foreground */
8187 p = getpgrp(); /* our process group id */
8188 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8189 tcsetpgrp(G_interactive_fd, p);
8190 }
8191 return rcode;
8192}
8193#endif
8194
8195/* Start all the jobs, but don't wait for anything to finish.
8196 * See checkjobs().
8197 *
8198 * Return code is normally -1, when the caller has to wait for children
8199 * to finish to determine the exit status of the pipe. If the pipe
8200 * is a simple builtin command, however, the action is done by the
8201 * time run_pipe returns, and the exit code is provided as the
8202 * return value.
8203 *
8204 * Returns -1 only if started some children. IOW: we have to
8205 * mask out retvals of builtins etc with 0xff!
8206 *
8207 * The only case when we do not need to [v]fork is when the pipe
8208 * is single, non-backgrounded, non-subshell command. Examples:
8209 * cmd ; ... { list } ; ...
8210 * cmd && ... { list } && ...
8211 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008212 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008213 * or (if SH_STANDALONE) an applet, and we can run the { list }
8214 * with run_list. If it isn't one of these, we fork and exec cmd.
8215 *
8216 * Cases when we must fork:
8217 * non-single: cmd | cmd
8218 * backgrounded: cmd & { list } &
8219 * subshell: ( list ) [&]
8220 */
8221#if !ENABLE_HUSH_MODE_X
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008222#define redirect_and_varexp_helper(old_vars_p, command, squirrel, argv_expanded) \
8223 redirect_and_varexp_helper(old_vars_p, command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008224#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008225static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008226 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008227 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008228 char **argv_expanded)
8229{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008230 /* Assignments occur before redirects. Try:
8231 * a=`sleep 1` sleep 2 3>/qwe/rty
8232 */
8233
8234 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8235 dump_cmd_in_x_mode(new_env);
8236 dump_cmd_in_x_mode(argv_expanded);
8237 /* this takes ownership of new_env[i] elements, and frees new_env: */
8238 set_vars_and_save_old(new_env);
8239
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008240 /* setup_redirects acts on file descriptors, not FILEs.
8241 * This is perfect for work that comes after exec().
8242 * Is it really safe for inline use? Experimentally,
8243 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008244 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008245}
8246static NOINLINE int run_pipe(struct pipe *pi)
8247{
8248 static const char *const null_ptr = NULL;
8249
8250 int cmd_no;
8251 int next_infd;
8252 struct command *command;
8253 char **argv_expanded;
8254 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008255 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008256 int rcode;
8257
8258 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8259 debug_enter();
8260
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008261 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8262 * Result should be 3 lines: q w e, qwe, q w e
8263 */
8264 G.ifs = get_local_var_value("IFS");
8265 if (!G.ifs)
8266 G.ifs = defifs;
8267
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008268 IF_HUSH_JOB(pi->pgrp = -1;)
8269 pi->stopped_cmds = 0;
8270 command = &pi->cmds[0];
8271 argv_expanded = NULL;
8272
8273 if (pi->num_cmds != 1
8274 || pi->followup == PIPE_BG
8275 || command->cmd_type == CMD_SUBSHELL
8276 ) {
8277 goto must_fork;
8278 }
8279
8280 pi->alive_cmds = 1;
8281
8282 debug_printf_exec(": group:%p argv:'%s'\n",
8283 command->group, command->argv ? command->argv[0] : "NONE");
8284
8285 if (command->group) {
8286#if ENABLE_HUSH_FUNCTIONS
8287 if (command->cmd_type == CMD_FUNCDEF) {
8288 /* "executing" func () { list } */
8289 struct function *funcp;
8290
8291 funcp = new_function(command->argv[0]);
8292 /* funcp->name is already set to argv[0] */
8293 funcp->body = command->group;
8294# if !BB_MMU
8295 funcp->body_as_string = command->group_as_string;
8296 command->group_as_string = NULL;
8297# endif
8298 command->group = NULL;
8299 command->argv[0] = NULL;
8300 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8301 funcp->parent_cmd = command;
8302 command->child_func = funcp;
8303
8304 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8305 debug_leave();
8306 return EXIT_SUCCESS;
8307 }
8308#endif
8309 /* { list } */
8310 debug_printf("non-subshell group\n");
8311 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008312 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008313 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008314//FIXME: we need to pass squirrel down into run_list()
8315//for SH_STANDALONE case, or else this construct:
8316// { find /proc/self/fd; true; } >FILE; cmd2
8317//has no way of closing saved fd#1 for "find",
8318//and in SH_STANDALONE mode, "find" is not execed,
8319//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008320 rcode = run_list(command->group) & 0xff;
8321 }
8322 restore_redirects(squirrel);
8323 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8324 debug_leave();
8325 debug_printf_exec("run_pipe: return %d\n", rcode);
8326 return rcode;
8327 }
8328
8329 argv = command->argv ? command->argv : (char **) &null_ptr;
8330 {
8331 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008332 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8333 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008334 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008335 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008336
Denys Vlasenko5807e182018-02-08 19:19:04 +01008337#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008338 if (G.lineno_var)
8339 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8340#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008341
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008342 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008343 /* Assignments, but no command.
8344 * Ensure redirects take effect (that is, create files).
8345 * Try "a=t >file"
8346 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008347 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008348 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008349 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008350 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008351 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008352
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008353 /* Set shell variables */
8354 if (G_x_mode)
8355 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008356 i = 0;
8357 while (i < command->assignment_cnt) {
8358 char *p = expand_string_to_string(argv[i], /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008359 if (G_x_mode)
8360 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008361 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008362 if (set_local_var(p, /*flag:*/ 0)) {
8363 /* assignment to readonly var / putenv error? */
8364 rcode = 1;
8365 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008366 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008367 }
8368 if (G_x_mode)
8369 bb_putchar_stderr('\n');
8370 /* Redirect error sets $? to 1. Otherwise,
8371 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008372 * Else, clear $?:
8373 * false; q=`exit 2`; echo $? - should print 2
8374 * false; x=1; echo $? - should print 0
8375 * Because of the 2nd case, we can't just use G.last_exitcode.
8376 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008377 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008378 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008379 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8380 debug_leave();
8381 debug_printf_exec("run_pipe: return %d\n", rcode);
8382 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008383 }
8384
8385 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008386#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008387 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008388 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008389 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008390#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008391 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008392
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008393 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008394 if (!argv_expanded[0]) {
8395 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008396 /* `false` still has to set exitcode 1 */
8397 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008398 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008399 }
8400
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008401 old_vars = NULL;
8402 sv_shadowed = G.shadowed_vars_pp;
8403
Denys Vlasenko75481d32017-07-31 05:27:09 +02008404 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008405 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8406 IF_HUSH_FUNCTIONS(x = NULL;)
8407 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008408 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008409 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008410 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8411 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008412 /*
8413 * Variable assignments are executed, but then "forgotten":
8414 * a=`sleep 1;echo A` exec 3>&-; echo $a
8415 * sleeps, but prints nothing.
8416 */
8417 enter_var_nest_level();
8418 G.shadowed_vars_pp = &old_vars;
8419 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8420 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008421 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008422
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008423 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008424 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008425
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008426 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008427 * a=b true; env | grep ^a=
8428 */
8429 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008430 /* Collect all variables "shadowed" by helper
8431 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8432 * into old_vars list:
8433 */
8434 G.shadowed_vars_pp = &old_vars;
8435 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008436 if (rcode == 0) {
8437 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008438 /* Do not collect *to old_vars list* vars shadowed
8439 * by e.g. "local VAR" builtin (collect them
8440 * in the previously nested list instead):
8441 * don't want them to be restored immediately
8442 * after "local" completes.
8443 */
8444 G.shadowed_vars_pp = sv_shadowed;
8445
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008446 debug_printf_exec(": builtin '%s' '%s'...\n",
8447 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008448 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008449 rcode = x->b_function(argv_expanded) & 0xff;
8450 fflush_all();
8451 }
8452#if ENABLE_HUSH_FUNCTIONS
8453 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008454 debug_printf_exec(": function '%s' '%s'...\n",
8455 funcp->name, argv_expanded[1]);
8456 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008457 /*
8458 * But do collect *to old_vars list* vars shadowed
8459 * within function execution. To that end, restore
8460 * this pointer _after_ function run:
8461 */
8462 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008463 }
8464#endif
8465 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008466 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008467 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008468 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008469 if (n < 0 || !APPLET_IS_NOFORK(n))
8470 goto must_fork;
8471
8472 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008473 /* Collect all variables "shadowed" by helper into old_vars list */
8474 G.shadowed_vars_pp = &old_vars;
8475 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8476 G.shadowed_vars_pp = sv_shadowed;
8477
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008478 if (rcode == 0) {
8479 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8480 argv_expanded[0], argv_expanded[1]);
8481 /*
8482 * Note: signals (^C) can't interrupt here.
8483 * We remember them and they will be acted upon
8484 * after applet returns.
8485 * This makes applets which can run for a long time
8486 * and/or wait for user input ineligible for NOFORK:
8487 * for example, "yes" or "rm" (rm -i waits for input).
8488 */
8489 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008490 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008491 } else
8492 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008493
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008494 restore_redirects(squirrel);
8495 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008496 leave_var_nest_level();
8497 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008498
8499 /*
8500 * Try "usleep 99999999" + ^C + "echo $?"
8501 * with FEATURE_SH_NOFORK=y.
8502 */
8503 if (!funcp) {
8504 /* It was builtin or nofork.
8505 * if this would be a real fork/execed program,
8506 * it should have died if a fatal sig was received.
8507 * But OTOH, there was no separate process,
8508 * the sig was sent to _shell_, not to non-existing
8509 * child.
8510 * Let's just handle ^C only, this one is obvious:
8511 * we aren't ok with exitcode 0 when ^C was pressed
8512 * during builtin/nofork.
8513 */
8514 if (sigismember(&G.pending_set, SIGINT))
8515 rcode = 128 + SIGINT;
8516 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008517 free(argv_expanded);
8518 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8519 debug_leave();
8520 debug_printf_exec("run_pipe return %d\n", rcode);
8521 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008522 }
8523
8524 must_fork:
8525 /* NB: argv_expanded may already be created, and that
8526 * might include `cmd` runs! Do not rerun it! We *must*
8527 * use argv_expanded if it's non-NULL */
8528
8529 /* Going to fork a child per each pipe member */
8530 pi->alive_cmds = 0;
8531 next_infd = 0;
8532
8533 cmd_no = 0;
8534 while (cmd_no < pi->num_cmds) {
8535 struct fd_pair pipefds;
8536#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008537 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008538 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008539 nommu_save.old_vars = NULL;
8540 nommu_save.argv = NULL;
8541 nommu_save.argv_from_re_execing = NULL;
8542#endif
8543 command = &pi->cmds[cmd_no];
8544 cmd_no++;
8545 if (command->argv) {
8546 debug_printf_exec(": pipe member '%s' '%s'...\n",
8547 command->argv[0], command->argv[1]);
8548 } else {
8549 debug_printf_exec(": pipe member with no argv\n");
8550 }
8551
8552 /* pipes are inserted between pairs of commands */
8553 pipefds.rd = 0;
8554 pipefds.wr = 1;
8555 if (cmd_no < pi->num_cmds)
8556 xpiped_pair(pipefds);
8557
Denys Vlasenko5807e182018-02-08 19:19:04 +01008558#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008559 if (G.lineno_var)
8560 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8561#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008562
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008563 command->pid = BB_MMU ? fork() : vfork();
8564 if (!command->pid) { /* child */
8565#if ENABLE_HUSH_JOB
8566 disable_restore_tty_pgrp_on_exit();
8567 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8568
8569 /* Every child adds itself to new process group
8570 * with pgid == pid_of_first_child_in_pipe */
8571 if (G.run_list_level == 1 && G_interactive_fd) {
8572 pid_t pgrp;
8573 pgrp = pi->pgrp;
8574 if (pgrp < 0) /* true for 1st process only */
8575 pgrp = getpid();
8576 if (setpgid(0, pgrp) == 0
8577 && pi->followup != PIPE_BG
8578 && G_saved_tty_pgrp /* we have ctty */
8579 ) {
8580 /* We do it in *every* child, not just first,
8581 * to avoid races */
8582 tcsetpgrp(G_interactive_fd, pgrp);
8583 }
8584 }
8585#endif
8586 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8587 /* 1st cmd in backgrounded pipe
8588 * should have its stdin /dev/null'ed */
8589 close(0);
8590 if (open(bb_dev_null, O_RDONLY))
8591 xopen("/", O_RDONLY);
8592 } else {
8593 xmove_fd(next_infd, 0);
8594 }
8595 xmove_fd(pipefds.wr, 1);
8596 if (pipefds.rd > 1)
8597 close(pipefds.rd);
8598 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008599 * and the pipe fd (fd#1) is available for dup'ing:
8600 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8601 * of cmd1 goes into pipe.
8602 */
8603 if (setup_redirects(command, NULL)) {
8604 /* Happens when redir file can't be opened:
8605 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8606 * FOO
8607 * hush: can't open '/qwe/rty': No such file or directory
8608 * BAZ
8609 * (echo BAR is not executed, it hits _exit(1) below)
8610 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008611 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008612 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008613
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008614 /* Stores to nommu_save list of env vars putenv'ed
8615 * (NOMMU, on MMU we don't need that) */
8616 /* cast away volatility... */
8617 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8618 /* pseudo_exec() does not return */
8619 }
8620
8621 /* parent or error */
8622#if ENABLE_HUSH_FAST
8623 G.count_SIGCHLD++;
8624//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8625#endif
8626 enable_restore_tty_pgrp_on_exit();
8627#if !BB_MMU
8628 /* Clean up after vforked child */
8629 free(nommu_save.argv);
8630 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008631 G.var_nest_level = sv_var_nest_level;
8632 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008633 add_vars(nommu_save.old_vars);
8634#endif
8635 free(argv_expanded);
8636 argv_expanded = NULL;
8637 if (command->pid < 0) { /* [v]fork failed */
8638 /* Clearly indicate, was it fork or vfork */
8639 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8640 } else {
8641 pi->alive_cmds++;
8642#if ENABLE_HUSH_JOB
8643 /* Second and next children need to know pid of first one */
8644 if (pi->pgrp < 0)
8645 pi->pgrp = command->pid;
8646#endif
8647 }
8648
8649 if (cmd_no > 1)
8650 close(next_infd);
8651 if (cmd_no < pi->num_cmds)
8652 close(pipefds.wr);
8653 /* Pass read (output) pipe end to next iteration */
8654 next_infd = pipefds.rd;
8655 }
8656
8657 if (!pi->alive_cmds) {
8658 debug_leave();
8659 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8660 return 1;
8661 }
8662
8663 debug_leave();
8664 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8665 return -1;
8666}
8667
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008668/* NB: called by pseudo_exec, and therefore must not modify any
8669 * global data until exec/_exit (we can be a child after vfork!) */
8670static int run_list(struct pipe *pi)
8671{
8672#if ENABLE_HUSH_CASE
8673 char *case_word = NULL;
8674#endif
8675#if ENABLE_HUSH_LOOPS
8676 struct pipe *loop_top = NULL;
8677 char **for_lcur = NULL;
8678 char **for_list = NULL;
8679#endif
8680 smallint last_followup;
8681 smalluint rcode;
8682#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8683 smalluint cond_code = 0;
8684#else
8685 enum { cond_code = 0 };
8686#endif
8687#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008688 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008689 smallint last_rword; /* ditto */
8690#endif
8691
8692 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8693 debug_enter();
8694
8695#if ENABLE_HUSH_LOOPS
8696 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008697 {
8698 struct pipe *cpipe;
8699 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8700 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8701 continue;
8702 /* current word is FOR or IN (BOLD in comments below) */
8703 if (cpipe->next == NULL) {
8704 syntax_error("malformed for");
8705 debug_leave();
8706 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8707 return 1;
8708 }
8709 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8710 if (cpipe->next->res_word == RES_DO)
8711 continue;
8712 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8713 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8714 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8715 ) {
8716 syntax_error("malformed for");
8717 debug_leave();
8718 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8719 return 1;
8720 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008721 }
8722 }
8723#endif
8724
8725 /* Past this point, all code paths should jump to ret: label
8726 * in order to return, no direct "return" statements please.
8727 * This helps to ensure that no memory is leaked. */
8728
8729#if ENABLE_HUSH_JOB
8730 G.run_list_level++;
8731#endif
8732
8733#if HAS_KEYWORDS
8734 rword = RES_NONE;
8735 last_rword = RES_XXXX;
8736#endif
8737 last_followup = PIPE_SEQ;
8738 rcode = G.last_exitcode;
8739
8740 /* Go through list of pipes, (maybe) executing them. */
8741 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008742 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008743 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008744
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008745 if (G.flag_SIGINT)
8746 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008747 if (G_flag_return_in_progress == 1)
8748 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008749
8750 IF_HAS_KEYWORDS(rword = pi->res_word;)
8751 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8752 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008753
8754 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008755 if (
8756#if ENABLE_HUSH_IF
8757 rword == RES_IF || rword == RES_ELIF ||
8758#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008759 pi->followup != PIPE_SEQ
8760 ) {
8761 G.errexit_depth++;
8762 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008763#if ENABLE_HUSH_LOOPS
8764 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8765 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8766 ) {
8767 /* start of a loop: remember where loop starts */
8768 loop_top = pi;
8769 G.depth_of_loop++;
8770 }
8771#endif
8772 /* Still in the same "if...", "then..." or "do..." branch? */
8773 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8774 if ((rcode == 0 && last_followup == PIPE_OR)
8775 || (rcode != 0 && last_followup == PIPE_AND)
8776 ) {
8777 /* It is "<true> || CMD" or "<false> && CMD"
8778 * and we should not execute CMD */
8779 debug_printf_exec("skipped cmd because of || or &&\n");
8780 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008781 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008782 }
8783 }
8784 last_followup = pi->followup;
8785 IF_HAS_KEYWORDS(last_rword = rword;)
8786#if ENABLE_HUSH_IF
8787 if (cond_code) {
8788 if (rword == RES_THEN) {
8789 /* if false; then ... fi has exitcode 0! */
8790 G.last_exitcode = rcode = EXIT_SUCCESS;
8791 /* "if <false> THEN cmd": skip cmd */
8792 continue;
8793 }
8794 } else {
8795 if (rword == RES_ELSE || rword == RES_ELIF) {
8796 /* "if <true> then ... ELSE/ELIF cmd":
8797 * skip cmd and all following ones */
8798 break;
8799 }
8800 }
8801#endif
8802#if ENABLE_HUSH_LOOPS
8803 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8804 if (!for_lcur) {
8805 /* first loop through for */
8806
8807 static const char encoded_dollar_at[] ALIGN1 = {
8808 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8809 }; /* encoded representation of "$@" */
8810 static const char *const encoded_dollar_at_argv[] = {
8811 encoded_dollar_at, NULL
8812 }; /* argv list with one element: "$@" */
8813 char **vals;
8814
8815 vals = (char**)encoded_dollar_at_argv;
8816 if (pi->next->res_word == RES_IN) {
8817 /* if no variable values after "in" we skip "for" */
8818 if (!pi->next->cmds[0].argv) {
8819 G.last_exitcode = rcode = EXIT_SUCCESS;
8820 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8821 break;
8822 }
8823 vals = pi->next->cmds[0].argv;
8824 } /* else: "for var; do..." -> assume "$@" list */
8825 /* create list of variable values */
8826 debug_print_strings("for_list made from", vals);
8827 for_list = expand_strvec_to_strvec(vals);
8828 for_lcur = for_list;
8829 debug_print_strings("for_list", for_list);
8830 }
8831 if (!*for_lcur) {
8832 /* "for" loop is over, clean up */
8833 free(for_list);
8834 for_list = NULL;
8835 for_lcur = NULL;
8836 break;
8837 }
8838 /* Insert next value from for_lcur */
8839 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008840 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008841 continue;
8842 }
8843 if (rword == RES_IN) {
8844 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8845 }
8846 if (rword == RES_DONE) {
8847 continue; /* "done" has no cmds too */
8848 }
8849#endif
8850#if ENABLE_HUSH_CASE
8851 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008852 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02008853 case_word = expand_string_to_string(pi->cmds->argv[0], 1);
8854 debug_printf_exec("CASE word1:'%s'\n", case_word);
8855 //unbackslash(case_word);
8856 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008857 continue;
8858 }
8859 if (rword == RES_MATCH) {
8860 char **argv;
8861
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008862 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008863 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8864 break;
8865 /* all prev words didn't match, does this one match? */
8866 argv = pi->cmds->argv;
8867 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008868 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008869 /* TODO: which FNM_xxx flags to use? */
8870 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008871 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008872 free(pattern);
8873 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008874 free(case_word);
8875 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008876 break;
8877 }
8878 argv++;
8879 }
8880 continue;
8881 }
8882 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008883 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008884 if (cond_code != 0)
8885 continue; /* not matched yet, skip this pipe */
8886 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008887 if (rword == RES_ESAC) {
8888 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8889 if (case_word) {
8890 /* "case" did not match anything: still set $? (to 0) */
8891 G.last_exitcode = rcode = EXIT_SUCCESS;
8892 }
8893 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008894#endif
8895 /* Just pressing <enter> in shell should check for jobs.
8896 * OTOH, in non-interactive shell this is useless
8897 * and only leads to extra job checks */
8898 if (pi->num_cmds == 0) {
8899 if (G_interactive_fd)
8900 goto check_jobs_and_continue;
8901 continue;
8902 }
8903
8904 /* After analyzing all keywords and conditions, we decided
8905 * to execute this pipe. NB: have to do checkjobs(NULL)
8906 * after run_pipe to collect any background children,
8907 * even if list execution is to be stopped. */
8908 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008909#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008910 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008911#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008912 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8913 if (r != -1) {
8914 /* We ran a builtin, function, or group.
8915 * rcode is already known
8916 * and we don't need to wait for anything. */
8917 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8918 G.last_exitcode = rcode;
8919 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008920#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008921 /* Was it "break" or "continue"? */
8922 if (G.flag_break_continue) {
8923 smallint fbc = G.flag_break_continue;
8924 /* We might fall into outer *loop*,
8925 * don't want to break it too */
8926 if (loop_top) {
8927 G.depth_break_continue--;
8928 if (G.depth_break_continue == 0)
8929 G.flag_break_continue = 0;
8930 /* else: e.g. "continue 2" should *break* once, *then* continue */
8931 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8932 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008933 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008934 break;
8935 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008936 /* "continue": simulate end of loop */
8937 rword = RES_DONE;
8938 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008939 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008940#endif
8941 if (G_flag_return_in_progress == 1) {
8942 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8943 break;
8944 }
8945 } else if (pi->followup == PIPE_BG) {
8946 /* What does bash do with attempts to background builtins? */
8947 /* even bash 3.2 doesn't do that well with nested bg:
8948 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8949 * I'm NOT treating inner &'s as jobs */
8950#if ENABLE_HUSH_JOB
8951 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008952 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008953#endif
8954 /* Last command's pid goes to $! */
8955 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008956 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008957 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008958/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008959 rcode = EXIT_SUCCESS;
8960 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008961 } else {
8962#if ENABLE_HUSH_JOB
8963 if (G.run_list_level == 1 && G_interactive_fd) {
8964 /* Waits for completion, then fg's main shell */
8965 rcode = checkjobs_and_fg_shell(pi);
8966 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008967 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008968 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008969#endif
8970 /* This one just waits for completion */
8971 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8972 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8973 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008974 G.last_exitcode = rcode;
8975 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008976 }
8977
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008978 /* Handle "set -e" */
8979 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8980 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8981 if (G.errexit_depth == 0)
8982 hush_exit(rcode);
8983 }
8984 G.errexit_depth = sv_errexit_depth;
8985
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008986 /* Analyze how result affects subsequent commands */
8987#if ENABLE_HUSH_IF
8988 if (rword == RES_IF || rword == RES_ELIF)
8989 cond_code = rcode;
8990#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008991 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008992 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008993 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008994#if ENABLE_HUSH_LOOPS
8995 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008996 if (pi->next
8997 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008998 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008999 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009000 if (rword == RES_WHILE) {
9001 if (rcode) {
9002 /* "while false; do...done" - exitcode 0 */
9003 G.last_exitcode = rcode = EXIT_SUCCESS;
9004 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009005 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009006 }
9007 }
9008 if (rword == RES_UNTIL) {
9009 if (!rcode) {
9010 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009011 break;
9012 }
9013 }
9014 }
9015#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009016 } /* for (pi) */
9017
9018#if ENABLE_HUSH_JOB
9019 G.run_list_level--;
9020#endif
9021#if ENABLE_HUSH_LOOPS
9022 if (loop_top)
9023 G.depth_of_loop--;
9024 free(for_list);
9025#endif
9026#if ENABLE_HUSH_CASE
9027 free(case_word);
9028#endif
9029 debug_leave();
9030 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9031 return rcode;
9032}
9033
9034/* Select which version we will use */
9035static int run_and_free_list(struct pipe *pi)
9036{
9037 int rcode = 0;
9038 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009039 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009040 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9041 rcode = run_list(pi);
9042 }
9043 /* free_pipe_list has the side effect of clearing memory.
9044 * In the long run that function can be merged with run_list,
9045 * but doing that now would hobble the debugging effort. */
9046 free_pipe_list(pi);
9047 debug_printf_exec("run_and_free_list return %d\n", rcode);
9048 return rcode;
9049}
9050
9051
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009052static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009053{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009054 sighandler_t old_handler;
9055 unsigned sig = 0;
9056 while ((mask >>= 1) != 0) {
9057 sig++;
9058 if (!(mask & 1))
9059 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009060 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009061 /* POSIX allows shell to re-enable SIGCHLD
9062 * even if it was SIG_IGN on entry.
9063 * Therefore we skip IGN check for it:
9064 */
9065 if (sig == SIGCHLD)
9066 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009067 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9068 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9069 */
9070 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009071 if (old_handler == SIG_IGN) {
9072 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009073 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009074#if ENABLE_HUSH_TRAP
9075 if (!G_traps)
9076 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9077 free(G_traps[sig]);
9078 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9079#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009080 }
9081 }
9082}
9083
9084/* Called a few times only (or even once if "sh -c") */
9085static void install_special_sighandlers(void)
9086{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009087 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009088
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009089 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009090 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009091 if (G_interactive_fd) {
9092 mask |= SPECIAL_INTERACTIVE_SIGS;
9093 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009094 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009095 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009096 /* Careful, do not re-install handlers we already installed */
9097 if (G.special_sig_mask != mask) {
9098 unsigned diff = mask & ~G.special_sig_mask;
9099 G.special_sig_mask = mask;
9100 install_sighandlers(diff);
9101 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009102}
9103
9104#if ENABLE_HUSH_JOB
9105/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009106/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009107static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009108{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009109 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009110
9111 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009112 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009113 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9114 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009115 + (1 << SIGBUS ) * HUSH_DEBUG
9116 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009117 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009118 + (1 << SIGABRT)
9119 /* bash 3.2 seems to handle these just like 'fatal' ones */
9120 + (1 << SIGPIPE)
9121 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009122 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009123 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009124 * we never want to restore pgrp on exit, and this fn is not called
9125 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009126 /*+ (1 << SIGHUP )*/
9127 /*+ (1 << SIGTERM)*/
9128 /*+ (1 << SIGINT )*/
9129 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009130 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009131
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009132 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009133}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009134#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009135
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009136static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009137{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009138 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009139 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009140 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009141 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009142 break;
9143 case 'x':
9144 IF_HUSH_MODE_X(G_x_mode = state;)
9145 break;
9146 case 'o':
9147 if (!o_opt) {
9148 /* "set -+o" without parameter.
9149 * in bash, set -o produces this output:
9150 * pipefail off
9151 * and set +o:
9152 * set +o pipefail
9153 * We always use the second form.
9154 */
9155 const char *p = o_opt_strings;
9156 idx = 0;
9157 while (*p) {
9158 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9159 idx++;
9160 p += strlen(p) + 1;
9161 }
9162 break;
9163 }
9164 idx = index_in_strings(o_opt_strings, o_opt);
9165 if (idx >= 0) {
9166 G.o_opt[idx] = state;
9167 break;
9168 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009169 case 'e':
9170 G.o_opt[OPT_O_ERREXIT] = state;
9171 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009172 default:
9173 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009174 }
9175 return EXIT_SUCCESS;
9176}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009177
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009178int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009179int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009180{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009181 enum {
9182 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009183 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009184 };
9185 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009186 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009187 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009188 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009189 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009190
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009191 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009192 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009193 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009194
Denys Vlasenko10c01312011-05-11 11:49:21 +02009195#if ENABLE_HUSH_FAST
9196 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9197#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009198#if !BB_MMU
9199 G.argv0_for_re_execing = argv[0];
9200#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009201
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009202 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009203 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9204 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009205 shell_ver = xzalloc(sizeof(*shell_ver));
9206 shell_ver->flg_export = 1;
9207 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009208 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009209 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009210 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009211
Denys Vlasenko605067b2010-09-06 12:10:51 +02009212 /* Create shell local variables from the values
9213 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009214 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009215 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009216 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009217 if (e) while (*e) {
9218 char *value = strchr(*e, '=');
9219 if (value) { /* paranoia */
9220 cur_var->next = xzalloc(sizeof(*cur_var));
9221 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009222 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009223 cur_var->max_len = strlen(*e);
9224 cur_var->flg_export = 1;
9225 }
9226 e++;
9227 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009228 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009229 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9230 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009231
9232 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009233 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009234
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009235#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9236 /* Set (but not export) PS1/2 unless already set */
9237 if (!get_local_var_value("PS1"))
9238 set_local_var_from_halves("PS1", "\\w \\$ ");
9239 if (!get_local_var_value("PS2"))
9240 set_local_var_from_halves("PS2", "> ");
9241#endif
9242
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009243#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009244 /* Set (but not export) HOSTNAME unless already set */
9245 if (!get_local_var_value("HOSTNAME")) {
9246 struct utsname uts;
9247 uname(&uts);
9248 set_local_var_from_halves("HOSTNAME", uts.nodename);
9249 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009250 /* bash also exports SHLVL and _,
9251 * and sets (but doesn't export) the following variables:
9252 * BASH=/bin/bash
9253 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9254 * BASH_VERSION='3.2.0(1)-release'
9255 * HOSTTYPE=i386
9256 * MACHTYPE=i386-pc-linux-gnu
9257 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009258 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009259 * EUID=<NNNNN>
9260 * UID=<NNNNN>
9261 * GROUPS=()
9262 * LINES=<NNN>
9263 * COLUMNS=<NNN>
9264 * BASH_ARGC=()
9265 * BASH_ARGV=()
9266 * BASH_LINENO=()
9267 * BASH_SOURCE=()
9268 * DIRSTACK=()
9269 * PIPESTATUS=([0]="0")
9270 * HISTFILE=/<xxx>/.bash_history
9271 * HISTFILESIZE=500
9272 * HISTSIZE=500
9273 * MAILCHECK=60
9274 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9275 * SHELL=/bin/bash
9276 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9277 * TERM=dumb
9278 * OPTERR=1
9279 * OPTIND=1
9280 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009281 * PS4='+ '
9282 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009283#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009284
Denys Vlasenko5807e182018-02-08 19:19:04 +01009285#if ENABLE_HUSH_LINENO_VAR
9286 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009287 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9288 set_local_var(p, /*flags*/ 0);
9289 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9290 }
9291#endif
9292
Denis Vlasenko38f63192007-01-22 09:03:07 +00009293#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009294 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009295#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009296
Eric Andersen94ac2442001-05-22 19:05:18 +00009297 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009298 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009299
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009300 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009301
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009302 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009303 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009304 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009305 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009306 * in order to intercept (more) signals.
9307 */
9308
9309 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009310 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009311 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009312 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009313 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009314 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009315#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009316 "<:$:R:V:"
9317# if ENABLE_HUSH_FUNCTIONS
9318 "F:"
9319# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009320#endif
9321 );
9322 if (opt <= 0)
9323 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009324 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009325 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009326 /* Possibilities:
9327 * sh ... -c 'script'
9328 * sh ... -c 'script' ARG0 [ARG1...]
9329 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009330 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009331 * "" needs to be replaced with NULL
9332 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009333 * Note: the form without ARG0 never happens:
9334 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009335 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009336 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009337 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009338 G.root_ppid = getppid();
9339 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009340 G.global_argv = argv + optind;
9341 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009342 if (builtin_argc) {
9343 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9344 const struct built_in_command *x;
9345
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009346 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009347 x = find_builtin(optarg);
9348 if (x) { /* paranoia */
9349 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9350 G.global_argv += builtin_argc;
9351 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009352 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009353 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009354 }
9355 goto final_return;
9356 }
9357 if (!G.global_argv[0]) {
9358 /* -c 'script' (no params): prevent empty $0 */
9359 G.global_argv--; /* points to argv[i] of 'script' */
9360 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009361 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009362 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009363 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009364 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009365 goto final_return;
9366 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009367 /* Well, we cannot just declare interactiveness,
9368 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009369 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009370 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009371 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009372 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009373 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009374 case 'l':
9375 flags |= OPT_login;
9376 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009377#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009378 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009379 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009380 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009381 case '$': {
9382 unsigned long long empty_trap_mask;
9383
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009384 G.root_pid = bb_strtou(optarg, &optarg, 16);
9385 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009386 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9387 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009388 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9389 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009390 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009391 optarg++;
9392 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009393 optarg++;
9394 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9395 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009396 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009397 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009398# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009399 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009400 for (sig = 1; sig < NSIG; sig++) {
9401 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009402 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009403 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009404 }
9405 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009406# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009407 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009408# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009409 optarg++;
9410 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009411# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009412# if ENABLE_HUSH_FUNCTIONS
9413 /* nommu uses re-exec trick for "... | func | ...",
9414 * should allow "return".
9415 * This accidentally allows returns in subshells.
9416 */
9417 G_flag_return_in_progress = -1;
9418# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009419 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009420 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009421 case 'R':
9422 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009423 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009424 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009425# if ENABLE_HUSH_FUNCTIONS
9426 case 'F': {
9427 struct function *funcp = new_function(optarg);
9428 /* funcp->name is already set to optarg */
9429 /* funcp->body is set to NULL. It's a special case. */
9430 funcp->body_as_string = argv[optind];
9431 optind++;
9432 break;
9433 }
9434# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009435#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009436 case 'n':
9437 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009438 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009439 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009440 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009441 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009442#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009443 fprintf(stderr, "Usage: sh [FILE]...\n"
9444 " or: sh -c command [args]...\n\n");
9445 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009446#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009447 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009448#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009449 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009450 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009451
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009452 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9453 G.global_argc = argc - (optind - 1);
9454 G.global_argv = argv + (optind - 1);
9455 G.global_argv[0] = argv[0];
9456
Denys Vlasenkodea47882009-10-09 15:40:49 +02009457 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009458 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009459 G.root_ppid = getppid();
9460 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009461
9462 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009463 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009464 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009465 debug_printf("sourcing /etc/profile\n");
9466 input = fopen_for_read("/etc/profile");
9467 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009468 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009469 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009470 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009471 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009472 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009473 /* bash: after sourcing /etc/profile,
9474 * tries to source (in the given order):
9475 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009476 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009477 * bash also sources ~/.bash_logout on exit.
9478 * If called as sh, skips .bash_XXX files.
9479 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009480 }
9481
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009482 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9483 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009484 FILE *input;
9485 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009486 * "bash <script>" (which is never interactive (unless -i?))
9487 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009488 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009489 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009490 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009491 G.global_argc--;
9492 G.global_argv++;
9493 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009494 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009495 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009496 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009497 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009498 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009499 parse_and_run_file(input);
9500#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009501 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009502#endif
9503 goto final_return;
9504 }
9505
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009506 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009507 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009508 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009509
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009510 /* A shell is interactive if the '-i' flag was given,
9511 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009512 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009513 * no arguments remaining or the -s flag given
9514 * standard input is a terminal
9515 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009516 * Refer to Posix.2, the description of the 'sh' utility.
9517 */
9518#if ENABLE_HUSH_JOB
9519 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009520 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9521 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9522 if (G_saved_tty_pgrp < 0)
9523 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009524
9525 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009526 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009527 if (G_interactive_fd < 0) {
9528 /* try to dup to any fd */
9529 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009530 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009531 /* give up */
9532 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009533 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009534 }
9535 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009536// TODO: track & disallow any attempts of user
9537// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009538 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009539 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009540 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009541 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009542
Mike Frysinger38478a62009-05-20 04:48:06 -04009543 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009544 /* If we were run as 'hush &', sleep until we are
9545 * in the foreground (tty pgrp == our pgrp).
9546 * If we get started under a job aware app (like bash),
9547 * make sure we are now in charge so we don't fight over
9548 * who gets the foreground */
9549 while (1) {
9550 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009551 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9552 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009553 break;
9554 /* send TTIN to ourself (should stop us) */
9555 kill(- shell_pgrp, SIGTTIN);
9556 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009557 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009558
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009559 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009560 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009561
Mike Frysinger38478a62009-05-20 04:48:06 -04009562 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009563 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009564 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009565 /* Put ourselves in our own process group
9566 * (bash, too, does this only if ctty is available) */
9567 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9568 /* Grab control of the terminal */
9569 tcsetpgrp(G_interactive_fd, getpid());
9570 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009571 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009572
9573# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9574 {
9575 const char *hp = get_local_var_value("HISTFILE");
9576 if (!hp) {
9577 hp = get_local_var_value("HOME");
9578 if (hp)
9579 hp = concat_path_file(hp, ".hush_history");
9580 } else {
9581 hp = xstrdup(hp);
9582 }
9583 if (hp) {
9584 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009585 //set_local_var(xasprintf("HISTFILE=%s", ...));
9586 }
9587# if ENABLE_FEATURE_SH_HISTFILESIZE
9588 hp = get_local_var_value("HISTFILESIZE");
9589 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9590# endif
9591 }
9592# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009593 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009594 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009595 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009596#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009597 /* No job control compiled in, only prompt/line editing */
9598 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009599 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009600 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009601 /* try to dup to any fd */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009602 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009603 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009604 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009605 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009606 }
9607 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009608 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009609 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009610 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009611 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009612#else
9613 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009614 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009615#endif
9616 /* bash:
9617 * if interactive but not a login shell, sources ~/.bashrc
9618 * (--norc turns this off, --rcfile <file> overrides)
9619 */
9620
9621 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009622 /* note: ash and hush share this string */
9623 printf("\n\n%s %s\n"
9624 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9625 "\n",
9626 bb_banner,
9627 "hush - the humble shell"
9628 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009629 }
9630
Denis Vlasenkof9375282009-04-05 19:13:39 +00009631 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009632
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009633 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009634 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009635}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009636
9637
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009638/*
9639 * Built-ins
9640 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009641static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009642{
9643 return 0;
9644}
9645
Denys Vlasenko265062d2017-01-10 15:13:30 +01009646#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009647static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009648{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009649 int argc = string_array_len(argv);
9650 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009651}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009652#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009653#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009654static int FAST_FUNC builtin_test(char **argv)
9655{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009656 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009657}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009658#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009659#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009660static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009661{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009662 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009663}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009664#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009665#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009666static int FAST_FUNC builtin_printf(char **argv)
9667{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009668 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009669}
9670#endif
9671
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009672#if ENABLE_HUSH_HELP
9673static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9674{
9675 const struct built_in_command *x;
9676
9677 printf(
9678 "Built-in commands:\n"
9679 "------------------\n");
9680 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9681 if (x->b_descr)
9682 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9683 }
9684 return EXIT_SUCCESS;
9685}
9686#endif
9687
9688#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9689static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9690{
9691 show_history(G.line_input_state);
9692 return EXIT_SUCCESS;
9693}
9694#endif
9695
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009696static char **skip_dash_dash(char **argv)
9697{
9698 argv++;
9699 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9700 argv++;
9701 return argv;
9702}
9703
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009704static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009705{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009706 const char *newdir;
9707
9708 argv = skip_dash_dash(argv);
9709 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009710 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009711 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009712 * bash says "bash: cd: HOME not set" and does nothing
9713 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009714 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009715 const char *home = get_local_var_value("HOME");
9716 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009717 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009718 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009719 /* Mimic bash message exactly */
9720 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009721 return EXIT_FAILURE;
9722 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009723 /* Read current dir (get_cwd(1) is inside) and set PWD.
9724 * Note: do not enforce exporting. If PWD was unset or unexported,
9725 * set it again, but do not export. bash does the same.
9726 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009727 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009728 return EXIT_SUCCESS;
9729}
9730
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009731static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9732{
9733 puts(get_cwd(0));
9734 return EXIT_SUCCESS;
9735}
9736
9737static int FAST_FUNC builtin_eval(char **argv)
9738{
9739 int rcode = EXIT_SUCCESS;
9740
9741 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009742 if (argv[0]) {
9743 char *str = NULL;
9744
9745 if (argv[1]) {
9746 /* "The eval utility shall construct a command by
9747 * concatenating arguments together, separating
9748 * each with a <space> character."
9749 */
9750 char *p;
9751 unsigned len = 0;
9752 char **pp = argv;
9753 do
9754 len += strlen(*pp) + 1;
9755 while (*++pp);
9756 str = p = xmalloc(len);
9757 pp = argv;
9758 do {
9759 p = stpcpy(p, *pp);
9760 *p++ = ' ';
9761 } while (*++pp);
9762 p[-1] = '\0';
9763 }
9764
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009765 /* bash:
9766 * eval "echo Hi; done" ("done" is syntax error):
9767 * "echo Hi" will not execute too.
9768 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009769 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009770 free(str);
9771 rcode = G.last_exitcode;
9772 }
9773 return rcode;
9774}
9775
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009776static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009777{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009778 argv = skip_dash_dash(argv);
9779 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009780 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009781
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009782 /* Careful: we can end up here after [v]fork. Do not restore
9783 * tty pgrp then, only top-level shell process does that */
9784 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9785 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9786
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009787 /* Saved-redirect fds, script fds and G_interactive_fd are still
9788 * open here. However, they are all CLOEXEC, and execv below
9789 * closes them. Try interactive "exec ls -l /proc/self/fd",
9790 * it should show no extra open fds in the "ls" process.
9791 * If we'd try to run builtins/NOEXECs, this would need improving.
9792 */
9793 //close_saved_fds_and_FILE_fds();
9794
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009795 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009796 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009797 * and tcsetpgrp, and this is inherently racy.
9798 */
9799 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009800}
9801
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009802static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009803{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009804 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009805
9806 /* interactive bash:
9807 * # trap "echo EEE" EXIT
9808 * # exit
9809 * exit
9810 * There are stopped jobs.
9811 * (if there are _stopped_ jobs, running ones don't count)
9812 * # exit
9813 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009814 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009815 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009816 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009817 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009818
9819 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009820 argv = skip_dash_dash(argv);
9821 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009822 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009823 /* mimic bash: exit 123abc == exit 255 + error msg */
9824 xfunc_error_retval = 255;
9825 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009826 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009827}
9828
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009829#if ENABLE_HUSH_TYPE
9830/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9831static int FAST_FUNC builtin_type(char **argv)
9832{
9833 int ret = EXIT_SUCCESS;
9834
9835 while (*++argv) {
9836 const char *type;
9837 char *path = NULL;
9838
9839 if (0) {} /* make conditional compile easier below */
9840 /*else if (find_alias(*argv))
9841 type = "an alias";*/
9842#if ENABLE_HUSH_FUNCTIONS
9843 else if (find_function(*argv))
9844 type = "a function";
9845#endif
9846 else if (find_builtin(*argv))
9847 type = "a shell builtin";
9848 else if ((path = find_in_path(*argv)) != NULL)
9849 type = path;
9850 else {
9851 bb_error_msg("type: %s: not found", *argv);
9852 ret = EXIT_FAILURE;
9853 continue;
9854 }
9855
9856 printf("%s is %s\n", *argv, type);
9857 free(path);
9858 }
9859
9860 return ret;
9861}
9862#endif
9863
9864#if ENABLE_HUSH_READ
9865/* Interruptibility of read builtin in bash
9866 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9867 *
9868 * Empty trap makes read ignore corresponding signal, for any signal.
9869 *
9870 * SIGINT:
9871 * - terminates non-interactive shell;
9872 * - interrupts read in interactive shell;
9873 * if it has non-empty trap:
9874 * - executes trap and returns to command prompt in interactive shell;
9875 * - executes trap and returns to read in non-interactive shell;
9876 * SIGTERM:
9877 * - is ignored (does not interrupt) read in interactive shell;
9878 * - terminates non-interactive shell;
9879 * if it has non-empty trap:
9880 * - executes trap and returns to read;
9881 * SIGHUP:
9882 * - terminates shell (regardless of interactivity);
9883 * if it has non-empty trap:
9884 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009885 * SIGCHLD from children:
9886 * - does not interrupt read regardless of interactivity:
9887 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009888 */
9889static int FAST_FUNC builtin_read(char **argv)
9890{
9891 const char *r;
9892 char *opt_n = NULL;
9893 char *opt_p = NULL;
9894 char *opt_t = NULL;
9895 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009896 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009897 const char *ifs;
9898 int read_flags;
9899
9900 /* "!": do not abort on errors.
9901 * Option string must start with "sr" to match BUILTIN_READ_xxx
9902 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009903 read_flags = getopt32(argv,
9904#if BASH_READ_D
9905 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9906#else
9907 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9908#endif
9909 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009910 if (read_flags == (uint32_t)-1)
9911 return EXIT_FAILURE;
9912 argv += optind;
9913 ifs = get_local_var_value("IFS"); /* can be NULL */
9914
9915 again:
9916 r = shell_builtin_read(set_local_var_from_halves,
9917 argv,
9918 ifs,
9919 read_flags,
9920 opt_n,
9921 opt_p,
9922 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009923 opt_u,
9924 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009925 );
9926
9927 if ((uintptr_t)r == 1 && errno == EINTR) {
9928 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009929 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009930 goto again;
9931 }
9932
9933 if ((uintptr_t)r > 1) {
9934 bb_error_msg("%s", r);
9935 r = (char*)(uintptr_t)1;
9936 }
9937
9938 return (uintptr_t)r;
9939}
9940#endif
9941
9942#if ENABLE_HUSH_UMASK
9943static int FAST_FUNC builtin_umask(char **argv)
9944{
9945 int rc;
9946 mode_t mask;
9947
9948 rc = 1;
9949 mask = umask(0);
9950 argv = skip_dash_dash(argv);
9951 if (argv[0]) {
9952 mode_t old_mask = mask;
9953
9954 /* numeric umasks are taken as-is */
9955 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9956 if (!isdigit(argv[0][0]))
9957 mask ^= 0777;
9958 mask = bb_parse_mode(argv[0], mask);
9959 if (!isdigit(argv[0][0]))
9960 mask ^= 0777;
9961 if ((unsigned)mask > 0777) {
9962 mask = old_mask;
9963 /* bash messages:
9964 * bash: umask: 'q': invalid symbolic mode operator
9965 * bash: umask: 999: octal number out of range
9966 */
9967 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9968 rc = 0;
9969 }
9970 } else {
9971 /* Mimic bash */
9972 printf("%04o\n", (unsigned) mask);
9973 /* fall through and restore mask which we set to 0 */
9974 }
9975 umask(mask);
9976
9977 return !rc; /* rc != 0 - success */
9978}
9979#endif
9980
Denys Vlasenko41ade052017-01-08 18:56:24 +01009981#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009982static void print_escaped(const char *s)
9983{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009984 if (*s == '\'')
9985 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009986 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009987 const char *p = strchrnul(s, '\'');
9988 /* print 'xxxx', possibly just '' */
9989 printf("'%.*s'", (int)(p - s), s);
9990 if (*p == '\0')
9991 break;
9992 s = p;
9993 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009994 /* s points to '; print "'''...'''" */
9995 putchar('"');
9996 do putchar('\''); while (*++s == '\'');
9997 putchar('"');
9998 } while (*s);
9999}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010000#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010001
Denys Vlasenko1e660422017-07-17 21:10:50 +020010002#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010003static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010004{
10005 do {
10006 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010007 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010008
10009 /* So far we do not check that name is valid (TODO?) */
10010
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010011 if (*name_end == '\0') {
10012 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010013
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010014 vpp = get_ptr_to_local_var(name, name_end - name);
10015 var = vpp ? *vpp : NULL;
10016
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010017 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010018 /* export -n NAME (without =VALUE) */
10019 if (var) {
10020 var->flg_export = 0;
10021 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10022 unsetenv(name);
10023 } /* else: export -n NOT_EXISTING_VAR: no-op */
10024 continue;
10025 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010026 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010027 /* export NAME (without =VALUE) */
10028 if (var) {
10029 var->flg_export = 1;
10030 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10031 putenv(var->varstr);
10032 continue;
10033 }
10034 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010035 if (flags & SETFLAG_MAKE_RO) {
10036 /* readonly NAME (without =VALUE) */
10037 if (var) {
10038 var->flg_read_only = 1;
10039 continue;
10040 }
10041 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010042# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010043 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010044 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010045 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10046 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010047 /* "local x=abc; ...; local x" - ignore second local decl */
10048 continue;
10049 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010050 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010051# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010052 /* Exporting non-existing variable.
10053 * bash does not put it in environment,
10054 * but remembers that it is exported,
10055 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010056 * We just set it to "" and export.
10057 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010058 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010059 * bash sets the value to "".
10060 */
10061 /* Or, it's "readonly NAME" (without =VALUE).
10062 * bash remembers NAME and disallows its creation
10063 * in the future.
10064 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010065 name = xasprintf("%s=", name);
10066 } else {
10067 /* (Un)exporting/making local NAME=VALUE */
10068 name = xstrdup(name);
10069 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010070 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010071 if (set_local_var(name, flags))
10072 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010073 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010074 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010075}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010076#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010077
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010078#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010079static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010080{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010081 unsigned opt_unexport;
10082
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010083#if ENABLE_HUSH_EXPORT_N
10084 /* "!": do not abort on errors */
10085 opt_unexport = getopt32(argv, "!n");
10086 if (opt_unexport == (uint32_t)-1)
10087 return EXIT_FAILURE;
10088 argv += optind;
10089#else
10090 opt_unexport = 0;
10091 argv++;
10092#endif
10093
10094 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010095 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010096 if (e) {
10097 while (*e) {
10098#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010099 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010100#else
10101 /* ash emits: export VAR='VAL'
10102 * bash: declare -x VAR="VAL"
10103 * we follow ash example */
10104 const char *s = *e++;
10105 const char *p = strchr(s, '=');
10106
10107 if (!p) /* wtf? take next variable */
10108 continue;
10109 /* export var= */
10110 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010111 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010112 putchar('\n');
10113#endif
10114 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010115 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010116 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010117 return EXIT_SUCCESS;
10118 }
10119
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010120 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010121}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010122#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010123
Denys Vlasenko295fef82009-06-03 12:47:26 +020010124#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010125static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010126{
10127 if (G.func_nest_level == 0) {
10128 bb_error_msg("%s: not in a function", argv[0]);
10129 return EXIT_FAILURE; /* bash compat */
10130 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010131 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010132 /* Since all builtins run in a nested variable level,
10133 * need to use level - 1 here. Or else the variable will be removed at once
10134 * after builtin returns.
10135 */
10136 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010137}
10138#endif
10139
Denys Vlasenko1e660422017-07-17 21:10:50 +020010140#if ENABLE_HUSH_READONLY
10141static int FAST_FUNC builtin_readonly(char **argv)
10142{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010143 argv++;
10144 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010145 /* bash: readonly [-p]: list all readonly VARs
10146 * (-p has no effect in bash)
10147 */
10148 struct variable *e;
10149 for (e = G.top_var; e; e = e->next) {
10150 if (e->flg_read_only) {
10151//TODO: quote value: readonly VAR='VAL'
10152 printf("readonly %s\n", e->varstr);
10153 }
10154 }
10155 return EXIT_SUCCESS;
10156 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010157 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010158}
10159#endif
10160
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010161#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010162/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10163static int FAST_FUNC builtin_unset(char **argv)
10164{
10165 int ret;
10166 unsigned opts;
10167
10168 /* "!": do not abort on errors */
10169 /* "+": stop at 1st non-option */
10170 opts = getopt32(argv, "!+vf");
10171 if (opts == (unsigned)-1)
10172 return EXIT_FAILURE;
10173 if (opts == 3) {
10174 bb_error_msg("unset: -v and -f are exclusive");
10175 return EXIT_FAILURE;
10176 }
10177 argv += optind;
10178
10179 ret = EXIT_SUCCESS;
10180 while (*argv) {
10181 if (!(opts & 2)) { /* not -f */
10182 if (unset_local_var(*argv)) {
10183 /* unset <nonexistent_var> doesn't fail.
10184 * Error is when one tries to unset RO var.
10185 * Message was printed by unset_local_var. */
10186 ret = EXIT_FAILURE;
10187 }
10188 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010189# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010190 else {
10191 unset_func(*argv);
10192 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010193# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010194 argv++;
10195 }
10196 return ret;
10197}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010198#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010199
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010200#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010201/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10202 * built-in 'set' handler
10203 * SUSv3 says:
10204 * set [-abCefhmnuvx] [-o option] [argument...]
10205 * set [+abCefhmnuvx] [+o option] [argument...]
10206 * set -- [argument...]
10207 * set -o
10208 * set +o
10209 * Implementations shall support the options in both their hyphen and
10210 * plus-sign forms. These options can also be specified as options to sh.
10211 * Examples:
10212 * Write out all variables and their values: set
10213 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10214 * Turn on the -x and -v options: set -xv
10215 * Unset all positional parameters: set --
10216 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10217 * Set the positional parameters to the expansion of x, even if x expands
10218 * with a leading '-' or '+': set -- $x
10219 *
10220 * So far, we only support "set -- [argument...]" and some of the short names.
10221 */
10222static int FAST_FUNC builtin_set(char **argv)
10223{
10224 int n;
10225 char **pp, **g_argv;
10226 char *arg = *++argv;
10227
10228 if (arg == NULL) {
10229 struct variable *e;
10230 for (e = G.top_var; e; e = e->next)
10231 puts(e->varstr);
10232 return EXIT_SUCCESS;
10233 }
10234
10235 do {
10236 if (strcmp(arg, "--") == 0) {
10237 ++argv;
10238 goto set_argv;
10239 }
10240 if (arg[0] != '+' && arg[0] != '-')
10241 break;
10242 for (n = 1; arg[n]; ++n) {
10243 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10244 goto error;
10245 if (arg[n] == 'o' && argv[1])
10246 argv++;
10247 }
10248 } while ((arg = *++argv) != NULL);
10249 /* Now argv[0] is 1st argument */
10250
10251 if (arg == NULL)
10252 return EXIT_SUCCESS;
10253 set_argv:
10254
10255 /* NB: G.global_argv[0] ($0) is never freed/changed */
10256 g_argv = G.global_argv;
10257 if (G.global_args_malloced) {
10258 pp = g_argv;
10259 while (*++pp)
10260 free(*pp);
10261 g_argv[1] = NULL;
10262 } else {
10263 G.global_args_malloced = 1;
10264 pp = xzalloc(sizeof(pp[0]) * 2);
10265 pp[0] = g_argv[0]; /* retain $0 */
10266 g_argv = pp;
10267 }
10268 /* This realloc's G.global_argv */
10269 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10270
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010271 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010272
10273 return EXIT_SUCCESS;
10274
10275 /* Nothing known, so abort */
10276 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010277 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010278 return EXIT_FAILURE;
10279}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010280#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010281
10282static int FAST_FUNC builtin_shift(char **argv)
10283{
10284 int n = 1;
10285 argv = skip_dash_dash(argv);
10286 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010287 n = bb_strtou(argv[0], NULL, 10);
10288 if (errno || n < 0) {
10289 /* shared string with ash.c */
10290 bb_error_msg("Illegal number: %s", argv[0]);
10291 /*
10292 * ash aborts in this case.
10293 * bash prints error message and set $? to 1.
10294 * Interestingly, for "shift 99999" bash does not
10295 * print error message, but does set $? to 1
10296 * (and does no shifting at all).
10297 */
10298 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010299 }
10300 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010301 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010302 int m = 1;
10303 while (m <= n)
10304 free(G.global_argv[m++]);
10305 }
10306 G.global_argc -= n;
10307 memmove(&G.global_argv[1], &G.global_argv[n+1],
10308 G.global_argc * sizeof(G.global_argv[0]));
10309 return EXIT_SUCCESS;
10310 }
10311 return EXIT_FAILURE;
10312}
10313
Denys Vlasenko74d40582017-08-11 01:32:46 +020010314#if ENABLE_HUSH_GETOPTS
10315static int FAST_FUNC builtin_getopts(char **argv)
10316{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010317/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10318
Denys Vlasenko74d40582017-08-11 01:32:46 +020010319TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010320If a required argument is not found, and getopts is not silent,
10321a question mark (?) is placed in VAR, OPTARG is unset, and a
10322diagnostic message is printed. If getopts is silent, then a
10323colon (:) is placed in VAR and OPTARG is set to the option
10324character found.
10325
10326Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010327
10328"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010329*/
10330 char cbuf[2];
10331 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010332 int c, n, exitcode, my_opterr;
10333 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010334
10335 optstring = *++argv;
10336 if (!optstring || !(var = *++argv)) {
10337 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10338 return EXIT_FAILURE;
10339 }
10340
Denys Vlasenko238ff982017-08-29 13:38:30 +020010341 if (argv[1])
10342 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10343 else
10344 argv = G.global_argv;
10345 cbuf[1] = '\0';
10346
10347 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010348 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010349 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010350 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010351 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010352 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010353
10354 /* getopts stops on first non-option. Add "+" to force that */
10355 /*if (optstring[0] != '+')*/ {
10356 char *s = alloca(strlen(optstring) + 2);
10357 sprintf(s, "+%s", optstring);
10358 optstring = s;
10359 }
10360
Denys Vlasenko238ff982017-08-29 13:38:30 +020010361 /* Naively, now we should just
10362 * cp = get_local_var_value("OPTIND");
10363 * optind = cp ? atoi(cp) : 0;
10364 * optarg = NULL;
10365 * opterr = my_opterr;
10366 * c = getopt(string_array_len(argv), argv, optstring);
10367 * and be done? Not so fast...
10368 * Unlike normal getopt() usage in C programs, here
10369 * each successive call will (usually) have the same argv[] CONTENTS,
10370 * but not the ADDRESSES. Worse yet, it's possible that between
10371 * invocations of "getopts", there will be calls to shell builtins
10372 * which use getopt() internally. Example:
10373 * while getopts "abc" RES -a -bc -abc de; do
10374 * unset -ff func
10375 * done
10376 * This would not work correctly: getopt() call inside "unset"
10377 * modifies internal libc state which is tracking position in
10378 * multi-option strings ("-abc"). At best, it can skip options
10379 * or return the same option infinitely. With glibc implementation
10380 * of getopt(), it would use outright invalid pointers and return
10381 * garbage even _without_ "unset" mangling internal state.
10382 *
10383 * We resort to resetting getopt() state and calling it N times,
10384 * until we get Nth result (or failure).
10385 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10386 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010387 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010388 count = 0;
10389 n = string_array_len(argv);
10390 do {
10391 optarg = NULL;
10392 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10393 c = getopt(n, argv, optstring);
10394 if (c < 0)
10395 break;
10396 count++;
10397 } while (count <= G.getopt_count);
10398
10399 /* Set OPTIND. Prevent resetting of the magic counter! */
10400 set_local_var_from_halves("OPTIND", utoa(optind));
10401 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010402 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010403
10404 /* Set OPTARG */
10405 /* Always set or unset, never left as-is, even on exit/error:
10406 * "If no option was found, or if the option that was found
10407 * does not have an option-argument, OPTARG shall be unset."
10408 */
10409 cp = optarg;
10410 if (c == '?') {
10411 /* If ":optstring" and unknown option is seen,
10412 * it is stored to OPTARG.
10413 */
10414 if (optstring[1] == ':') {
10415 cbuf[0] = optopt;
10416 cp = cbuf;
10417 }
10418 }
10419 if (cp)
10420 set_local_var_from_halves("OPTARG", cp);
10421 else
10422 unset_local_var("OPTARG");
10423
10424 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010425 exitcode = EXIT_SUCCESS;
10426 if (c < 0) { /* -1: end of options */
10427 exitcode = EXIT_FAILURE;
10428 c = '?';
10429 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010430
Denys Vlasenko238ff982017-08-29 13:38:30 +020010431 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010432 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010433 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010434
Denys Vlasenko74d40582017-08-11 01:32:46 +020010435 return exitcode;
10436}
10437#endif
10438
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010439static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010440{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010441 char *arg_path, *filename;
10442 FILE *input;
10443 save_arg_t sv;
10444 char *args_need_save;
10445#if ENABLE_HUSH_FUNCTIONS
10446 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010447#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010448
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010449 argv = skip_dash_dash(argv);
10450 filename = argv[0];
10451 if (!filename) {
10452 /* bash says: "bash: .: filename argument required" */
10453 return 2; /* bash compat */
10454 }
10455 arg_path = NULL;
10456 if (!strchr(filename, '/')) {
10457 arg_path = find_in_path(filename);
10458 if (arg_path)
10459 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010460 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010461 errno = ENOENT;
10462 bb_simple_perror_msg(filename);
10463 return EXIT_FAILURE;
10464 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010465 }
10466 input = remember_FILE(fopen_or_warn(filename, "r"));
10467 free(arg_path);
10468 if (!input) {
10469 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10470 /* POSIX: non-interactive shell should abort here,
10471 * not merely fail. So far no one complained :)
10472 */
10473 return EXIT_FAILURE;
10474 }
10475
10476#if ENABLE_HUSH_FUNCTIONS
10477 sv_flg = G_flag_return_in_progress;
10478 /* "we are inside sourced file, ok to use return" */
10479 G_flag_return_in_progress = -1;
10480#endif
10481 args_need_save = argv[1]; /* used as a boolean variable */
10482 if (args_need_save)
10483 save_and_replace_G_args(&sv, argv);
10484
10485 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10486 G.last_exitcode = 0;
10487 parse_and_run_file(input);
10488 fclose_and_forget(input);
10489
10490 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10491 restore_G_args(&sv, argv);
10492#if ENABLE_HUSH_FUNCTIONS
10493 G_flag_return_in_progress = sv_flg;
10494#endif
10495
10496 return G.last_exitcode;
10497}
10498
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010499#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010500static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010501{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010502 int sig;
10503 char *new_cmd;
10504
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010505 if (!G_traps)
10506 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010507
10508 argv++;
10509 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010510 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010511 /* No args: print all trapped */
10512 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010513 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010514 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010515 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010516 /* note: bash adds "SIG", but only if invoked
10517 * as "bash". If called as "sh", or if set -o posix,
10518 * then it prints short signal names.
10519 * We are printing short names: */
10520 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010521 }
10522 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010523 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010524 return EXIT_SUCCESS;
10525 }
10526
10527 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010528 /* If first arg is a number: reset all specified signals */
10529 sig = bb_strtou(*argv, NULL, 10);
10530 if (errno == 0) {
10531 int ret;
10532 process_sig_list:
10533 ret = EXIT_SUCCESS;
10534 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010535 sighandler_t handler;
10536
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010537 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010538 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010539 ret = EXIT_FAILURE;
10540 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010541 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010542 continue;
10543 }
10544
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010545 free(G_traps[sig]);
10546 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010547
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010548 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010549 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010550
10551 /* There is no signal for 0 (EXIT) */
10552 if (sig == 0)
10553 continue;
10554
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010555 if (new_cmd)
10556 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10557 else
10558 /* We are removing trap handler */
10559 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010560 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010561 }
10562 return ret;
10563 }
10564
10565 if (!argv[1]) { /* no second arg */
10566 bb_error_msg("trap: invalid arguments");
10567 return EXIT_FAILURE;
10568 }
10569
10570 /* First arg is "-": reset all specified to default */
10571 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10572 /* Everything else: set arg as signal handler
10573 * (includes "" case, which ignores signal) */
10574 if (argv[0][0] == '-') {
10575 if (argv[0][1] == '\0') { /* "-" */
10576 /* new_cmd remains NULL: "reset these sigs" */
10577 goto reset_traps;
10578 }
10579 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10580 argv++;
10581 }
10582 /* else: "-something", no special meaning */
10583 }
10584 new_cmd = *argv;
10585 reset_traps:
10586 argv++;
10587 goto process_sig_list;
10588}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010589#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010590
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010591#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010592static struct pipe *parse_jobspec(const char *str)
10593{
10594 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010595 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010596
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010597 if (sscanf(str, "%%%u", &jobnum) != 1) {
10598 if (str[0] != '%'
10599 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10600 ) {
10601 bb_error_msg("bad argument '%s'", str);
10602 return NULL;
10603 }
10604 /* It is "%%", "%+" or "%" - current job */
10605 jobnum = G.last_jobid;
10606 if (jobnum == 0) {
10607 bb_error_msg("no current job");
10608 return NULL;
10609 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010610 }
10611 for (pi = G.job_list; pi; pi = pi->next) {
10612 if (pi->jobid == jobnum) {
10613 return pi;
10614 }
10615 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010616 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010617 return NULL;
10618}
10619
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010620static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10621{
10622 struct pipe *job;
10623 const char *status_string;
10624
10625 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10626 for (job = G.job_list; job; job = job->next) {
10627 if (job->alive_cmds == job->stopped_cmds)
10628 status_string = "Stopped";
10629 else
10630 status_string = "Running";
10631
10632 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10633 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010634
10635 clean_up_last_dead_job();
10636
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010637 return EXIT_SUCCESS;
10638}
10639
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010640/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010641static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010642{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010643 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010644 struct pipe *pi;
10645
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010646 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010647 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010648
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010649 /* If they gave us no args, assume they want the last backgrounded task */
10650 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010651 for (pi = G.job_list; pi; pi = pi->next) {
10652 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010653 goto found;
10654 }
10655 }
10656 bb_error_msg("%s: no current job", argv[0]);
10657 return EXIT_FAILURE;
10658 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010659
10660 pi = parse_jobspec(argv[1]);
10661 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010662 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010663 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010664 /* TODO: bash prints a string representation
10665 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010666 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010667 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010668 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010669 }
10670
10671 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010672 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10673 for (i = 0; i < pi->num_cmds; i++) {
10674 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010675 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010676 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010677
10678 i = kill(- pi->pgrp, SIGCONT);
10679 if (i < 0) {
10680 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010681 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010682 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010683 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010684 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010685 }
10686
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010687 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010688 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010689 return checkjobs_and_fg_shell(pi);
10690 }
10691 return EXIT_SUCCESS;
10692}
10693#endif
10694
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010695#if ENABLE_HUSH_KILL
10696static int FAST_FUNC builtin_kill(char **argv)
10697{
10698 int ret = 0;
10699
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010700# if ENABLE_HUSH_JOB
10701 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10702 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010703
10704 do {
10705 struct pipe *pi;
10706 char *dst;
10707 int j, n;
10708
10709 if (argv[i][0] != '%')
10710 continue;
10711 /*
10712 * "kill %N" - job kill
10713 * Converting to pgrp / pid kill
10714 */
10715 pi = parse_jobspec(argv[i]);
10716 if (!pi) {
10717 /* Eat bad jobspec */
10718 j = i;
10719 do {
10720 j++;
10721 argv[j - 1] = argv[j];
10722 } while (argv[j]);
10723 ret = 1;
10724 i--;
10725 continue;
10726 }
10727 /*
10728 * In jobs started under job control, we signal
10729 * entire process group by kill -PGRP_ID.
10730 * This happens, f.e., in interactive shell.
10731 *
10732 * Otherwise, we signal each child via
10733 * kill PID1 PID2 PID3.
10734 * Testcases:
10735 * sh -c 'sleep 1|sleep 1 & kill %1'
10736 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10737 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10738 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010739 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010740 dst = alloca(n * sizeof(int)*4);
10741 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010742 if (G_interactive_fd)
10743 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010744 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010745 struct command *cmd = &pi->cmds[j];
10746 /* Skip exited members of the job */
10747 if (cmd->pid == 0)
10748 continue;
10749 /*
10750 * kill_main has matching code to expect
10751 * leading space. Needed to not confuse
10752 * negative pids with "kill -SIGNAL_NO" syntax
10753 */
10754 dst += sprintf(dst, " %u", (int)cmd->pid);
10755 }
10756 *dst = '\0';
10757 } while (argv[++i]);
10758 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010759# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010760
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010761 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010762 ret = run_applet_main(argv, kill_main);
10763 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010764 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010765 return ret;
10766}
10767#endif
10768
10769#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010770/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010771#if !ENABLE_HUSH_JOB
10772# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10773#endif
10774static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010775{
10776 int ret = 0;
10777 for (;;) {
10778 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010779 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010780
Denys Vlasenko830ea352016-11-08 04:59:11 +010010781 if (!sigisemptyset(&G.pending_set))
10782 goto check_sig;
10783
Denys Vlasenko7e675362016-10-28 21:57:31 +020010784 /* waitpid is not interruptible by SA_RESTARTed
10785 * signals which we use. Thus, this ugly dance:
10786 */
10787
10788 /* Make sure possible SIGCHLD is stored in kernel's
10789 * pending signal mask before we call waitpid.
10790 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010791 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010792 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010793 sigfillset(&oldset); /* block all signals, remember old set */
10794 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010795
10796 if (!sigisemptyset(&G.pending_set)) {
10797 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010798 goto restore;
10799 }
10800
10801 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010802/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010803 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010804 debug_printf_exec("checkjobs:%d\n", ret);
10805#if ENABLE_HUSH_JOB
10806 if (waitfor_pipe) {
10807 int rcode = job_exited_or_stopped(waitfor_pipe);
10808 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10809 if (rcode >= 0) {
10810 ret = rcode;
10811 sigprocmask(SIG_SETMASK, &oldset, NULL);
10812 break;
10813 }
10814 }
10815#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010816 /* if ECHILD, there are no children (ret is -1 or 0) */
10817 /* if ret == 0, no children changed state */
10818 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010819 if (errno == ECHILD || ret) {
10820 ret--;
10821 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010822 ret = 0;
10823 sigprocmask(SIG_SETMASK, &oldset, NULL);
10824 break;
10825 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010826 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010827 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10828 /* Note: sigsuspend invokes signal handler */
10829 sigsuspend(&oldset);
10830 restore:
10831 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010832 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010833 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010834 sig = check_and_run_traps();
10835 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010836 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010837 ret = 128 + sig;
10838 break;
10839 }
10840 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10841 }
10842 return ret;
10843}
10844
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010845static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010846{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010847 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010848 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010849
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010850 argv = skip_dash_dash(argv);
10851 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010852 /* Don't care about wait results */
10853 /* Note 1: must wait until there are no more children */
10854 /* Note 2: must be interruptible */
10855 /* Examples:
10856 * $ sleep 3 & sleep 6 & wait
10857 * [1] 30934 sleep 3
10858 * [2] 30935 sleep 6
10859 * [1] Done sleep 3
10860 * [2] Done sleep 6
10861 * $ sleep 3 & sleep 6 & wait
10862 * [1] 30936 sleep 3
10863 * [2] 30937 sleep 6
10864 * [1] Done sleep 3
10865 * ^C <-- after ~4 sec from keyboard
10866 * $
10867 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010868 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010869 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010870
Denys Vlasenko7e675362016-10-28 21:57:31 +020010871 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010872 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010873 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010874#if ENABLE_HUSH_JOB
10875 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010876 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010877 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010878 wait_pipe = parse_jobspec(*argv);
10879 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010880 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010881 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010882 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010883 } else {
10884 /* waiting on "last dead job" removes it */
10885 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010886 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010887 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010888 /* else: parse_jobspec() already emitted error msg */
10889 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010890 }
10891#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010892 /* mimic bash message */
10893 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010894 ret = EXIT_FAILURE;
10895 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010896 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010897
Denys Vlasenko7e675362016-10-28 21:57:31 +020010898 /* Do we have such child? */
10899 ret = waitpid(pid, &status, WNOHANG);
10900 if (ret < 0) {
10901 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010902 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010903 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010904 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010905 /* "wait $!" but last bg task has already exited. Try:
10906 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10907 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010908 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010909 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010910 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010911 } else {
10912 /* Example: "wait 1". mimic bash message */
10913 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010914 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010915 } else {
10916 /* ??? */
10917 bb_perror_msg("wait %s", *argv);
10918 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010919 continue; /* bash checks all argv[] */
10920 }
10921 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010922 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010923 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010924 } else {
10925 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010926 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010927 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010928 if (WIFSIGNALED(status))
10929 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010930 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010931 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010932
10933 return ret;
10934}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010935#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010936
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010937#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10938static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10939{
10940 if (argv[1]) {
10941 def = bb_strtou(argv[1], NULL, 10);
10942 if (errno || def < def_min || argv[2]) {
10943 bb_error_msg("%s: bad arguments", argv[0]);
10944 def = UINT_MAX;
10945 }
10946 }
10947 return def;
10948}
10949#endif
10950
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010951#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010952static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010953{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010954 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010955 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010956 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010957 /* if we came from builtin_continue(), need to undo "= 1" */
10958 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010959 return EXIT_SUCCESS; /* bash compat */
10960 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010961 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010962
10963 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10964 if (depth == UINT_MAX)
10965 G.flag_break_continue = BC_BREAK;
10966 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010967 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010968
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010969 return EXIT_SUCCESS;
10970}
10971
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010972static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010973{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010974 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10975 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010976}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010977#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010978
10979#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010980static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010981{
10982 int rc;
10983
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010984 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010985 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10986 return EXIT_FAILURE; /* bash compat */
10987 }
10988
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010989 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010990
10991 /* bash:
10992 * out of range: wraps around at 256, does not error out
10993 * non-numeric param:
10994 * f() { false; return qwe; }; f; echo $?
10995 * bash: return: qwe: numeric argument required <== we do this
10996 * 255 <== we also do this
10997 */
10998 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10999 return rc;
11000}
11001#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011002
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011003#if ENABLE_HUSH_TIMES
11004static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11005{
11006 static const uint8_t times_tbl[] ALIGN1 = {
11007 ' ', offsetof(struct tms, tms_utime),
11008 '\n', offsetof(struct tms, tms_stime),
11009 ' ', offsetof(struct tms, tms_cutime),
11010 '\n', offsetof(struct tms, tms_cstime),
11011 0
11012 };
11013 const uint8_t *p;
11014 unsigned clk_tck;
11015 struct tms buf;
11016
11017 clk_tck = bb_clk_tck();
11018
11019 times(&buf);
11020 p = times_tbl;
11021 do {
11022 unsigned sec, frac;
11023 unsigned long t;
11024 t = *(clock_t *)(((char *) &buf) + p[1]);
11025 sec = t / clk_tck;
11026 frac = t % clk_tck;
11027 printf("%um%u.%03us%c",
11028 sec / 60, sec % 60,
11029 (frac * 1000) / clk_tck,
11030 p[0]);
11031 p += 2;
11032 } while (*p);
11033
11034 return EXIT_SUCCESS;
11035}
11036#endif
11037
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011038#if ENABLE_HUSH_MEMLEAK
11039static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11040{
11041 void *p;
11042 unsigned long l;
11043
11044# ifdef M_TRIM_THRESHOLD
11045 /* Optional. Reduces probability of false positives */
11046 malloc_trim(0);
11047# endif
11048 /* Crude attempt to find where "free memory" starts,
11049 * sans fragmentation. */
11050 p = malloc(240);
11051 l = (unsigned long)p;
11052 free(p);
11053 p = malloc(3400);
11054 if (l < (unsigned long)p) l = (unsigned long)p;
11055 free(p);
11056
11057
11058# if 0 /* debug */
11059 {
11060 struct mallinfo mi = mallinfo();
11061 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11062 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11063 }
11064# endif
11065
11066 if (!G.memleak_value)
11067 G.memleak_value = l;
11068
11069 l -= G.memleak_value;
11070 if ((long)l < 0)
11071 l = 0;
11072 l /= 1024;
11073 if (l > 127)
11074 l = 127;
11075
11076 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11077 return l;
11078}
11079#endif