blob: b881b001abe3956eb8502cf1f28414af06044a3b [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:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * 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 Vlasenkob097a842018-12-28 03:20:17 +010096//config: bool "hush (68 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
Ron Yorston060f0a02018-11-09 12:00:39 +0000160//config: bool "Support command 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
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200360#ifndef O_CLOEXEC
361# define O_CLOEXEC 0
362#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100363#ifndef F_DUPFD_CLOEXEC
364# define F_DUPFD_CLOEXEC F_DUPFD
365#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100366
Ron Yorston71df2d32018-11-27 14:34:25 +0000367#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
368# include "embedded_scripts.h"
369#else
370# define NUM_SCRIPTS 0
371#endif
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000372
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100373/* So far, all bash compat is controlled by one config option */
374/* Separate defines document which part of code implements what */
375#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
376#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100377#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
378#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100379#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200380#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200381#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100382
383
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200384/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000385#define LEAK_HUNTING 0
386#define BUILD_AS_NOMMU 0
387/* Enable/disable sanity checks. Ok to enable in production,
388 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
389 * Keeping 1 for now even in released versions.
390 */
391#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200392/* Slightly bigger (+200 bytes), but faster hush.
393 * So far it only enables a trick with counting SIGCHLDs and forks,
394 * which allows us to do fewer waitpid's.
395 * (we can detect a case where neither forks were done nor SIGCHLDs happened
396 * and therefore waitpid will return the same result as last time)
397 */
398#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200399/* TODO: implement simplified code for users which do not need ${var%...} ops
400 * So far ${var%...} ops are always enabled:
401 */
402#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000403
404
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000405#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000406# undef BB_MMU
407# undef USE_FOR_NOMMU
408# undef USE_FOR_MMU
409# define BB_MMU 0
410# define USE_FOR_NOMMU(...) __VA_ARGS__
411# define USE_FOR_MMU(...)
412#endif
413
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200414#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100415#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000416/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000417# undef CONFIG_FEATURE_SH_STANDALONE
418# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000419# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100420# undef IF_NOT_FEATURE_SH_STANDALONE
421# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000422# define IF_FEATURE_SH_STANDALONE(...)
423# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000424#endif
425
Denis Vlasenko05743d72008-02-10 12:10:08 +0000426#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000427# undef ENABLE_FEATURE_EDITING
428# define ENABLE_FEATURE_EDITING 0
429# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
430# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200431# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
432# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000433#endif
434
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000435/* Do we support ANY keywords? */
436#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000437# define HAS_KEYWORDS 1
438# define IF_HAS_KEYWORDS(...) __VA_ARGS__
439# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000440#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000441# define HAS_KEYWORDS 0
442# define IF_HAS_KEYWORDS(...)
443# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000444#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000445
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000446/* If you comment out one of these below, it will be #defined later
447 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200448#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000449/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200450#define debug_printf_parse(...) do {} while (0)
451#define debug_printf_heredoc(...) do {} while (0)
452#define debug_print_tree(a, b) do {} while (0)
453#define debug_printf_exec(...) do {} while (0)
454#define debug_printf_env(...) do {} while (0)
455#define debug_printf_jobs(...) do {} while (0)
456#define debug_printf_expand(...) do {} while (0)
457#define debug_printf_varexp(...) do {} while (0)
458#define debug_printf_glob(...) do {} while (0)
459#define debug_printf_redir(...) do {} while (0)
460#define debug_printf_list(...) do {} while (0)
461#define debug_printf_subst(...) do {} while (0)
462#define debug_printf_prompt(...) do {} while (0)
463#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000464
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000465#define ERR_PTR ((void*)(long)1)
466
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100467#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000468
Denys Vlasenkoef8985c2019-05-19 16:29:09 +0200469#define _SPECIAL_VARS_STR "_*@$!?#-"
470#define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
471#define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100472#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200473/* Support / and // replace ops */
474/* Note that // is stored as \ in "encoded" string representation */
475# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
476# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
477# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
478#else
479# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
480# define VAR_SUBST_OPS "%#:-=+?"
481# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
482#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200483
Denys Vlasenko932b9972018-01-11 12:39:48 +0100484#define SPECIAL_VAR_SYMBOL_STR "\3"
485#define SPECIAL_VAR_SYMBOL 3
486/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
487#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000488
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200489struct variable;
490
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000491static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
492
493/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000494 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000495 */
496#if !BB_MMU
497typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200498 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000499 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000500 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000501} nommu_save_t;
502#endif
503
Denys Vlasenko9b782552010-09-08 13:33:26 +0200504enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000505 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000506#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_IF ,
508 RES_THEN ,
509 RES_ELIF ,
510 RES_ELSE ,
511 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000512#endif
513#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_FOR ,
515 RES_WHILE ,
516 RES_UNTIL ,
517 RES_DO ,
518 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000519#endif
520#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000521 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000522#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523#if ENABLE_HUSH_CASE
524 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200525 /* three pseudo-keywords support contrived "case" syntax: */
526 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
527 RES_MATCH , /* "word)" */
528 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000529 RES_ESAC ,
530#endif
531 RES_XXXX ,
532 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200533};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000534
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000535typedef struct o_string {
536 char *data;
537 int length; /* position where data is appended */
538 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200539 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000540 /* At least some part of the string was inside '' or "",
541 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200542 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000543 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200544 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545} o_string;
546enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200547 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
548 EXP_FLAG_GLOB = 0x2,
549 /* Protect newly added chars against globbing
550 * by prepending \ to *, ?, [, \ */
551 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
552};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000553/* Used for initialization: o_string foo = NULL_O_STRING; */
554#define NULL_O_STRING { NULL }
555
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200556#ifndef debug_printf_parse
557static const char *const assignment_flag[] = {
558 "MAYBE_ASSIGNMENT",
559 "DEFINITELY_ASSIGNMENT",
560 "NOT_ASSIGNMENT",
561 "WORD_IS_KEYWORD",
562};
563#endif
564
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200565/* We almost can use standard FILE api, but we need an ability to move
566 * its fd when redirects coincide with it. No api exists for that
567 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
568 * HFILE is our internal alternative. Only supports reading.
569 * Since we now can, we incorporate linked list of all opened HFILEs
570 * into the struct (used to be a separate mini-list).
571 */
572typedef struct HFILE {
573 char *cur;
574 char *end;
575 struct HFILE *next_hfile;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200576 int fd;
577 char buf[1024];
578} HFILE;
579
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000580typedef struct in_str {
581 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200582 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200583 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200584 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000585} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000586
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200587/* The descrip member of this structure is only used to make
588 * debugging output pretty */
589static const struct {
590 int mode;
591 signed char default_fd;
592 char descrip[3];
593} redir_table[] = {
594 { O_RDONLY, 0, "<" },
595 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
596 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
597 { O_CREAT|O_RDWR, 1, "<>" },
598 { O_RDONLY, 0, "<<" },
599/* Should not be needed. Bogus default_fd helps in debugging */
600/* { O_RDONLY, 77, "<<" }, */
601};
602
Eric Andersen25f27032001-04-26 23:22:31 +0000603struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000604 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000605 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000606 int rd_fd; /* fd to redirect */
607 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
608 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000609 smallint rd_type; /* (enum redir_type) */
610 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000611 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200612 * bit 0: do we need to trim leading tabs?
613 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000614 */
Eric Andersen25f27032001-04-26 23:22:31 +0000615};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000616typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200617 REDIRECT_INPUT = 0,
618 REDIRECT_OVERWRITE = 1,
619 REDIRECT_APPEND = 2,
620 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000621 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200622 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000623
624 REDIRFD_CLOSE = -3,
625 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000626 REDIRFD_TO_FILE = -1,
627 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000628
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000629 HEREDOC_SKIPTABS = 1,
630 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000631} redir_type;
632
Eric Andersen25f27032001-04-26 23:22:31 +0000633
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000634struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000635 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200636 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100637#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100638 unsigned lineno;
639#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200640 smallint cmd_type; /* CMD_xxx */
641#define CMD_NORMAL 0
642#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200643#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
644/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
645 * "export v=t*"
646 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200647# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000648#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200649#if ENABLE_HUSH_FUNCTIONS
650# define CMD_FUNCDEF 3
651#endif
652
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100653 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200654 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
655 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000656#if !BB_MMU
657 char *group_as_string;
658#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000659#if ENABLE_HUSH_FUNCTIONS
660 struct function *child_func;
661/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200662 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000663 * When we execute "f1() {a;}" cmd, we create new function and clear
664 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200665 * When we execute "f1() {b;}", we notice that f1 exists,
666 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000667 * we put those fields back into cmd->xxx
668 * (struct function has ->parent_cmd ptr to facilitate that).
669 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
670 * Without this trick, loop would execute a;b;b;b;...
671 * instead of correct sequence a;b;a;b;...
672 * When command is freed, it severs the link
673 * (sets ->child_func->parent_cmd to NULL).
674 */
675#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000676 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000677/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
678 * and on execution these are substituted with their values.
679 * Substitution can make _several_ words out of one argv[n]!
680 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000681 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000682 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000683 struct redir_struct *redirects; /* I/O redirections */
684};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000685/* Is there anything in this command at all? */
686#define IS_NULL_CMD(cmd) \
687 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
688
Eric Andersen25f27032001-04-26 23:22:31 +0000689struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000690 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000691 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000692 int alive_cmds; /* number of commands running (not exited) */
693 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000694#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100695 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000696 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000697 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000698#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000699 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000700 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000701 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
702 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000703};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000704typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100705 PIPE_SEQ = 0,
706 PIPE_AND = 1,
707 PIPE_OR = 2,
708 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000709} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000710/* Is there anything in this pipe at all? */
711#define IS_NULL_PIPE(pi) \
712 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000713
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000714/* This holds pointers to the various results of parsing */
715struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000716 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000717 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000718 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000719 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000720 /* last command in pipe (being constructed right now) */
721 struct command *command;
722 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000723 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200724 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000725#if !BB_MMU
726 o_string as_string;
727#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200728 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000729#if HAS_KEYWORDS
730 smallint ctx_res_w;
731 smallint ctx_inverted; /* "! cmd | cmd" */
732#if ENABLE_HUSH_CASE
733 smallint ctx_dsemicolon; /* ";;" seen */
734#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000735 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
736 int old_flag;
737 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000738 * example: "if pipe1; pipe2; then pipe3; fi"
739 * when we see "if" or "then", we malloc and copy current context,
740 * and make ->stack point to it. then we parse pipeN.
741 * when closing "then" / fi" / whatever is found,
742 * we move list_head into ->stack->command->group,
743 * copy ->stack into current context, and delete ->stack.
744 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000745 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000746 struct parse_context *stack;
747#endif
748};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200749enum {
750 MAYBE_ASSIGNMENT = 0,
751 DEFINITELY_ASSIGNMENT = 1,
752 NOT_ASSIGNMENT = 2,
753 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
754 WORD_IS_KEYWORD = 3,
755};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000756
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000757/* On program start, environ points to initial environment.
758 * putenv adds new pointers into it, unsetenv removes them.
759 * Neither of these (de)allocates the strings.
760 * setenv allocates new strings in malloc space and does putenv,
761 * and thus setenv is unusable (leaky) for shell's purposes */
762#define setenv(...) setenv_is_leaky_dont_use()
763struct variable {
764 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000765 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200767 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000768 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000769 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000770};
771
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000772enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000773 BC_BREAK = 1,
774 BC_CONTINUE = 2,
775};
776
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000777#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000778struct function {
779 struct function *next;
780 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000781 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000782 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200783# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000784 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200785# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000787#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000788
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000789
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100790/* set -/+o OPT support. (TODO: make it optional)
791 * bash supports the following opts:
792 * allexport off
793 * braceexpand on
794 * emacs on
795 * errexit off
796 * errtrace off
797 * functrace off
798 * hashall on
799 * histexpand off
800 * history on
801 * ignoreeof off
802 * interactive-comments on
803 * keyword off
804 * monitor on
805 * noclobber off
806 * noexec off
807 * noglob off
808 * nolog off
809 * notify off
810 * nounset off
811 * onecmd off
812 * physical off
813 * pipefail off
814 * posix off
815 * privileged off
816 * verbose off
817 * vi off
818 * xtrace off
819 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800820static const char o_opt_strings[] ALIGN1 =
821 "pipefail\0"
822 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200823 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800824#if ENABLE_HUSH_MODE_X
825 "xtrace\0"
826#endif
827 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100828enum {
829 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800830 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200831 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800832#if ENABLE_HUSH_MODE_X
833 OPT_O_XTRACE,
834#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100835 NUM_OPT_O
836};
837
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839/* Sorted roughly by size (smaller offsets == smaller code) */
840struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000841 /* interactive_fd != 0 means we are an interactive shell.
842 * If we are, then saved_tty_pgrp can also be != 0, meaning
843 * that controlling tty is available. With saved_tty_pgrp == 0,
844 * job control still works, but terminal signals
845 * (^C, ^Z, ^Y, ^\) won't work at all, and background
846 * process groups can only be created with "cmd &".
847 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
848 * to give tty to the foreground process group,
849 * and will take it back when the group is stopped (^Z)
850 * or killed (^C).
851 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000852#if ENABLE_HUSH_INTERACTIVE
853 /* 'interactive_fd' is a fd# open to ctty, if we have one
854 * _AND_ if we decided to act interactively */
855 int interactive_fd;
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +0200856 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000857# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000858#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000859# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000860#endif
861#if ENABLE_FEATURE_EDITING
862 line_input_t *line_input_state;
863#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000864 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200865 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000866 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200867#if ENABLE_HUSH_RANDOM_SUPPORT
868 random_t random_gen;
869#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000870#if ENABLE_HUSH_JOB
871 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100872 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000873 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000874 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400875# define G_saved_tty_pgrp (G.saved_tty_pgrp)
876#else
877# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000878#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200879 /* How deeply are we in context where "set -e" is ignored */
880 int errexit_depth;
881 /* "set -e" rules (do we follow them correctly?):
882 * Exit if pipe, list, or compound command exits with a non-zero status.
883 * Shell does not exit if failed command is part of condition in
884 * if/while, part of && or || list except the last command, any command
885 * in a pipe but the last, or if the command's return value is being
886 * inverted with !. If a compound command other than a subshell returns a
887 * non-zero status because a command failed while -e was being ignored, the
888 * shell does not exit. A trap on ERR, if set, is executed before the shell
889 * exits [ERR is a bashism].
890 *
891 * If a compound command or function executes in a context where -e is
892 * ignored, none of the commands executed within are affected by the -e
893 * setting. If a compound command or function sets -e while executing in a
894 * context where -e is ignored, that setting does not have any effect until
895 * the compound command or the command containing the function call completes.
896 */
897
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100898 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100899#if ENABLE_HUSH_MODE_X
900# define G_x_mode (G.o_opt[OPT_O_XTRACE])
901#else
902# define G_x_mode 0
903#endif
Denys Vlasenkod8740b22019-05-19 19:11:21 +0200904 char opt_s;
Denys Vlasenkof3634582019-06-03 12:21:04 +0200905 char opt_c;
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200906#if ENABLE_HUSH_INTERACTIVE
907 smallint promptmode; /* 0: PS1, 1: PS2 */
908#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000909 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000910#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000911 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000912#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000913#if ENABLE_HUSH_FUNCTIONS
914 /* 0: outside of a function (or sourced file)
915 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000916 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000917 */
918 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200919# define G_flag_return_in_progress (G.flag_return_in_progress)
920#else
921# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000922#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000923 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100924 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000925 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200926 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200927 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000929 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000930 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100931# define G_global_args_malloced (G.global_args_malloced)
932#else
933# define G_global_args_malloced 0
934#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100935#if ENABLE_HUSH_BASH_COMPAT
936 int dead_job_exitcode; /* for "wait -n" */
937#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000938 /* how many non-NULL argv's we have. NB: $# + 1 */
939 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000940 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000941#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000942 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000943#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000944#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000945 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000946 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000947#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200948#if ENABLE_HUSH_GETOPTS
949 unsigned getopt_count;
950#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000951 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200952 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000953 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200954 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200955 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200956 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200957 unsigned var_nest_level;
958#if ENABLE_HUSH_FUNCTIONS
959# if ENABLE_HUSH_LOCAL
960 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200961# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200962 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000963#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000964 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200965#if ENABLE_HUSH_FAST
966 unsigned count_SIGCHLD;
967 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200968 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200969#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100970#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200971 unsigned parse_lineno;
972 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100973#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200974 HFILE *HFILE_list;
Denys Vlasenko21806562019-11-01 14:16:07 +0100975 HFILE *HFILE_stdin;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200976 /* Which signals have non-DFL handler (even with no traps set)?
977 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200978 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200979 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200980 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200981 * Other than these two times, never modified.
982 */
983 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200984#if ENABLE_HUSH_JOB
985 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100986# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200987#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200988# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200989#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100990#if ENABLE_HUSH_TRAP
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +0100991 int pre_trap_exitcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +0100992# if ENABLE_HUSH_FUNCTIONS
993 int return_exitcode;
994# endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000995 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100996# define G_traps G.traps
997#else
998# define G_traps ((char**)NULL)
999#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001000 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +01001001#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001002 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001003#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001004#if ENABLE_HUSH_MODE_X
1005 unsigned x_mode_depth;
1006 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1007 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1008 * for all subsequent output.
1009 */
1010 int x_mode_fd;
1011 o_string x_mode_buf;
1012#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001013#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001014 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001015#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001016 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001017 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001018#if BASH_EPOCH_VARS
1019 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1020#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001021#if ENABLE_FEATURE_EDITING
1022 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1023#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001024};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001025#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001026/* Not #defining name to G.name - this quickly gets unwieldy
1027 * (too many defines). Also, I actually prefer to see when a variable
1028 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001029#define INIT_G() do { \
1030 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001031 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1032 sigfillset(&G.sa.sa_mask); \
1033 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001034} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001035
1036
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001037/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001039#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001041#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_eval(char **argv) FAST_FUNC;
1043static int builtin_exec(char **argv) FAST_FUNC;
1044static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001045#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001046static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001047#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001048#if ENABLE_HUSH_READONLY
1049static int builtin_readonly(char **argv) FAST_FUNC;
1050#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001051#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_fg_bg(char **argv) FAST_FUNC;
1053static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001054#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001055#if ENABLE_HUSH_GETOPTS
1056static int builtin_getopts(char **argv) FAST_FUNC;
1057#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001058#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001060#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001061#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001062static int builtin_history(char **argv) FAST_FUNC;
1063#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001064#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001066#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001067#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001068static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001069#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001070#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001071static int builtin_printf(char **argv) FAST_FUNC;
1072#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001074#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001076#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001077#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001078static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001079#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001080static int builtin_shift(char **argv) FAST_FUNC;
1081static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001082#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001083static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001084#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001085#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001086static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001087#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001088#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001089static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001090#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001091#if ENABLE_HUSH_TIMES
1092static int builtin_times(char **argv) FAST_FUNC;
1093#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001094static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001095#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001096static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001097#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001098#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001099static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001100#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001101#if ENABLE_HUSH_KILL
1102static int builtin_kill(char **argv) FAST_FUNC;
1103#endif
1104#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001105static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001106#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001108static int builtin_break(char **argv) FAST_FUNC;
1109static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001110#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001111#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001112static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001113#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001114
1115/* Table of built-in functions. They can be forked or not, depending on
1116 * context: within pipes, they fork. As simple commands, they do not.
1117 * When used in non-forking context, they can change global variables
1118 * in the parent shell process. If forked, of course they cannot.
1119 * For example, 'unset foo | whatever' will parse and run, but foo will
1120 * still be set at the end. */
1121struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001122 const char *b_cmd;
1123 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001125 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001126# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001127#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001128# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001129#endif
1130};
1131
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001132static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001133 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001134 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001135#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001136 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001137#endif
1138#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001139 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001140#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001141 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001142#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001144#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001145 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1146 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001148#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001150#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001151#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001152 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001153#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001154#if ENABLE_HUSH_GETOPTS
1155 BLTIN("getopts" , builtin_getopts , NULL),
1156#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001157#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001159#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001160#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001161 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001162#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001163#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001164 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001165#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001166#if ENABLE_HUSH_KILL
1167 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1168#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001169#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001171#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001172#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001174#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001175#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001176 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001177#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001178#if ENABLE_HUSH_READONLY
1179 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1180#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001181#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001182 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001183#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001184#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001185 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001186#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001188#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001189 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001190#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001191#if ENABLE_HUSH_TIMES
1192 BLTIN("times" , builtin_times , NULL),
1193#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001194#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001195 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001196#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001197 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001198#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001199 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001200#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001201#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001202 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001203#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001204#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001205 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001206#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001207#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001208 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001209#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001210#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001211 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001212#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001213};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001214/* These builtins won't be used if we are on NOMMU and need to re-exec
1215 * (it's cheaper to run an external program in this case):
1216 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001217static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001218#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001219 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001220#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001221#if BASH_TEST2
1222 BLTIN("[[" , builtin_test , NULL),
1223#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001224#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001225 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001226#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001227#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001228 BLTIN("printf" , builtin_printf , NULL),
1229#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001230 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001231#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001232 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001233#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001234};
1235
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001236
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237/* Debug printouts.
1238 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001239#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001240/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001241# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001242# define debug_enter() (G.debug_indent++)
1243# define debug_leave() (G.debug_indent--)
1244#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001245# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001246# define debug_enter() ((void)0)
1247# define debug_leave() ((void)0)
1248#endif
1249
1250#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001251# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001252#endif
1253
1254#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001255# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001256#endif
1257
Denys Vlasenko3675c372018-07-23 16:31:21 +02001258#ifndef debug_printf_heredoc
1259# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1260#endif
1261
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001262#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001263#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#endif
1265
1266#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001267# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001268#endif
1269
1270#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001271# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001272# define DEBUG_JOBS 1
1273#else
1274# define DEBUG_JOBS 0
1275#endif
1276
1277#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001278# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001279# define DEBUG_EXPAND 1
1280#else
1281# define DEBUG_EXPAND 0
1282#endif
1283
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001284#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001285# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001286#endif
1287
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001288#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001289# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290# define DEBUG_GLOB 1
1291#else
1292# define DEBUG_GLOB 0
1293#endif
1294
Denys Vlasenko2db74612017-07-07 22:07:28 +02001295#ifndef debug_printf_redir
1296# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1297#endif
1298
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001299#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001300# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001301#endif
1302
1303#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001304# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001305#endif
1306
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001307#ifndef debug_printf_prompt
1308# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1309#endif
1310
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001311#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001312# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001313# define DEBUG_CLEAN 1
1314#else
1315# define DEBUG_CLEAN 0
1316#endif
1317
1318#if DEBUG_EXPAND
1319static void debug_print_strings(const char *prefix, char **vv)
1320{
1321 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001322 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001323 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001324 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001325}
1326#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001327# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001328#endif
1329
1330
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001331/* Leak hunting. Use hush_leaktool.sh for post-processing.
1332 */
1333#if LEAK_HUNTING
1334static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001335{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001336 void *ptr = xmalloc((size + 0xff) & ~0xff);
1337 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1338 return ptr;
1339}
1340static void *xxrealloc(int lineno, void *ptr, size_t size)
1341{
1342 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1343 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1344 return ptr;
1345}
1346static char *xxstrdup(int lineno, const char *str)
1347{
1348 char *ptr = xstrdup(str);
1349 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1350 return ptr;
1351}
1352static void xxfree(void *ptr)
1353{
1354 fdprintf(2, "free %p\n", ptr);
1355 free(ptr);
1356}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001357# define xmalloc(s) xxmalloc(__LINE__, s)
1358# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1359# define xstrdup(s) xxstrdup(__LINE__, s)
1360# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001361#endif
1362
1363
1364/* Syntax and runtime errors. They always abort scripts.
1365 * In interactive use they usually discard unparsed and/or unexecuted commands
1366 * and return to the prompt.
1367 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1368 */
1369#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001370# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001371# define syntax_error(lineno, msg) syntax_error(msg)
1372# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1373# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1374# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1375# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001376#endif
1377
Denys Vlasenko39701202017-08-02 19:44:05 +02001378static void die_if_script(void)
1379{
1380 if (!G_interactive_fd) {
1381 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1382 xfunc_error_retval = G.last_exitcode;
1383 xfunc_die();
1384 }
1385}
1386
1387static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001389 va_list p;
1390
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001391#if HUSH_DEBUG >= 2
1392 bb_error_msg("hush.c:%u", lineno);
1393#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001394 va_start(p, fmt);
1395 bb_verror_msg(fmt, p, NULL);
1396 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001397 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001398}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001399
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001400static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001401{
1402 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001403 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001404 else
James Byrne69374872019-07-02 11:35:03 +02001405 bb_simple_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001406 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001407}
1408
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001409static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001410{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001411 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001412 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001413}
1414
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001415static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001416{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001417 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001418//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1419// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001420}
1421
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001422static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001423{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001424 char msg[2] = { ch, '\0' };
1425 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001426}
1427
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001428static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001429{
1430 char msg[2];
1431 msg[0] = ch;
1432 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001433#if HUSH_DEBUG >= 2
1434 bb_error_msg("hush.c:%u", lineno);
1435#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001436 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001437 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001438}
1439
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001440#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001441# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001442# undef syntax_error
1443# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001444# undef syntax_error_unterm_ch
1445# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001446# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001447#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001448# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001449# define syntax_error(msg) syntax_error(__LINE__, msg)
1450# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1451# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1452# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1453# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001454#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001455
Denis Vlasenko552433b2009-04-04 19:29:21 +00001456
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001457/* Utility functions
1458 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001459/* Replace each \x with x in place, return ptr past NUL. */
1460static char *unbackslash(char *src)
1461{
Denys Vlasenko71885402009-09-24 01:44:13 +02001462 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001463 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001464 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001465 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001466 if (*src != '\0') {
1467 /* \x -> x */
1468 *dst++ = *src++;
1469 continue;
1470 }
1471 /* else: "\<nul>". Do not delete this backslash.
1472 * Testcase: eval 'echo ok\'
1473 */
1474 *dst++ = '\\';
1475 /* fallthrough */
1476 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001477 if ((*dst++ = *src++) == '\0')
1478 break;
1479 }
1480 return dst;
1481}
1482
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001483static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001484{
1485 int i;
1486 unsigned count1;
1487 unsigned count2;
1488 char **v;
1489
1490 v = strings;
1491 count1 = 0;
1492 if (v) {
1493 while (*v) {
1494 count1++;
1495 v++;
1496 }
1497 }
1498 count2 = 0;
1499 v = add;
1500 while (*v) {
1501 count2++;
1502 v++;
1503 }
1504 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1505 v[count1 + count2] = NULL;
1506 i = count2;
1507 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001508 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001509 return v;
1510}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001511#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001512static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1513{
1514 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1515 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1516 return ptr;
1517}
1518#define add_strings_to_strings(strings, add, need_to_dup) \
1519 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1520#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001521
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001522/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001523static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001524{
1525 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001526 v[0] = add;
1527 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001528 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001529}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001530#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001531static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1532{
1533 char **ptr = add_string_to_strings(strings, add);
1534 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1535 return ptr;
1536}
1537#define add_string_to_strings(strings, add) \
1538 xx_add_string_to_strings(__LINE__, strings, add)
1539#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001540
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001541static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001542{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001543 char **v;
1544
1545 if (!strings)
1546 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001547 v = strings;
1548 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001549 free(*v);
1550 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001551 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001552 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001553}
1554
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001555static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001556{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001557 int newfd;
1558 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001559 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1560 if (newfd >= 0) {
1561 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1562 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1563 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001564 if (errno == EBUSY)
1565 goto repeat;
1566 if (errno == EINTR)
1567 goto repeat;
1568 }
1569 return newfd;
1570}
1571
Denys Vlasenko657e9002017-07-30 23:34:04 +02001572static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001573{
1574 int newfd;
1575 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001576 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001577 if (newfd < 0) {
1578 if (errno == EBUSY)
1579 goto repeat;
1580 if (errno == EINTR)
1581 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001582 /* fd was not open? */
1583 if (errno == EBADF)
1584 return fd;
1585 xfunc_die();
1586 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001587 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1588 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001589 close(fd);
1590 return newfd;
1591}
1592
1593
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001594/* Manipulating HFILEs */
1595static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001596{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001597 HFILE *fp;
1598 int fd;
1599
1600 fd = STDIN_FILENO;
1601 if (name) {
1602 fd = open(name, O_RDONLY | O_CLOEXEC);
1603 if (fd < 0)
1604 return NULL;
1605 if (O_CLOEXEC == 0) /* ancient libc */
1606 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001607 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001608
1609 fp = xmalloc(sizeof(*fp));
Denys Vlasenko21806562019-11-01 14:16:07 +01001610 if (name == NULL)
1611 G.HFILE_stdin = fp;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001612 fp->fd = fd;
1613 fp->cur = fp->end = fp->buf;
1614 fp->next_hfile = G.HFILE_list;
1615 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001616 return fp;
1617}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001618static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001621 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001622 HFILE *cur = *pp;
1623 if (cur == fp) {
1624 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001625 break;
1626 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001627 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001629 if (fp->fd >= 0)
1630 close(fp->fd);
1631 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001632}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001633static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001634{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001635 int n;
1636
1637 if (fp->fd < 0) {
1638 /* Already saw EOF */
1639 return EOF;
1640 }
1641 /* Try to buffer more input */
1642 fp->cur = fp->buf;
1643 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1644 if (n < 0) {
James Byrne69374872019-07-02 11:35:03 +02001645 bb_simple_perror_msg("read error");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001646 n = 0;
1647 }
1648 fp->end = fp->buf + n;
1649 if (n == 0) {
1650 /* EOF/error */
1651 close(fp->fd);
1652 fp->fd = -1;
1653 return EOF;
1654 }
1655 return (unsigned char)(*fp->cur++);
1656}
1657/* Inlined for common case of non-empty buffer.
1658 */
1659static ALWAYS_INLINE int hfgetc(HFILE *fp)
1660{
1661 if (fp->cur < fp->end)
1662 return (unsigned char)(*fp->cur++);
1663 /* Buffer empty */
1664 return refill_HFILE_and_getc(fp);
1665}
1666static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1667{
1668 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001669 while (fl) {
1670 if (fd == fl->fd) {
1671 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001672 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001673 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001674 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001675 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001676 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001677 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001678#if ENABLE_HUSH_MODE_X
1679 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1680 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1681 return 1; /* "found and moved" */
1682 }
1683#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001684 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001685}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001686#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001687static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001688{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001689 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001690 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001691 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001692 * It is disastrous if we share memory with a vforked parent.
1693 * I'm not sure we never come here after vfork.
1694 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001695 *
1696 * ">" instead of ">=": we don't close fd#0,
1697 * interactive shell uses hfopen(NULL) as stdin input
1698 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1699 * If we'd close it here, then e.g. interactive "set | sort"
1700 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001701 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001702 if (fl->fd > 0)
1703 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001704 close(fl->fd);
1705 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001706 }
1707}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001708#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001709static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001710{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001711 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001712 while (fl) {
1713 if (fl->fd == fd)
1714 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001715 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001716 }
1717 return 0;
1718}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001719
1720
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001721/* Helpers for setting new $n and restoring them back
1722 */
1723typedef struct save_arg_t {
1724 char *sv_argv0;
1725 char **sv_g_argv;
1726 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001727 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001728} save_arg_t;
1729
1730static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1731{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001732 sv->sv_argv0 = argv[0];
1733 sv->sv_g_argv = G.global_argv;
1734 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001735 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001736
1737 argv[0] = G.global_argv[0]; /* retain $0 */
1738 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001739 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001740
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001741 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001742}
1743
1744static void restore_G_args(save_arg_t *sv, char **argv)
1745{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001746#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001747 if (G.global_args_malloced) {
1748 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001749 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001750 while (*++pp) /* note: does not free $0 */
1751 free(*pp);
1752 free(G.global_argv);
1753 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001754#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001755 argv[0] = sv->sv_argv0;
1756 G.global_argv = sv->sv_g_argv;
1757 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001758 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001759}
1760
1761
Denis Vlasenkod5762932009-03-31 11:22:57 +00001762/* Basic theory of signal handling in shell
1763 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001764 * This does not describe what hush does, rather, it is current understanding
1765 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001766 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1767 *
1768 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1769 * is finished or backgrounded. It is the same in interactive and
1770 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001771 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001772 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001773 * backgrounds (i.e. stops) or kills all members of currently running
1774 * pipe.
1775 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001776 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001777 * or by SIGINT in interactive shell.
1778 *
1779 * Trap handlers will execute even within trap handlers. (right?)
1780 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001781 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1782 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001783 *
1784 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001785 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001786 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001787 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001788 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001789 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001790 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001791 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001792 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001793 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001794 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001795 *
1796 * SIGQUIT: ignore
1797 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001798 * SIGHUP (interactive):
1799 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001800 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001801 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1802 * that all pipe members are stopped. Try this in bash:
1803 * while :; do :; done - ^Z does not background it
1804 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001805 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001806 * of the command line, show prompt. NB: ^C does not send SIGINT
1807 * to interactive shell while shell is waiting for a pipe,
1808 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001809 * Example 1: this waits 5 sec, but does not execute ls:
1810 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1811 * Example 2: this does not wait and does not execute ls:
1812 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1813 * Example 3: this does not wait 5 sec, but executes ls:
1814 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001815 * Example 4: this does not wait and does not execute ls:
1816 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 *
1818 * (What happens to signals which are IGN on shell start?)
1819 * (What happens with signal mask on shell start?)
1820 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001821 * Old implementation
1822 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001823 * We use in-kernel pending signal mask to determine which signals were sent.
1824 * We block all signals which we don't want to take action immediately,
1825 * i.e. we block all signals which need to have special handling as described
1826 * above, and all signals which have traps set.
1827 * After each pipe execution, we extract any pending signals via sigtimedwait()
1828 * and act on them.
1829 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001830 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001831 * sigset_t blocked_set: current blocked signal set
1832 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001833 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001834 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001835 * "trap 'cmd' SIGxxx":
1836 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001837 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001838 * unblock signals with special interactive handling
1839 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001840 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001841 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001842 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001843 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001844 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001845 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001846 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001847 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001848 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001849 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001850 * Standard says "When a subshell is entered, traps that are not being ignored
1851 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001852 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001853 *
1854 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001855 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001856 * masked signals are not visible!
1857 *
1858 * New implementation
1859 * ==================
1860 * We record each signal we are interested in by installing signal handler
1861 * for them - a bit like emulating kernel pending signal mask in userspace.
1862 * We are interested in: signals which need to have special handling
1863 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001864 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001865 * After each pipe execution, we extract any pending signals
1866 * and act on them.
1867 *
1868 * unsigned special_sig_mask: a mask of shell-special signals.
1869 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1870 * char *traps[sig] if trap for sig is set (even if it's '').
1871 * sigset_t pending_set: set of sigs we received.
1872 *
1873 * "trap - SIGxxx":
1874 * if sig is in special_sig_mask, set handler back to:
1875 * record_pending_signo, or to IGN if it's a tty stop signal
1876 * if sig is in fatal_sig_mask, set handler back to sigexit.
1877 * else: set handler back to SIG_DFL
1878 * "trap 'cmd' SIGxxx":
1879 * set handler to record_pending_signo.
1880 * "trap '' SIGxxx":
1881 * set handler to SIG_IGN.
1882 * after [v]fork, if we plan to be a shell:
1883 * set signals with special interactive handling to SIG_DFL
1884 * (because child shell is not interactive),
1885 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1886 * after [v]fork, if we plan to exec:
1887 * POSIX says fork clears pending signal mask in child - no need to clear it.
1888 *
1889 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1890 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1891 *
1892 * Note (compat):
1893 * Standard says "When a subshell is entered, traps that are not being ignored
1894 * are set to the default actions". bash interprets it so that traps which
1895 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001896 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001897enum {
1898 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001899 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001900 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001901 | (1 << SIGHUP)
1902 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001904#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001905 | (1 << SIGTTIN)
1906 | (1 << SIGTTOU)
1907 | (1 << SIGTSTP)
1908#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001909 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001910};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001911
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001913{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001914 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001915#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001916 if (sig == SIGCHLD) {
1917 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001918//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 +02001919 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001920#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001921}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001922
Denys Vlasenko0806e402011-05-12 23:06:20 +02001923static sighandler_t install_sighandler(int sig, sighandler_t handler)
1924{
1925 struct sigaction old_sa;
1926
1927 /* We could use signal() to install handlers... almost:
1928 * except that we need to mask ALL signals while handlers run.
1929 * I saw signal nesting in strace, race window isn't small.
1930 * SA_RESTART is also needed, but in Linux, signal()
1931 * sets SA_RESTART too.
1932 */
1933 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1934 /* sigfillset(&G.sa.sa_mask); - already done */
1935 /* G.sa.sa_flags = SA_RESTART; - already done */
1936 G.sa.sa_handler = handler;
1937 sigaction(sig, &G.sa, &old_sa);
1938 return old_sa.sa_handler;
1939}
1940
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001941static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001942
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001943static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001944static void restore_ttypgrp_and__exit(void)
1945{
1946 /* xfunc has failed! die die die */
1947 /* no EXIT traps, this is an escape hatch! */
1948 G.exiting = 1;
1949 hush_exit(xfunc_error_retval);
1950}
1951
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001952#if ENABLE_HUSH_JOB
1953
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001954/* Needed only on some libc:
1955 * It was observed that on exit(), fgetc'ed buffered data
1956 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1957 * With the net effect that even after fork(), not vfork(),
1958 * exit() in NOEXECed applet in "sh SCRIPT":
1959 * noexec_applet_here
1960 * echo END_OF_SCRIPT
1961 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1962 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001963 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001964 * and in `cmd` handling.
1965 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1966 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001967static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001968static void fflush_and__exit(void)
1969{
1970 fflush_all();
1971 _exit(xfunc_error_retval);
1972}
1973
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001974/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001975# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001976/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001977# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001978
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001979/* Restores tty foreground process group, and exits.
1980 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001981 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001982 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001983 * We also call it if xfunc is exiting.
1984 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001985static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001986static void sigexit(int sig)
1987{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001988 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001989 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001990 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1991 /* Disable all signals: job control, SIGPIPE, etc.
1992 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1993 */
1994 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001995 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001996 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001997
1998 /* Not a signal, just exit */
1999 if (sig <= 0)
2000 _exit(- sig);
2001
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002002 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002003}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002004#else
2005
Denys Vlasenko8391c482010-05-22 17:50:43 +02002006# define disable_restore_tty_pgrp_on_exit() ((void)0)
2007# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002008
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002009#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002010
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002011static sighandler_t pick_sighandler(unsigned sig)
2012{
2013 sighandler_t handler = SIG_DFL;
2014 if (sig < sizeof(unsigned)*8) {
2015 unsigned sigmask = (1 << sig);
2016
2017#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002018 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002019 if (G_fatal_sig_mask & sigmask)
2020 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002021 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002022#endif
2023 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002024 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002025 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002026 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002027 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002028 * in an endless loop when we try to do some
2029 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002030 */
2031 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2032 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002033 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002034 }
2035 return handler;
2036}
2037
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002038/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002039static void hush_exit(int exitcode)
2040{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002041#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko76a4e832019-05-19 18:24:52 +02002042 if (G.line_input_state)
2043 save_history(G.line_input_state);
Denys Vlasenkobede2152011-09-04 16:12:33 +02002044#endif
2045
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002046 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002047 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002048 char *argv[3];
2049 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002050 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002051 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002052 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002053 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002054 * "trap" will still show it, if executed
2055 * in the handler */
2056 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002057 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002058
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002059#if ENABLE_FEATURE_CLEAN_UP
2060 {
2061 struct variable *cur_var;
2062 if (G.cwd != bb_msg_unknown)
2063 free((char*)G.cwd);
2064 cur_var = G.top_var;
2065 while (cur_var) {
2066 struct variable *tmp = cur_var;
2067 if (!cur_var->max_len)
2068 free(cur_var->varstr);
2069 cur_var = cur_var->next;
2070 free(tmp);
2071 }
2072 }
2073#endif
2074
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002075 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002076#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002077 sigexit(- (exitcode & 0xff));
2078#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002079 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002080#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002081}
2082
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002083
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002084//TODO: return a mask of ALL handled sigs?
2085static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002086{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002087 int last_sig = 0;
2088
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002089 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002090 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002091
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002092 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002093 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002094 sig = 0;
2095 do {
2096 sig++;
2097 if (sigismember(&G.pending_set, sig)) {
2098 sigdelset(&G.pending_set, sig);
2099 goto got_sig;
2100 }
2101 } while (sig < NSIG);
2102 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002103 got_sig:
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002104#if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002105 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002106 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002107 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002108 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002109 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002110 char *argv[3];
2111 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002112 argv[1] = xstrdup(G_traps[sig]);
2113 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002114 argv[2] = NULL;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002115 G.pre_trap_exitcode = save_rcode = G.last_exitcode;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002116 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002117 free(argv[1]);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002118 G.last_exitcode = save_rcode;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002119 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002120# if ENABLE_HUSH_FUNCTIONS
2121 if (G.return_exitcode >= 0) {
2122 debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
2123 G.last_exitcode = G.return_exitcode;
2124 }
2125# endif
Denys Vlasenkob8709032011-05-08 21:20:01 +02002126 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002127 } /* else: "" trap, ignoring signal */
2128 continue;
2129 }
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002130#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002131 /* not a trap: special action */
2132 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002133 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002134 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002135 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002136 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002137 break;
2138#if ENABLE_HUSH_JOB
2139 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002140//TODO: why are we doing this? ash and dash don't do this,
2141//they have no handler for SIGHUP at all,
2142//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002143 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002144 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002145 /* bash is observed to signal whole process groups,
2146 * not individual processes */
2147 for (job = G.job_list; job; job = job->next) {
2148 if (job->pgrp <= 0)
2149 continue;
2150 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2151 if (kill(- job->pgrp, SIGHUP) == 0)
2152 kill(- job->pgrp, SIGCONT);
2153 }
2154 sigexit(SIGHUP);
2155 }
2156#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002157#if ENABLE_HUSH_FAST
2158 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002159 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002160 G.count_SIGCHLD++;
2161//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2162 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002163 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002164 * This simplifies wait builtin a bit.
2165 */
2166 break;
2167#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002168 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002169 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002170 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002171 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002172 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002173 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002174 * in interactive shell, because TERM is ignored.
2175 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002176 break;
2177 }
2178 }
2179 return last_sig;
2180}
2181
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002182
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002183static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002184{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002185 if (force || G.cwd == NULL) {
2186 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2187 * we must not try to free(bb_msg_unknown) */
2188 if (G.cwd == bb_msg_unknown)
2189 G.cwd = NULL;
2190 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2191 if (!G.cwd)
2192 G.cwd = bb_msg_unknown;
2193 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002194 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002195}
2196
Denis Vlasenko83506862007-11-23 13:11:42 +00002197
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002198/*
2199 * Shell and environment variable support
2200 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002201static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002203 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002204 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002206 pp = &G.top_var;
2207 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002208 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002209 return pp;
2210 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002211 }
2212 return NULL;
2213}
2214
Denys Vlasenko03dad222010-01-12 23:29:57 +01002215static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002216{
Denys Vlasenko29082232010-07-16 13:52:32 +02002217 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002218 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002219
2220 if (G.expanded_assignments) {
2221 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002222 while (*cpp) {
2223 char *cp = *cpp;
2224 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2225 return cp + len + 1;
2226 cpp++;
2227 }
2228 }
2229
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002230 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002231 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002232 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002233
Denys Vlasenkodea47882009-10-09 15:40:49 +02002234 if (strcmp(name, "PPID") == 0)
2235 return utoa(G.root_ppid);
2236 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002237#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002238 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002239 return utoa(next_random(&G.random_gen));
2240#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002241#if ENABLE_HUSH_LINENO_VAR
2242 if (strcmp(name, "LINENO") == 0)
2243 return utoa(G.execute_lineno);
2244#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002245#if BASH_EPOCH_VARS
2246 {
2247 const char *fmt = NULL;
2248 if (strcmp(name, "EPOCHSECONDS") == 0)
2249 fmt = "%lu";
2250 else if (strcmp(name, "EPOCHREALTIME") == 0)
2251 fmt = "%lu.%06u";
2252 if (fmt) {
2253 struct timeval tv;
2254 gettimeofday(&tv, NULL);
2255 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2256 (unsigned)tv.tv_usec);
2257 return G.epoch_buf;
2258 }
2259 }
2260#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261 return NULL;
2262}
2263
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002264#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002265static void handle_changed_special_names(const char *name, unsigned name_len)
2266{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002267 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002268 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002269 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002270 return;
2271 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002272 }
2273}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002274#else
2275/* Do not even bother evaluating arguments */
2276# define handle_changed_special_names(...) ((void)0)
2277#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002278
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002279/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002280 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002281 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002282#define SETFLAG_EXPORT (1 << 0)
2283#define SETFLAG_UNEXPORT (1 << 1)
2284#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002285#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002286static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002287{
Denys Vlasenko61407802018-04-04 21:14:28 +02002288 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002290 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002291 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002292 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002293 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002294 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002295
Denis Vlasenko950bd722009-04-21 11:23:56 +00002296 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002297 if (HUSH_DEBUG && !eq_sign)
James Byrne69374872019-07-02 11:35:03 +02002298 bb_simple_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002299
Denis Vlasenko950bd722009-04-21 11:23:56 +00002300 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002301 cur_pp = &G.top_var;
2302 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002303 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002304 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002305 continue;
2306 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002307
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002308 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002309 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002310 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002312//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2313//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002314 return -1;
2315 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002316 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002317 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2318 *eq_sign = '\0';
2319 unsetenv(str);
2320 *eq_sign = '=';
2321 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002322 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002323 /* bash 3.2.33(1) and exported vars:
2324 * # export z=z
2325 * # f() { local z=a; env | grep ^z; }
2326 * # f
2327 * z=a
2328 * # env | grep ^z
2329 * z=z
2330 */
2331 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002332 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002333 /* New variable is local ("local VAR=VAL" or
2334 * "VAR=VAL cmd")
2335 * and existing one is global, or local
2336 * on a lower level that new one.
2337 * Remove it from global variable list:
2338 */
2339 *cur_pp = cur->next;
2340 if (G.shadowed_vars_pp) {
2341 /* Save in "shadowed" list */
2342 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2343 cur->flg_export ? "exported " : "",
2344 cur->varstr, cur->var_nest_level, str, local_lvl
2345 );
2346 cur->next = *G.shadowed_vars_pp;
2347 *G.shadowed_vars_pp = cur;
2348 } else {
2349 /* Came from pseudo_exec_argv(), no need to save: delete it */
2350 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2351 cur->flg_export ? "exported " : "",
2352 cur->varstr, cur->var_nest_level, str, local_lvl
2353 );
2354 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2355 free_me = cur->varstr; /* then free it later */
2356 free(cur);
2357 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002358 break;
2359 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002360
Denis Vlasenko950bd722009-04-21 11:23:56 +00002361 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002362 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002363 free_and_exp:
2364 free(str);
2365 goto exp;
2366 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002367
2368 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002369 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002370 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002371 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002372 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002373 strcpy(cur->varstr, str);
2374 goto free_and_exp;
2375 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002376 /* Can't reuse */
2377 cur->max_len = 0;
2378 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002379 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002380 /* max_len == 0 signifies "malloced" var, which we can
2381 * (and have to) free. But we can't free(cur->varstr) here:
2382 * if cur->flg_export is 1, it is in the environment.
2383 * We should either unsetenv+free, or wait until putenv,
2384 * then putenv(new)+free(old).
2385 */
2386 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002387 goto set_str_and_exp;
2388 }
2389
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002390 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002391 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002392 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002393 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002394 cur->next = *cur_pp;
2395 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002396
2397 set_str_and_exp:
2398 cur->varstr = str;
2399 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002400#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002401 if (flags & SETFLAG_MAKE_RO) {
2402 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002403 }
2404#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002405 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002406 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002407 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002408 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002409 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002410 cur->flg_export = 0;
2411 /* unsetenv was already done */
2412 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002413 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002414 retval = putenv(cur->varstr);
2415 /* fall through to "free(free_me)" -
2416 * only now we can free old exported malloced string
2417 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002418 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002420 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002421
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002422 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002423
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002424 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002425}
2426
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002427static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2428{
2429 char *var = xasprintf("%s=%s", name, val);
2430 set_local_var(var, /*flag:*/ 0);
2431}
2432
Denys Vlasenko6db47842009-09-05 20:15:17 +02002433/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002434static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002435{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002436 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002437}
2438
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002439#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002440static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002441{
2442 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002443 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002444
Denys Vlasenko61407802018-04-04 21:14:28 +02002445 cur_pp = &G.top_var;
2446 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002447 if (strncmp(cur->varstr, name, name_len) == 0
2448 && cur->varstr[name_len] == '='
2449 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002450 if (cur->flg_read_only) {
2451 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002452 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002453 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002454
Denys Vlasenko61407802018-04-04 21:14:28 +02002455 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002456 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2457 bb_unsetenv(cur->varstr);
2458 if (!cur->max_len)
2459 free(cur->varstr);
2460 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002461
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002462 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002464 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002465 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002466
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002467 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002468 handle_changed_special_names(name, name_len);
2469
Mike Frysingerd690f682009-03-30 06:50:54 +00002470 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002471}
2472
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002473static int unset_local_var(const char *name)
2474{
2475 return unset_local_var_len(name, strlen(name));
2476}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002477#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002478
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002479
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002480/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002481 * Helpers for "var1=val1 var2=val2 cmd" feature
2482 */
2483static void add_vars(struct variable *var)
2484{
2485 struct variable *next;
2486
2487 while (var) {
2488 next = var->next;
2489 var->next = G.top_var;
2490 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002491 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002492 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002493 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002494 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002495 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002496 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002497 var = next;
2498 }
2499}
2500
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002501/* We put strings[i] into variable table and possibly putenv them.
2502 * If variable is read only, we can free the strings[i]
2503 * which attempts to overwrite it.
2504 * The strings[] vector itself is freed.
2505 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002506static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002507{
2508 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002509
2510 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002511 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002512
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002513 s = strings;
2514 while (*s) {
2515 struct variable *var_p;
2516 struct variable **var_pp;
2517 char *eq;
2518
2519 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002520 if (HUSH_DEBUG && !eq)
James Byrne69374872019-07-02 11:35:03 +02002521 bb_simple_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002522 var_pp = get_ptr_to_local_var(*s, eq - *s);
2523 if (var_pp) {
2524 var_p = *var_pp;
2525 if (var_p->flg_read_only) {
2526 char **p;
2527 bb_error_msg("%s: readonly variable", *s);
2528 /*
2529 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2530 * If VAR is readonly, leaving it in the list
2531 * after asssignment error (msg above)
2532 * causes doubled error message later, on unset.
2533 */
2534 debug_printf_env("removing/freeing '%s' element\n", *s);
2535 free(*s);
2536 p = s;
2537 do { *p = p[1]; p++; } while (*p);
2538 goto next;
2539 }
2540 /* below, set_local_var() with nest level will
2541 * "shadow" (remove) this variable from
2542 * global linked list.
2543 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002544 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002545 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2546 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002547 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002548 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002549 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002550 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002551}
2552
2553
2554/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002555 * Unicode helper
2556 */
2557static void reinit_unicode_for_hush(void)
2558{
2559 /* Unicode support should be activated even if LANG is set
2560 * _during_ shell execution, not only if it was set when
2561 * shell was started. Therefore, re-check LANG every time:
2562 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002563 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2564 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002565 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002566 const char *s = get_local_var_value("LC_ALL");
2567 if (!s) s = get_local_var_value("LC_CTYPE");
2568 if (!s) s = get_local_var_value("LANG");
2569 reinit_unicode(s);
2570 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002571}
2572
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002573/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002574 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576
2577#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002578/* To test correct lineedit/interactive behavior, type from command line:
2579 * echo $P\
2580 * \
2581 * AT\
2582 * H\
2583 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002584 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002585 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002586static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002587{
2588 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002589
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002590 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002591
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002592# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2593 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2594 if (!prompt_str)
2595 prompt_str = "";
2596# else
2597 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002598 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002599 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2600 free(G.PS1);
2601 /* bash uses $PWD value, even if it is set by user.
2602 * It uses current dir only if PWD is unset.
2603 * We always use current dir. */
2604 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002605 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002606# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002607 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002608 return prompt_str;
2609}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002610static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002611{
2612 int r;
2613 const char *prompt_str;
2614
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002615 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002616# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002617 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002618 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002619 if (G.flag_SIGINT) {
2620 /* There was ^C'ed, make it look prettier: */
2621 bb_putchar('\n');
2622 G.flag_SIGINT = 0;
2623 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002624 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002625 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002626 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002627 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002628 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002629 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002630 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002631 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002632 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002633 if (r != 0 && !G.flag_SIGINT)
2634 break;
2635 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002636 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2637 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002638 G.last_exitcode = 128 + SIGINT;
2639 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002640 if (r < 0) {
2641 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002642 i->p = NULL;
2643 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002644 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002645 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002646 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002647 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002648# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002649 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002650 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002651 if (i->last_char == '\0' || i->last_char == '\n') {
2652 /* Why check_and_run_traps here? Try this interactively:
2653 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2654 * $ <[enter], repeatedly...>
2655 * Without check_and_run_traps, handler never runs.
2656 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002657 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002658 fputs(prompt_str, stdout);
2659 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002660 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002661//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002662 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002663 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2664 * no ^C masking happens during fgetc, no special code for ^C:
2665 * it generates SIGINT as usual.
2666 */
2667 check_and_run_traps();
2668 if (G.flag_SIGINT)
2669 G.last_exitcode = 128 + SIGINT;
2670 if (r != '\0')
2671 break;
2672 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002673 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002674# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002675}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002676/* This is the magic location that prints prompts
2677 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002678static int fgetc_interactive(struct in_str *i)
2679{
2680 int ch;
2681 /* If it's interactive stdin, get new line. */
Denys Vlasenko21806562019-11-01 14:16:07 +01002682 if (G_interactive_fd && i->file == G.HFILE_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002683 /* Returns first char (or EOF), the rest is in i->p[] */
2684 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002685 G.promptmode = 1; /* PS2 */
2686 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002687 } else {
2688 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002689 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002690 }
2691 return ch;
2692}
2693#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002694static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002695{
2696 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002697 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002698 return ch;
2699}
2700#endif /* INTERACTIVE */
2701
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002702static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002703{
2704 int ch;
2705
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002706 if (!i->file) {
2707 /* string-based in_str */
2708 ch = (unsigned char)*i->p;
2709 if (ch != '\0') {
2710 i->p++;
2711 i->last_char = ch;
2712 return ch;
2713 }
2714 return EOF;
2715 }
2716
2717 /* FILE-based in_str */
2718
Denys Vlasenko4074d492016-09-30 01:49:53 +02002719#if ENABLE_FEATURE_EDITING
2720 /* This can be stdin, check line editing char[] buffer */
2721 if (i->p && *i->p != '\0') {
2722 ch = (unsigned char)*i->p++;
2723 goto out;
2724 }
2725#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002726 /* peek_buf[] is an int array, not char. Can contain EOF. */
2727 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002728 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002729 int ch2 = i->peek_buf[1];
2730 i->peek_buf[0] = ch2;
2731 if (ch2 == 0) /* very likely, avoid redundant write */
2732 goto out;
2733 i->peek_buf[1] = 0;
2734 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002735 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002736
Denys Vlasenko4074d492016-09-30 01:49:53 +02002737 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002738 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002739 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002740 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002741#if ENABLE_HUSH_LINENO_VAR
2742 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002743 G.parse_lineno++;
2744 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002745 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002746#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747 return ch;
2748}
2749
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002750static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002751{
2752 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002753
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002754 if (!i->file) {
2755 /* string-based in_str */
2756 /* Doesn't report EOF on NUL. None of the callers care. */
2757 return (unsigned char)*i->p;
2758 }
2759
2760 /* FILE-based in_str */
2761
Denys Vlasenko4074d492016-09-30 01:49:53 +02002762#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002763 /* This can be stdin, check line editing char[] buffer */
2764 if (i->p && *i->p != '\0')
2765 return (unsigned char)*i->p;
2766#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002767 /* peek_buf[] is an int array, not char. Can contain EOF. */
2768 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002769 if (ch != 0)
2770 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002771
Denys Vlasenko4074d492016-09-30 01:49:53 +02002772 /* Need to get a new char */
2773 ch = fgetc_interactive(i);
2774 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2775
2776 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2777#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2778 if (i->p) {
2779 i->p -= 1;
2780 return ch;
2781 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002782#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002783 i->peek_buf[0] = ch;
2784 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002785 return ch;
2786}
2787
Denys Vlasenko4074d492016-09-30 01:49:53 +02002788/* Only ever called if i_peek() was called, and did not return EOF.
2789 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2790 * not end-of-line. Therefore we never need to read a new editing line here.
2791 */
2792static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002793{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002794 int ch;
2795
2796 /* There are two cases when i->p[] buffer exists.
2797 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002798 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002799 * In both cases, we know that i->p[0] exists and not NUL, and
2800 * the peek2 result is in i->p[1].
2801 */
2802 if (i->p)
2803 return (unsigned char)i->p[1];
2804
2805 /* Now we know it is a file-based in_str. */
2806
2807 /* peek_buf[] is an int array, not char. Can contain EOF. */
2808 /* Is there 2nd char? */
2809 ch = i->peek_buf[1];
2810 if (ch == 0) {
2811 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002812 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002813 i->peek_buf[1] = ch;
2814 }
2815
2816 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2817 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002818}
2819
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002820static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2821{
2822 for (;;) {
2823 int ch, ch2;
2824
2825 ch = i_getch(input);
2826 if (ch != '\\')
2827 return ch;
2828 ch2 = i_peek(input);
2829 if (ch2 != '\n')
2830 return ch;
2831 /* backslash+newline, skip it */
2832 i_getch(input);
2833 }
2834}
2835
2836/* Note: this function _eats_ \<newline> pairs, safe to use plain
2837 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2838 */
2839static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2840{
2841 for (;;) {
2842 int ch, ch2;
2843
2844 ch = i_peek(input);
2845 if (ch != '\\')
2846 return ch;
2847 ch2 = i_peek2(input);
2848 if (ch2 != '\n')
2849 return ch;
2850 /* backslash+newline, skip it */
2851 i_getch(input);
2852 i_getch(input);
2853 }
2854}
2855
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002856static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002857{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002858 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002859 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002860 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002861}
2862
2863static void setup_string_in_str(struct in_str *i, const char *s)
2864{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002865 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002866 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002867 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002868}
2869
2870
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002871/*
2872 * o_string support
2873 */
2874#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002875
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002876static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002877{
2878 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002879 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002880 if (o->data)
2881 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002882}
2883
Denys Vlasenko18567402018-07-20 17:51:31 +02002884static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002885{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002886 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002887 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002888}
2889
Denys Vlasenko18567402018-07-20 17:51:31 +02002890static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002891{
2892 free(o->data);
2893}
2894
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002895static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002896{
2897 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002898 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002899 o->data = xrealloc(o->data, 1 + o->maxlen);
2900 }
2901}
2902
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002903static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002904{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002905 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002906 if (o->length < o->maxlen) {
2907 /* likely. avoid o_grow_by() call */
2908 add:
2909 o->data[o->length] = ch;
2910 o->length++;
2911 o->data[o->length] = '\0';
2912 return;
2913 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002914 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002915 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002916}
2917
Denys Vlasenko657086a2016-09-29 18:07:42 +02002918#if 0
2919/* Valid only if we know o_string is not empty */
2920static void o_delchr(o_string *o)
2921{
2922 o->length--;
2923 o->data[o->length] = '\0';
2924}
2925#endif
2926
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002927static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002928{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002929 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002930 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002931 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002932}
2933
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002934static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002935{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002936 o_addblock(o, str, strlen(str));
2937}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002938
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002939static void o_addstr_with_NUL(o_string *o, const char *str)
2940{
2941 o_addblock(o, str, strlen(str) + 1);
2942}
2943
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002944#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002945static void nommu_addchr(o_string *o, int ch)
2946{
2947 if (o)
2948 o_addchr(o, ch);
2949}
2950#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002951# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002952#endif
2953
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002954#if ENABLE_HUSH_MODE_X
2955static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002956{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002957 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002958}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002959static void x_mode_addstr(const char *str)
2960{
2961 o_addstr(&G.x_mode_buf, str);
2962}
2963static void x_mode_addblock(const char *str, int len)
2964{
2965 o_addblock(&G.x_mode_buf, str, len);
2966}
2967static void x_mode_prefix(void)
2968{
2969 int n = G.x_mode_depth;
2970 do x_mode_addchr('+'); while (--n >= 0);
2971}
2972static void x_mode_flush(void)
2973{
2974 int len = G.x_mode_buf.length;
2975 if (len <= 0)
2976 return;
2977 if (G.x_mode_fd > 0) {
2978 G.x_mode_buf.data[len] = '\n';
2979 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2980 }
2981 G.x_mode_buf.length = 0;
2982}
2983#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002984
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002985/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002986 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002987 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2988 * Apparently, on unquoted $v bash still does globbing
2989 * ("v='*.txt'; echo $v" prints all .txt files),
2990 * but NOT brace expansion! Thus, there should be TWO independent
2991 * quoting mechanisms on $v expansion side: one protects
2992 * $v from brace expansion, and other additionally protects "$v" against globbing.
2993 * We have only second one.
2994 */
2995
Denys Vlasenko9e800222010-10-03 14:28:04 +02002996#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002997# define MAYBE_BRACES "{}"
2998#else
2999# define MAYBE_BRACES ""
3000#endif
3001
Eric Andersen25f27032001-04-26 23:22:31 +00003002/* My analysis of quoting semantics tells me that state information
3003 * is associated with a destination, not a source.
3004 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003005static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003006{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003007 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003008 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003009 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003010 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003011 o_grow_by(o, sz);
3012 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003013 o->data[o->length] = '\\';
3014 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003015 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003016 o->data[o->length] = ch;
3017 o->length++;
3018 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003019}
3020
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003021static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003022{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003023 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003024 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3025 && strchr("*?[\\" MAYBE_BRACES, ch)
3026 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003027 sz++;
3028 o->data[o->length] = '\\';
3029 o->length++;
3030 }
3031 o_grow_by(o, sz);
3032 o->data[o->length] = ch;
3033 o->length++;
3034 o->data[o->length] = '\0';
3035}
3036
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003037static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003038{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003039 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003040 char ch;
3041 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003042 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003043 if (ordinary_cnt > len) /* paranoia */
3044 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003045 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003046 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003047 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003048 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003049 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003050
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003051 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003052 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003053 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003054 sz++;
3055 o->data[o->length] = '\\';
3056 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003057 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003058 o_grow_by(o, sz);
3059 o->data[o->length] = ch;
3060 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003061 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003062 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003063}
3064
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003065static void o_addQblock(o_string *o, const char *str, int len)
3066{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003067 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003068 o_addblock(o, str, len);
3069 return;
3070 }
3071 o_addqblock(o, str, len);
3072}
3073
Denys Vlasenko38292b62010-09-05 14:49:40 +02003074static void o_addQstr(o_string *o, const char *str)
3075{
3076 o_addQblock(o, str, strlen(str));
3077}
3078
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003079/* A special kind of o_string for $VAR and `cmd` expansion.
3080 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003081 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003082 * list[i] contains an INDEX (int!) into this string data.
3083 * It means that if list[] needs to grow, data needs to be moved higher up
3084 * but list[i]'s need not be modified.
3085 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003086 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003087 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3088 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003089#if DEBUG_EXPAND || DEBUG_GLOB
3090static void debug_print_list(const char *prefix, o_string *o, int n)
3091{
3092 char **list = (char**)o->data;
3093 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3094 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003095
3096 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003097 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 +02003098 prefix, list, n, string_start, o->length, o->maxlen,
3099 !!(o->o_expflags & EXP_FLAG_GLOB),
3100 o->has_quoted_part,
3101 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003102 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003103 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003104 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3105 o->data + (int)(uintptr_t)list[i] + string_start,
3106 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003107 i++;
3108 }
3109 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003110 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003111 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003112 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003113 }
3114}
3115#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003116# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003117#endif
3118
3119/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3120 * in list[n] so that it points past last stored byte so far.
3121 * It returns n+1. */
3122static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003123{
3124 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003125 int string_start;
3126 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003127
3128 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003129 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3130 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003131 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003132 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003133 /* list[n] points to string_start, make space for 16 more pointers */
3134 o->maxlen += 0x10 * sizeof(list[0]);
3135 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003136 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003137 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003138 /*
3139 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3140 * check. (grep for -prev-ifs-check-).
3141 * Ensure that argv[-1][last] is not garbage
3142 * but zero bytes, to save index check there.
3143 */
3144 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003145 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003146 } else {
3147 debug_printf_list("list[%d]=%d string_start=%d\n",
3148 n, string_len, string_start);
3149 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003150 } else {
3151 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003152 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3153 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003154 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3155 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003156 o->has_empty_slot = 0;
3157 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003158 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003159 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003160 return n + 1;
3161}
3162
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003163/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003164static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003165{
3166 char **list = (char**)o->data;
3167 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3168
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003169 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003170}
3171
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003172/*
3173 * Globbing routines.
3174 *
3175 * Most words in commands need to be globbed, even ones which are
3176 * (single or double) quoted. This stems from the possiblity of
3177 * constructs like "abc"* and 'abc'* - these should be globbed.
3178 * Having a different code path for fully-quoted strings ("abc",
3179 * 'abc') would only help performance-wise, but we still need
3180 * code for partially-quoted strings.
3181 *
3182 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003183 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003184 * to a string, then globbed, and if globbing does not match anything,
3185 * it is used verbatim". Here are two examples where it fails:
3186 *
3187 * echo 'b\*'?
3188 *
3189 * The globbing can't be avoided (because of '?' at the end).
3190 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3191 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003192 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003193 * Now, look at this:
3194 *
3195 * v='\\\*'; echo b$v?
3196 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003197 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003198 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003199 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003200 *
3201 * ash implements this by having an encoded representation of the word
3202 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3203 * Glob pattern is derived from it. If glob fails, the decision what result
3204 * should be is made using that encoded representation. Not glob pattern.
3205 */
3206
Denys Vlasenko9e800222010-10-03 14:28:04 +02003207#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003208/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3209 * first, it processes even {a} (no commas), second,
3210 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003211 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003212 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003213
3214/* Helper */
3215static int glob_needed(const char *s)
3216{
3217 while (*s) {
3218 if (*s == '\\') {
3219 if (!s[1])
3220 return 0;
3221 s += 2;
3222 continue;
3223 }
3224 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3225 return 1;
3226 s++;
3227 }
3228 return 0;
3229}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003230/* Return pointer to next closing brace or to comma */
3231static const char *next_brace_sub(const char *cp)
3232{
3233 unsigned depth = 0;
3234 cp++;
3235 while (*cp != '\0') {
3236 if (*cp == '\\') {
3237 if (*++cp == '\0')
3238 break;
3239 cp++;
3240 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003241 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003242 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003243 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003244 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003245 depth++;
3246 }
3247
3248 return *cp != '\0' ? cp : NULL;
3249}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003250/* Recursive brace globber. Note: may garble pattern[]. */
3251static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003252{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003253 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003254 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003255 const char *next;
3256 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003257 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003258 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003259
3260 debug_printf_glob("glob_brace('%s')\n", pattern);
3261
3262 begin = pattern;
3263 while (1) {
3264 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003265 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003266 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003267 /* Find the first sub-pattern and at the same time
3268 * find the rest after the closing brace */
3269 next = next_brace_sub(begin);
3270 if (next == NULL) {
3271 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003272 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003273 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003274 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003275 /* "{abc}" with no commas - illegal
3276 * brace expr, disregard and skip it */
3277 begin = next + 1;
3278 continue;
3279 }
3280 break;
3281 }
3282 if (*begin == '\\' && begin[1] != '\0')
3283 begin++;
3284 begin++;
3285 }
3286 debug_printf_glob("begin:%s\n", begin);
3287 debug_printf_glob("next:%s\n", next);
3288
3289 /* Now find the end of the whole brace expression */
3290 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003291 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003292 rest = next_brace_sub(rest);
3293 if (rest == NULL) {
3294 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003295 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003296 }
3297 debug_printf_glob("rest:%s\n", rest);
3298 }
3299 rest_len = strlen(++rest) + 1;
3300
3301 /* We are sure the brace expression is well-formed */
3302
3303 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003304 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003305
3306 /* We have a brace expression. BEGIN points to the opening {,
3307 * NEXT points past the terminator of the first element, and REST
3308 * points past the final }. We will accumulate result names from
3309 * recursive runs for each brace alternative in the buffer using
3310 * GLOB_APPEND. */
3311
3312 p = begin + 1;
3313 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003314 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003315 memcpy(
3316 mempcpy(
3317 mempcpy(new_pattern_buf,
3318 /* We know the prefix for all sub-patterns */
3319 pattern, begin - pattern),
3320 p, next - p),
3321 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003322
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003323 /* Note: glob_brace() may garble new_pattern_buf[].
3324 * That's why we re-copy prefix every time (1st memcpy above).
3325 */
3326 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003327 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003328 /* We saw the last entry */
3329 break;
3330 }
3331 p = next + 1;
3332 next = next_brace_sub(next);
3333 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003334 free(new_pattern_buf);
3335 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003336
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003337 simple_glob:
3338 {
3339 int gr;
3340 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003341
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003342 memset(&globdata, 0, sizeof(globdata));
3343 gr = glob(pattern, 0, NULL, &globdata);
3344 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3345 if (gr != 0) {
3346 if (gr == GLOB_NOMATCH) {
3347 globfree(&globdata);
3348 /* NB: garbles parameter */
3349 unbackslash(pattern);
3350 o_addstr_with_NUL(o, pattern);
3351 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3352 return o_save_ptr_helper(o, n);
3353 }
3354 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003355 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003356 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3357 * but we didn't specify it. Paranoia again. */
3358 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3359 }
3360 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3361 char **argv = globdata.gl_pathv;
3362 while (1) {
3363 o_addstr_with_NUL(o, *argv);
3364 n = o_save_ptr_helper(o, n);
3365 argv++;
3366 if (!*argv)
3367 break;
3368 }
3369 }
3370 globfree(&globdata);
3371 }
3372 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003373}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003374/* Performs globbing on last list[],
3375 * saving each result as a new list[].
3376 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003377static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003378{
3379 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003380
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003381 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003382 if (!o->data)
3383 return o_save_ptr_helper(o, n);
3384 pattern = o->data + o_get_last_ptr(o, n);
3385 debug_printf_glob("glob pattern '%s'\n", pattern);
3386 if (!glob_needed(pattern)) {
3387 /* unbackslash last string in o in place, fix length */
3388 o->length = unbackslash(pattern) - o->data;
3389 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3390 return o_save_ptr_helper(o, n);
3391 }
3392
3393 copy = xstrdup(pattern);
3394 /* "forget" pattern in o */
3395 o->length = pattern - o->data;
3396 n = glob_brace(copy, o, n);
3397 free(copy);
3398 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003399 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003400 return n;
3401}
3402
Denys Vlasenko238081f2010-10-03 14:26:26 +02003403#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003404
3405/* Helper */
3406static int glob_needed(const char *s)
3407{
3408 while (*s) {
3409 if (*s == '\\') {
3410 if (!s[1])
3411 return 0;
3412 s += 2;
3413 continue;
3414 }
3415 if (*s == '*' || *s == '[' || *s == '?')
3416 return 1;
3417 s++;
3418 }
3419 return 0;
3420}
3421/* Performs globbing on last list[],
3422 * saving each result as a new list[].
3423 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003424static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003425{
3426 glob_t globdata;
3427 int gr;
3428 char *pattern;
3429
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003430 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003431 if (!o->data)
3432 return o_save_ptr_helper(o, n);
3433 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003434 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003435 if (!glob_needed(pattern)) {
3436 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003437 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003438 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003439 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003440 return o_save_ptr_helper(o, n);
3441 }
3442
3443 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003444 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3445 * If we glob "*.\*" and don't find anything, we need
3446 * to fall back to using literal "*.*", but GLOB_NOCHECK
3447 * will return "*.\*"!
3448 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003449 gr = glob(pattern, 0, NULL, &globdata);
3450 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003451 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003452 if (gr == GLOB_NOMATCH) {
3453 globfree(&globdata);
3454 goto literal;
3455 }
3456 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003457 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003458 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3459 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003460 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003461 }
3462 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3463 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003464 /* "forget" pattern in o */
3465 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003466 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003467 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003468 n = o_save_ptr_helper(o, n);
3469 argv++;
3470 if (!*argv)
3471 break;
3472 }
3473 }
3474 globfree(&globdata);
3475 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003476 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003477 return n;
3478}
3479
Denys Vlasenko238081f2010-10-03 14:26:26 +02003480#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003481
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003482/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003483 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003484static int o_save_ptr(o_string *o, int n)
3485{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003486 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003487 /* If o->has_empty_slot, list[n] was already globbed
3488 * (if it was requested back then when it was filled)
3489 * so don't do that again! */
3490 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003491 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003492 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003493 return o_save_ptr_helper(o, n);
3494}
3495
3496/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003497static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003498{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003499 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003500 int string_start;
3501
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003502 if (DEBUG_EXPAND)
3503 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003504 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003505 list = (char**)o->data;
3506 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3507 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003508 while (n) {
3509 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003510 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003511 }
3512 return list;
3513}
3514
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003515static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003516
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003517/* Returns pi->next - next pipe in the list */
3518static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003519{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003520 struct pipe *next;
3521 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003522
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003523 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003524 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003525 struct command *command;
3526 struct redir_struct *r, *rnext;
3527
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003528 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003529 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003530 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003531 if (DEBUG_CLEAN) {
3532 int a;
3533 char **p;
3534 for (a = 0, p = command->argv; *p; a++, p++) {
3535 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3536 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003537 }
3538 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003539 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003540 }
3541 /* not "else if": on syntax error, we may have both! */
3542 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003543 debug_printf_clean(" begin group (cmd_type:%d)\n",
3544 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003545 free_pipe_list(command->group);
3546 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003547 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003548 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003549 /* else is crucial here.
3550 * If group != NULL, child_func is meaningless */
3551#if ENABLE_HUSH_FUNCTIONS
3552 else if (command->child_func) {
3553 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3554 command->child_func->parent_cmd = NULL;
3555 }
3556#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003557#if !BB_MMU
3558 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003559 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003560#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003561 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003562 debug_printf_clean(" redirect %d%s",
3563 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003564 /* guard against the case >$FOO, where foo is unset or blank */
3565 if (r->rd_filename) {
3566 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3567 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003568 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003569 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003570 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003571 rnext = r->next;
3572 free(r);
3573 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003574 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003575 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003577 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003578#if ENABLE_HUSH_JOB
3579 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003580 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003581#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003582
3583 next = pi->next;
3584 free(pi);
3585 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003586}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003587
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003588static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003589{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003590 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003591#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003592 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003593#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003594 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003595 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003596 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003597}
3598
3599
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003600/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003601
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003602#ifndef debug_print_tree
3603static void debug_print_tree(struct pipe *pi, int lvl)
3604{
3605 static const char *const PIPE[] = {
3606 [PIPE_SEQ] = "SEQ",
3607 [PIPE_AND] = "AND",
3608 [PIPE_OR ] = "OR" ,
3609 [PIPE_BG ] = "BG" ,
3610 };
3611 static const char *RES[] = {
3612 [RES_NONE ] = "NONE" ,
3613# if ENABLE_HUSH_IF
3614 [RES_IF ] = "IF" ,
3615 [RES_THEN ] = "THEN" ,
3616 [RES_ELIF ] = "ELIF" ,
3617 [RES_ELSE ] = "ELSE" ,
3618 [RES_FI ] = "FI" ,
3619# endif
3620# if ENABLE_HUSH_LOOPS
3621 [RES_FOR ] = "FOR" ,
3622 [RES_WHILE] = "WHILE",
3623 [RES_UNTIL] = "UNTIL",
3624 [RES_DO ] = "DO" ,
3625 [RES_DONE ] = "DONE" ,
3626# endif
3627# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3628 [RES_IN ] = "IN" ,
3629# endif
3630# if ENABLE_HUSH_CASE
3631 [RES_CASE ] = "CASE" ,
3632 [RES_CASE_IN ] = "CASE_IN" ,
3633 [RES_MATCH] = "MATCH",
3634 [RES_CASE_BODY] = "CASE_BODY",
3635 [RES_ESAC ] = "ESAC" ,
3636# endif
3637 [RES_XXXX ] = "XXXX" ,
3638 [RES_SNTX ] = "SNTX" ,
3639 };
3640 static const char *const CMDTYPE[] = {
3641 "{}",
3642 "()",
3643 "[noglob]",
3644# if ENABLE_HUSH_FUNCTIONS
3645 "func()",
3646# endif
3647 };
3648
3649 int pin, prn;
3650
3651 pin = 0;
3652 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003653 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3654 lvl*2, "",
3655 pin,
3656 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3657 RES[pi->res_word],
3658 pi->followup, PIPE[pi->followup]
3659 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003660 prn = 0;
3661 while (prn < pi->num_cmds) {
3662 struct command *command = &pi->cmds[prn];
3663 char **argv = command->argv;
3664
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003665 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003666 lvl*2, "", prn,
3667 command->assignment_cnt);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003668# if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko5807e182018-02-08 19:19:04 +01003669 fdprintf(2, " LINENO:%u", command->lineno);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003670# endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003671 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003672 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003673 CMDTYPE[command->cmd_type],
3674 argv
3675# if !BB_MMU
3676 , " group_as_string:", command->group_as_string
3677# else
3678 , "", ""
3679# endif
3680 );
3681 debug_print_tree(command->group, lvl+1);
3682 prn++;
3683 continue;
3684 }
3685 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003686 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003687 argv++;
3688 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003689 if (command->redirects)
3690 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003691 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003692 prn++;
3693 }
3694 pi = pi->next;
3695 pin++;
3696 }
3697}
3698#endif /* debug_print_tree */
3699
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003700static struct pipe *new_pipe(void)
3701{
Eric Andersen25f27032001-04-26 23:22:31 +00003702 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003703 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003704 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003705 return pi;
3706}
3707
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003708/* Command (member of a pipe) is complete, or we start a new pipe
3709 * if ctx->command is NULL.
3710 * No errors possible here.
3711 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003712static int done_command(struct parse_context *ctx)
3713{
3714 /* The command is really already in the pipe structure, so
3715 * advance the pipe counter and make a new, null command. */
3716 struct pipe *pi = ctx->pipe;
3717 struct command *command = ctx->command;
3718
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003719#if 0 /* Instead we emit error message at run time */
3720 if (ctx->pending_redirect) {
3721 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003722 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003723 ctx->pending_redirect = NULL;
3724 }
3725#endif
3726
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003727 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003728 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003729 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003730 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003731 }
3732 pi->num_cmds++;
3733 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003734 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003735 } else {
3736 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3737 }
3738
3739 /* Only real trickiness here is that the uncommitted
3740 * command structure is not counted in pi->num_cmds. */
3741 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003742 ctx->command = command = &pi->cmds[pi->num_cmds];
3743 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003744 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003745#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003746 command->lineno = G.parse_lineno;
3747 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003748#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003749 return pi->num_cmds; /* used only for 0/nonzero check */
3750}
3751
3752static void done_pipe(struct parse_context *ctx, pipe_style type)
3753{
3754 int not_null;
3755
3756 debug_printf_parse("done_pipe entered, followup %d\n", type);
3757 /* Close previous command */
3758 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003759#if HAS_KEYWORDS
3760 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3761 ctx->ctx_inverted = 0;
3762 ctx->pipe->res_word = ctx->ctx_res_w;
3763#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003764 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3765 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003766 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3767 * in a backgrounded subshell.
3768 */
3769 struct pipe *pi;
3770 struct command *command;
3771
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003772 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003773 pi = ctx->list_head;
3774 while (pi != ctx->pipe) {
3775 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3776 goto no_conv;
3777 pi = pi->next;
3778 }
3779
3780 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3781 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3782 pi = xzalloc(sizeof(*pi));
3783 pi->followup = PIPE_BG;
3784 pi->num_cmds = 1;
3785 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3786 command = &pi->cmds[0];
3787 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3788 command->cmd_type = CMD_NORMAL;
3789 command->group = ctx->list_head;
3790#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003791 command->group_as_string = xstrndup(
3792 ctx->as_string.data,
3793 ctx->as_string.length - 1 /* do not copy last char, "&" */
3794 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003795#endif
3796 /* Replace all pipes in ctx with one newly created */
3797 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003798 } else {
3799 no_conv:
3800 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003801 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003802
3803 /* Without this check, even just <enter> on command line generates
3804 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003805 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003806 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003807#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003808 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003809#endif
3810#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003811 || ctx->ctx_res_w == RES_DONE
3812 || ctx->ctx_res_w == RES_FOR
3813 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003814#endif
3815#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003816 || ctx->ctx_res_w == RES_ESAC
3817#endif
3818 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003819 struct pipe *new_p;
3820 debug_printf_parse("done_pipe: adding new pipe: "
3821 "not_null:%d ctx->ctx_res_w:%d\n",
3822 not_null, ctx->ctx_res_w);
3823 new_p = new_pipe();
3824 ctx->pipe->next = new_p;
3825 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003826 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003827 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003828 * This is used to control execution.
3829 * RES_FOR and RES_IN are NOT sticky (needed to support
3830 * cases where variable or value happens to match a keyword):
3831 */
3832#if ENABLE_HUSH_LOOPS
3833 if (ctx->ctx_res_w == RES_FOR
3834 || ctx->ctx_res_w == RES_IN)
3835 ctx->ctx_res_w = RES_NONE;
3836#endif
3837#if ENABLE_HUSH_CASE
3838 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003839 ctx->ctx_res_w = RES_CASE_BODY;
3840 if (ctx->ctx_res_w == RES_CASE)
3841 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003842#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003843 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003844 /* Create the memory for command, roughly:
3845 * ctx->pipe->cmds = new struct command;
3846 * ctx->command = &ctx->pipe->cmds[0];
3847 */
3848 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003849 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003850 }
3851 debug_printf_parse("done_pipe return\n");
3852}
3853
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003854static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003855{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003856 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003857 if (MAYBE_ASSIGNMENT != 0)
3858 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003859 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003860 /* Create the memory for command, roughly:
3861 * ctx->pipe->cmds = new struct command;
3862 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003863 */
3864 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003865}
3866
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003867/* If a reserved word is found and processed, parse context is modified
3868 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003869 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003870#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003871struct reserved_combo {
3872 char literal[6];
3873 unsigned char res;
3874 unsigned char assignment_flag;
3875 int flag;
3876};
3877enum {
3878 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003879# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003880 FLAG_IF = (1 << RES_IF ),
3881 FLAG_THEN = (1 << RES_THEN ),
3882 FLAG_ELIF = (1 << RES_ELIF ),
3883 FLAG_ELSE = (1 << RES_ELSE ),
3884 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003885# endif
3886# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003887 FLAG_FOR = (1 << RES_FOR ),
3888 FLAG_WHILE = (1 << RES_WHILE),
3889 FLAG_UNTIL = (1 << RES_UNTIL),
3890 FLAG_DO = (1 << RES_DO ),
3891 FLAG_DONE = (1 << RES_DONE ),
3892 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003893# endif
3894# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003895 FLAG_MATCH = (1 << RES_MATCH),
3896 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003897# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003898 FLAG_START = (1 << RES_XXXX ),
3899};
3900
3901static const struct reserved_combo* match_reserved_word(o_string *word)
3902{
Eric Andersen25f27032001-04-26 23:22:31 +00003903 /* Mostly a list of accepted follow-up reserved words.
3904 * FLAG_END means we are done with the sequence, and are ready
3905 * to turn the compound list into a command.
3906 * FLAG_START means the word must start a new compound list.
3907 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003908 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003909# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003910 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3911 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3912 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3913 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3914 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3915 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003916# endif
3917# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003918 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3919 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3920 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3921 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3922 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3923 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003924# endif
3925# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003926 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3927 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003928# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003929 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003930 const struct reserved_combo *r;
3931
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003932 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003933 if (strcmp(word->data, r->literal) == 0)
3934 return r;
3935 }
3936 return NULL;
3937}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003938/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003939 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003940static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003941{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003942# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003943 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003944 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003945 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003946# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003947 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003948
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003949 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003950 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003951 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003952 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003953 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003954
3955 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003956# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003957 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3958 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003959 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003960 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003961# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003962 if (r->flag == 0) { /* '!' */
3963 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003964 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003965 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003966 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003967 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003968 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003969 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003970 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003971 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003972
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003973 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003974 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003975 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003976 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003977 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003978 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003979 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003980 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003981 } else {
3982 /* "{...} fi" is ok. "{...} if" is not
3983 * Example:
3984 * if { echo foo; } then { echo bar; } fi */
3985 if (ctx->command->group)
3986 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003987 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003988
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003989 ctx->ctx_res_w = r->res;
3990 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003991 ctx->is_assignment = r->assignment_flag;
3992 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003993
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003994 if (ctx->old_flag & FLAG_END) {
3995 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003996
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003997 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003998 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003999 old = ctx->stack;
4000 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004001 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004002# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004003 /* At this point, the compound command's string is in
4004 * ctx->as_string... except for the leading keyword!
4005 * Consider this example: "echo a | if true; then echo a; fi"
4006 * ctx->as_string will contain "true; then echo a; fi",
4007 * with "if " remaining in old->as_string!
4008 */
4009 {
4010 char *str;
4011 int len = old->as_string.length;
4012 /* Concatenate halves */
4013 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004014 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004015 /* Find where leading keyword starts in first half */
4016 str = old->as_string.data + len;
4017 if (str > old->as_string.data)
4018 str--; /* skip whitespace after keyword */
4019 while (str > old->as_string.data && isalpha(str[-1]))
4020 str--;
4021 /* Ugh, we're done with this horrid hack */
4022 old->command->group_as_string = xstrdup(str);
4023 debug_printf_parse("pop, remembering as:'%s'\n",
4024 old->command->group_as_string);
4025 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004026# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004027 *ctx = *old; /* physical copy */
4028 free(old);
4029 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004030 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004031}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004032#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004033
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004034/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004035 * Normal return is 0. Syntax errors return 1.
4036 * Note: on return, word is reset, but not o_free'd!
4037 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004038static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004039{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004040 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004041
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004042 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4043 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004044 debug_printf_parse("done_word return 0: true null, ignored\n");
4045 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004046 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004047
Eric Andersen25f27032001-04-26 23:22:31 +00004048 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004049 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4050 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004051 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004052 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004053 * If the redirection operator is "<<" or "<<-", the word
4054 * that follows the redirection operator shall be
4055 * subjected to quote removal; it is unspecified whether
4056 * any of the other expansions occur. For the other
4057 * redirection operators, the word that follows the
4058 * redirection operator shall be subjected to tilde
4059 * expansion, parameter expansion, command substitution,
4060 * arithmetic expansion, and quote removal.
4061 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004062 * on the word by a non-interactive shell; an interactive
4063 * shell may perform it, but shall do so only when
4064 * the expansion would result in one word."
4065 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004066//bash does not do parameter/command substitution or arithmetic expansion
4067//for _heredoc_ redirection word: these constructs look for exact eof marker
4068// as written:
4069// <<EOF$t
4070// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004071// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4072
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004073 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004074 /* Cater for >\file case:
4075 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4076 * Same with heredocs:
4077 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4078 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004079 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4080 unbackslash(ctx->pending_redirect->rd_filename);
4081 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004082 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004083 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4084 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004085 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004086 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004087 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004088 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004089#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004090# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004091 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004092 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004093 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004094 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004095 /* ctx->ctx_res_w = RES_MATCH; */
4096 ctx->ctx_dsemicolon = 0;
4097 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004098# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004099 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004100# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004101 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4102 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004103# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004104# if ENABLE_HUSH_CASE
4105 && ctx->ctx_res_w != RES_CASE
4106# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004107 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004108 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004109 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004110 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004111 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004112# if ENABLE_HUSH_LINENO_VAR
4113/* Case:
4114 * "while ...; do
4115 * cmd ..."
4116 * If we don't close the pipe _now_, immediately after "do", lineno logic
4117 * sees "cmd" as starting at "do" - i.e., at the previous line.
4118 */
4119 if (0
4120 IF_HUSH_IF(|| reserved->res == RES_THEN)
4121 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4122 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4123 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4124 ) {
4125 done_pipe(ctx, PIPE_SEQ);
4126 }
4127# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004128 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004129 debug_printf_parse("done_word return %d\n",
4130 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004131 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004132 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004133# if defined(CMD_SINGLEWORD_NOGLOB)
4134 if (0
4135# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004136 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004137# endif
4138 /* In bash, local/export/readonly are special, args
4139 * are assignments and therefore expansion of them
4140 * should be "one-word" expansion:
4141 * $ export i=`echo 'a b'` # one arg: "i=a b"
4142 * compare with:
4143 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4144 * ls: cannot access i=a: No such file or directory
4145 * ls: cannot access b: No such file or directory
4146 * Note: bash 3.2.33(1) does this only if export word
4147 * itself is not quoted:
4148 * $ export i=`echo 'aaa bbb'`; echo "$i"
4149 * aaa bbb
4150 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4151 * aaa
4152 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004153 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4154 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4155 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004156 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004157 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4158 }
4159 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004160# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004161 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004162#endif /* HAS_KEYWORDS */
4163
Denis Vlasenkobb929512009-04-16 10:59:40 +00004164 if (command->group) {
4165 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004166 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004167 debug_printf_parse("done_word return 1: syntax error, "
4168 "groups and arglists don't mix\n");
4169 return 1;
4170 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004171
4172 /* If this word wasn't an assignment, next ones definitely
4173 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004174 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4175 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004176 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004177 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004178 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004179 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004180 command->assignment_cnt++;
4181 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4182 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004183 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4184 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004185 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004186 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4187 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004188 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004189 }
Eric Andersen25f27032001-04-26 23:22:31 +00004190
Denis Vlasenko06810332007-05-21 23:30:54 +00004191#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004192 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004193 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004194 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004195 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004196 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004197 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004198 return 1;
4199 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004200 /* Force FOR to have just one word (variable name) */
4201 /* NB: basically, this makes hush see "for v in ..."
4202 * syntax as if it is "for v; in ...". FOR and IN become
4203 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004204 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004205 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004206#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004207#if ENABLE_HUSH_CASE
4208 /* Force CASE to have just one word */
4209 if (ctx->ctx_res_w == RES_CASE) {
4210 done_pipe(ctx, PIPE_SEQ);
4211 }
4212#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004213
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004214 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004215
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004216 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004217 return 0;
4218}
4219
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004220
4221/* Peek ahead in the input to find out if we have a "&n" construct,
4222 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004223 * Return:
4224 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4225 * REDIRFD_SYNTAX_ERR if syntax error,
4226 * REDIRFD_TO_FILE if no & was seen,
4227 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004228 */
4229#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004230#define parse_redir_right_fd(as_string, input) \
4231 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004232#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004233static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004234{
4235 int ch, d, ok;
4236
4237 ch = i_peek(input);
4238 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004239 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004240
4241 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004242 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004243 ch = i_peek(input);
4244 if (ch == '-') {
4245 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004246 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004247 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004248 }
4249 d = 0;
4250 ok = 0;
4251 while (ch != EOF && isdigit(ch)) {
4252 d = d*10 + (ch-'0');
4253 ok = 1;
4254 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004255 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004256 ch = i_peek(input);
4257 }
4258 if (ok) return d;
4259
4260//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4261
James Byrne69374872019-07-02 11:35:03 +02004262 bb_simple_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004263 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004264}
4265
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004266/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004267 */
4268static int parse_redirect(struct parse_context *ctx,
4269 int fd,
4270 redir_type style,
4271 struct in_str *input)
4272{
4273 struct command *command = ctx->command;
4274 struct redir_struct *redir;
4275 struct redir_struct **redirp;
4276 int dup_num;
4277
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004278 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004279 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004280 /* Check for a '>&1' type redirect */
4281 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4282 if (dup_num == REDIRFD_SYNTAX_ERR)
4283 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004284 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004285 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004286 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004287 if (dup_num) { /* <<-... */
4288 ch = i_getch(input);
4289 nommu_addchr(&ctx->as_string, ch);
4290 ch = i_peek(input);
4291 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004292 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004293
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004294 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004295 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004296 if (ch == '|') {
4297 /* >|FILE redirect ("clobbering" >).
4298 * Since we do not support "set -o noclobber" yet,
4299 * >| and > are the same for now. Just eat |.
4300 */
4301 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004302 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303 }
4304 }
4305
4306 /* Create a new redir_struct and append it to the linked list */
4307 redirp = &command->redirects;
4308 while ((redir = *redirp) != NULL) {
4309 redirp = &(redir->next);
4310 }
4311 *redirp = redir = xzalloc(sizeof(*redir));
4312 /* redir->next = NULL; */
4313 /* redir->rd_filename = NULL; */
4314 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004315 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004316
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004317 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4318 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004319
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004320 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004321 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004322 /* Erik had a check here that the file descriptor in question
4323 * is legit; I postpone that to "run time"
4324 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004325 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4326 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004328#if 0 /* Instead we emit error message at run time */
4329 if (ctx->pending_redirect) {
4330 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004331 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004332 }
4333#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004334 /* Set ctx->pending_redirect, so we know what to do at the
4335 * end of the next parsed word. */
4336 ctx->pending_redirect = redir;
4337 }
4338 return 0;
4339}
4340
Eric Andersen25f27032001-04-26 23:22:31 +00004341/* If a redirect is immediately preceded by a number, that number is
4342 * supposed to tell which file descriptor to redirect. This routine
4343 * looks for such preceding numbers. In an ideal world this routine
4344 * needs to handle all the following classes of redirects...
4345 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4346 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4347 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4348 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004349 *
4350 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4351 * "2.7 Redirection
4352 * ... If n is quoted, the number shall not be recognized as part of
4353 * the redirection expression. For example:
4354 * echo \2>a
4355 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004356 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004357 *
4358 * A -1 return means no valid number was found,
4359 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004360 */
4361static int redirect_opt_num(o_string *o)
4362{
4363 int num;
4364
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004365 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004366 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004367 num = bb_strtou(o->data, NULL, 10);
4368 if (errno || num < 0)
4369 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004370 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004371 return num;
4372}
4373
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004374#if BB_MMU
4375#define fetch_till_str(as_string, input, word, skip_tabs) \
4376 fetch_till_str(input, word, skip_tabs)
4377#endif
4378static char *fetch_till_str(o_string *as_string,
4379 struct in_str *input,
4380 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004381 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004382{
4383 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004384 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004385 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004386 int ch;
4387
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004388 /* Starting with "" is necessary for this case:
4389 * cat <<EOF
4390 *
4391 * xxx
4392 * EOF
4393 */
4394 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4395
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004396 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004397
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004398 while (1) {
4399 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004400 if (ch != EOF)
4401 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004402 if (ch == '\n' || ch == EOF) {
4403 check_heredoc_end:
4404 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004405 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004406 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4407 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004408 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004409 return heredoc.data;
4410 }
4411 if (ch == '\n') {
4412 /* This is a new line.
4413 * Remember position and backslash-escaping status.
4414 */
4415 o_addchr(&heredoc, ch);
4416 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004417 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004418 past_EOL = heredoc.length;
4419 /* Get 1st char of next line, possibly skipping leading tabs */
4420 do {
4421 ch = i_getch(input);
4422 if (ch != EOF)
4423 nommu_addchr(as_string, ch);
4424 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4425 /* If this immediately ended the line,
4426 * go back to end-of-line checks.
4427 */
4428 if (ch == '\n')
4429 goto check_heredoc_end;
4430 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004431 } else {
4432 /* Backslash-line continuation in an unquoted
4433 * heredoc. This does not need special handling
4434 * for heredoc body (unquoted heredocs are
4435 * expanded on "execution" and that would take
4436 * care of this case too), but not the case
4437 * of line continuation *in terminator*:
4438 * cat <<EOF
4439 * Ok1
4440 * EO\
4441 * F
4442 */
4443 heredoc.data[--heredoc.length] = '\0';
4444 prev = 0; /* not '\' */
4445 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004446 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004447 }
4448 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004449 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004450 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004451 }
4452 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004453 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004454 if (prev == '\\' && ch == '\\')
4455 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004456 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004457 else
4458 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004459 }
4460}
4461
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004462/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4463 * and load them all. There should be exactly heredoc_cnt of them.
4464 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004465#if BB_MMU
4466#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4467 fetch_heredocs(pi, heredoc_cnt, input)
4468#endif
4469static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004470{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004471 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004472 int i;
4473 struct command *cmd = pi->cmds;
4474
Denys Vlasenko3675c372018-07-23 16:31:21 +02004475 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004476 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004477 cmd->argv ? cmd->argv[0] : "NONE"
4478 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004479 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004480 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004481
Denys Vlasenko3675c372018-07-23 16:31:21 +02004482 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004483 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004484 while (redir) {
4485 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004486 char *p;
4487
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004488 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004489 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004490 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004491 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004492 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004493 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004494 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004495 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004496 free(redir->rd_filename);
4497 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004498 heredoc_cnt--;
4499 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004500 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004501 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004502 if (cmd->group) {
4503 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4504 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4505 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4506 if (heredoc_cnt < 0)
4507 return heredoc_cnt; /* error */
4508 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004509 cmd++;
4510 }
4511 pi = pi->next;
4512 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004513 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004514}
4515
4516
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004517static int run_list(struct pipe *pi);
4518#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004519#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4520 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004521#endif
4522static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004523 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004524 struct in_str *input,
4525 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004526
Denys Vlasenko474cb202018-07-24 13:03:03 +02004527/* Returns number of heredocs not yet consumed,
4528 * or -1 on error.
4529 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004530static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004531 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004532{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004533 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004534 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004535 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004536#if BB_MMU
4537# define as_string NULL
4538#else
4539 char *as_string = NULL;
4540#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004541 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004542 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004543 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004544 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004545
4546 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004547#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004548 if (ch == '(' && !ctx->word.has_quoted_part) {
4549 if (ctx->word.length)
4550 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004551 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004552 if (!command->argv)
4553 goto skip; /* (... */
4554 if (command->argv[1]) { /* word word ... (... */
4555 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004556 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004557 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004558 /* it is "word(..." or "word (..." */
4559 do
4560 ch = i_getch(input);
4561 while (ch == ' ' || ch == '\t');
4562 if (ch != ')') {
4563 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004564 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004565 }
4566 nommu_addchr(&ctx->as_string, ch);
4567 do
4568 ch = i_getch(input);
4569 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004570 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004571 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004572 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004573 }
4574 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004575 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004576 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004577 }
4578#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004579
4580#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004581 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004582 || ctx->word.length /* word{... */
4583 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004584 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004585 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004586 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004587 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004588 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004589 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004590#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004591
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004592 IF_HUSH_FUNCTIONS(skip:)
4593
Denis Vlasenko240c2552009-04-03 03:45:05 +00004594 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004595 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004596 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004597 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4598 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004599 } else {
4600 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004601 ch = i_peek(input);
4602 if (ch != ' ' && ch != '\t' && ch != '\n'
4603 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4604 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004605 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004606 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004607 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004608 if (ch != '(') {
4609 ch = i_getch(input);
4610 nommu_addchr(&ctx->as_string, ch);
4611 }
Eric Andersen25f27032001-04-26 23:22:31 +00004612 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004613
Denys Vlasenko474cb202018-07-24 13:03:03 +02004614 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4615 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4616 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004617#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004618 if (as_string)
4619 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004620#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004621
4622 /* empty ()/{} or parse error? */
4623 if (!pipe_list || pipe_list == ERR_PTR) {
4624 /* parse_stream already emitted error msg */
4625 if (!BB_MMU)
4626 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004627 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004628 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004629 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004630 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004631#if !BB_MMU
4632 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4633 command->group_as_string = as_string;
4634 debug_printf_parse("end of group, remembering as:'%s'\n",
4635 command->group_as_string);
4636#endif
4637
4638#if ENABLE_HUSH_FUNCTIONS
4639 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4640 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4641 struct command *cmd2;
4642
4643 cmd2 = xzalloc(sizeof(*cmd2));
4644 cmd2->cmd_type = CMD_SUBSHELL;
4645 cmd2->group = pipe_list;
4646# if !BB_MMU
4647//UNTESTED!
4648 cmd2->group_as_string = command->group_as_string;
4649 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4650# endif
4651
4652 pipe_list = new_pipe();
4653 pipe_list->cmds = cmd2;
4654 pipe_list->num_cmds = 1;
4655 }
4656#endif
4657
4658 command->group = pipe_list;
4659
Denys Vlasenko474cb202018-07-24 13:03:03 +02004660 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4661 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004662 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004663#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004664}
4665
Denys Vlasenko0b883582016-12-23 16:49:07 +01004666#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004667/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004668/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004669static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004670{
4671 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004672 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004673 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004674 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004675 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004676 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004677 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004678 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004679 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004680 }
4681}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004682static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4683{
4684 while (1) {
4685 int ch = i_getch(input);
4686 if (ch == EOF) {
4687 syntax_error_unterm_ch('\'');
4688 return 0;
4689 }
4690 if (ch == '\'')
4691 return 1;
4692 o_addqchr(dest, ch);
4693 }
4694}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004695/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004696static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004697static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004698{
4699 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004700 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004701 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004702 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004703 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004704 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004705 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004706 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004707 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004708 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004709 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004710 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004711 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004712 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004713 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4714 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004715 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004716 continue;
4717 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004718 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004719 }
4720}
4721/* Process `cmd` - copy contents until "`" is seen. Complicated by
4722 * \` quoting.
4723 * "Within the backquoted style of command substitution, backslash
4724 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4725 * The search for the matching backquote shall be satisfied by the first
4726 * backquote found without a preceding backslash; during this search,
4727 * if a non-escaped backquote is encountered within a shell comment,
4728 * a here-document, an embedded command substitution of the $(command)
4729 * form, or a quoted string, undefined results occur. A single-quoted
4730 * or double-quoted string that begins, but does not end, within the
4731 * "`...`" sequence produces undefined results."
4732 * Example Output
4733 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4734 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004735static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004736{
4737 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004738 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004739 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004740 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004741 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004742 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4743 ch = i_getch(input);
4744 if (ch != '`'
4745 && ch != '$'
4746 && ch != '\\'
4747 && (!in_dquote || ch != '"')
4748 ) {
4749 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004750 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004751 }
4752 if (ch == EOF) {
4753 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004754 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004755 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004756 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004757 }
4758}
4759/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4760 * quoting and nested ()s.
4761 * "With the $(command) style of command substitution, all characters
4762 * following the open parenthesis to the matching closing parenthesis
4763 * constitute the command. Any valid shell script can be used for command,
4764 * except a script consisting solely of redirections which produces
4765 * unspecified results."
4766 * Example Output
4767 * echo $(echo '(TEST)' BEST) (TEST) BEST
4768 * echo $(echo 'TEST)' BEST) TEST) BEST
4769 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004770 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004771 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004772 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004773 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4774 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004775 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004776#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004777static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004778{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004779 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004780 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004781# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004782 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004783# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004784 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4785
Denys Vlasenko259747c2019-11-28 10:28:14 +01004786# if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004787 G.promptmode = 1; /* PS2 */
Denys Vlasenko259747c2019-11-28 10:28:14 +01004788# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004789 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4790
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004791 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004792 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004793 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004794 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004795 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004796 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004797 if (ch == end_ch
4798# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004799 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004800# endif
4801 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004802 if (!dbl)
4803 break;
4804 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004805 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004806 i_getch(input); /* eat second ')' */
4807 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004808 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004809 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004810 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004811 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004812 if (ch == '(' || ch == '{') {
4813 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004814 if (!add_till_closing_bracket(dest, input, ch))
4815 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004816 o_addchr(dest, ch);
4817 continue;
4818 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004819 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004820 if (!add_till_single_quote(dest, input))
4821 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004822 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004823 continue;
4824 }
4825 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004826 if (!add_till_double_quote(dest, input))
4827 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004828 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004829 continue;
4830 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004831 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004832 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4833 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004834 o_addchr(dest, ch);
4835 continue;
4836 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004837 if (ch == '\\') {
4838 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004839 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004840 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004841 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004842 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004843 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004844# if 0
Denys Vlasenko657086a2016-09-29 18:07:42 +02004845 if (ch == '\n') {
4846 /* "backslash+newline", ignore both */
4847 o_delchr(dest); /* undo insertion of '\' */
4848 continue;
4849 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004850# endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004851 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004852 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004853 continue;
4854 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004855 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004856 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004857 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004858}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004859#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004860
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004861/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004862#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004863#define parse_dollar(as_string, dest, input, quote_mask) \
4864 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004865#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004866#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004867static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004868 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004869 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004870{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004871 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004872
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004873 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004874 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004875 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004876 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004877 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004878 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004880 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004881 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004882 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004883 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004884 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004885 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004886 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004887 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004888 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004889 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004890 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004891 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004892 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004893 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004894 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004895 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004896 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004897 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004898 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004899 o_addchr(dest, ch | quote_mask);
4900 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004901 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004902 case '$': /* pid */
4903 case '!': /* last bg pid */
4904 case '?': /* last exit code */
4905 case '#': /* number of args */
4906 case '*': /* args */
4907 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02004908 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004909 goto make_one_char_var;
4910 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004911 char len_single_ch;
4912
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004913 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4914
Denys Vlasenko74369502010-05-21 19:52:01 +02004915 ch = i_getch(input); /* eat '{' */
4916 nommu_addchr(as_string, ch);
4917
Denys Vlasenko46e64982016-09-29 19:50:55 +02004918 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004919 /* It should be ${?}, or ${#var},
4920 * or even ${?+subst} - operator acting on a special variable,
4921 * or the beginning of variable name.
4922 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004923 if (ch == EOF
4924 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4925 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004926 bad_dollar_syntax:
4927 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004928 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4929 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004930 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004931 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004932 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004933 ch |= quote_mask;
4934
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004935 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004936 * However, this regresses some of our testsuite cases
4937 * which check invalid constructs like ${%}.
4938 * Oh well... let's check that the var name part is fine... */
4939
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004940 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004941 unsigned pos;
4942
Denys Vlasenko74369502010-05-21 19:52:01 +02004943 o_addchr(dest, ch);
4944 debug_printf_parse(": '%c'\n", ch);
4945
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004946 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004947 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004948 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004949 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004950
Denys Vlasenko74369502010-05-21 19:52:01 +02004951 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004952 unsigned end_ch;
4953 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004954 /* handle parameter expansions
4955 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4956 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004957 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4958 if (len_single_ch != '#'
4959 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4960 || i_peek(input) != '}'
4961 ) {
4962 goto bad_dollar_syntax;
4963 }
4964 /* else: it's "length of C" ${#C} op,
4965 * where C is a single char
4966 * special var name, e.g. ${#!}.
4967 */
4968 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004969 /* Eat everything until closing '}' (or ':') */
4970 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004971 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004972 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004973 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004974 ) {
4975 /* It's ${var:N[:M]} thing */
4976 end_ch = '}' * 0x100 + ':';
4977 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004978 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004979 && ch == '/'
4980 ) {
4981 /* It's ${var/[/]pattern[/repl]} thing */
4982 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4983 i_getch(input);
4984 nommu_addchr(as_string, '/');
4985 ch = '\\';
4986 }
4987 end_ch = '}' * 0x100 + '/';
4988 }
4989 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02004990 /* The pattern can't be empty.
4991 * IOW: if the first char after "${v//" is a slash,
4992 * it does not terminate the pattern - it's the first char of the pattern:
4993 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4994 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4995 */
4996 if (i_peek(input) == '/') {
4997 o_addchr(dest, i_getch(input));
4998 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004999 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005000 if (!BB_MMU)
5001 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005002#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005003 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005004 if (last_ch == 0) /* error? */
5005 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005006#else
Denys Vlasenko259747c2019-11-28 10:28:14 +01005007# error Simple code to only allow ${var} is not implemented
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005008#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005009 if (as_string) {
5010 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005011 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005012 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005013
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005014 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5015 && (end_ch & 0xff00)
5016 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005017 /* close the first block: */
5018 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005019 /* while parsing N from ${var:N[:M]}
5020 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005021 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005022 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005023 end_ch = '}';
5024 goto again;
5025 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005026 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005027 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005028 /* it's ${var:N} - emulate :999999999 */
5029 o_addstr(dest, "999999999");
5030 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005031 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005032 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005033 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005034 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005035 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005036 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5037 break;
5038 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005039#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005040 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005041 unsigned pos;
5042
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005043 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005044 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005045# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005046 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005047 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005048 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005049 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5050 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005051 if (!BB_MMU)
5052 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005053 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5054 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005055 if (as_string) {
5056 o_addstr(as_string, dest->data + pos);
5057 o_addchr(as_string, ')');
5058 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005059 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005060 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005061 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005062 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005063# endif
5064# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005065 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5066 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005067 if (!BB_MMU)
5068 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005069 if (!add_till_closing_bracket(dest, input, ')'))
5070 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005071 if (as_string) {
5072 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005073 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005074 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005075 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005076# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005077 break;
5078 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005079#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005080 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005081 goto make_var;
5082#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005083 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005084 /* $_ Shell or shell script name; or last argument of last command
5085 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5086 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005087 ch = i_getch(input);
5088 nommu_addchr(as_string, ch);
5089 ch = i_peek_and_eat_bkslash_nl(input);
5090 if (isalnum(ch)) { /* it's $_name or $_123 */
5091 ch = '_';
5092 goto make_var1;
5093 }
5094 /* else: it's $_ */
5095#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005096 default:
5097 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005098 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005099 debug_printf_parse("parse_dollar return 1 (ok)\n");
5100 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005101#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005102}
5103
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005104#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005105#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005106 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005107#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005108#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005109static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005110 o_string *dest,
5111 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005112 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005113{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005114 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005115 int next;
5116
5117 again:
5118 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005119 if (ch != EOF)
5120 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005121 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005122 debug_printf_parse("encode_string return 1 (ok)\n");
5123 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005124 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005125 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005126 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005127 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005128 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005129 }
5130 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005131 if (ch != '\n') {
5132 next = i_peek(input);
5133 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005134 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005135 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005136 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005137 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005138 /* Testcase: in interactive shell a file with
5139 * echo "unterminated string\<eof>
5140 * is sourced.
5141 */
5142 syntax_error_unterm_ch('"');
5143 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005144 }
5145 /* bash:
5146 * "The backslash retains its special meaning [in "..."]
5147 * only when followed by one of the following characters:
5148 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005149 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005150 * NB: in (unquoted) heredoc, above does not apply to ",
5151 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005152 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005153 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005154 ch = i_getch(input); /* eat next */
5155 if (ch == '\n')
5156 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005157 } /* else: ch remains == '\\', and we double it below: */
5158 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005159 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005160 goto again;
5161 }
5162 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005163 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5164 debug_printf_parse("encode_string return 0: "
5165 "parse_dollar returned 0 (error)\n");
5166 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005167 }
5168 goto again;
5169 }
5170#if ENABLE_HUSH_TICK
5171 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005172 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005173 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5174 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005175 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5176 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005177 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5178 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005179 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005180 }
5181#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005182 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005183 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005184#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005185}
5186
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005187/*
5188 * Scan input until EOF or end_trigger char.
5189 * Return a list of pipes to execute, or NULL on EOF
5190 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005191 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005192 * reset parsing machinery and start parsing anew,
5193 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005194 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005195static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005196 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005197 struct in_str *input,
5198 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005199{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005200 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005201 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005202
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005203 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005204 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005205 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005206 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005207 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005208 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005209
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005210 initialize_context(&ctx);
5211
5212 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5213 * Preventing this:
5214 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005215 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005216
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005217 /* We used to separate words on $IFS here. This was wrong.
5218 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005219 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005220 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005221
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005222 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005223 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005224 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005225 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005226 int ch;
5227 int next;
5228 int redir_fd;
5229 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005230
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005231 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005232 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005233 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005234 if (ch == EOF) {
5235 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005236
5237 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005238 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005239 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005240 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005241 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005242 syntax_error_unterm_ch('(');
5243 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005244 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005245 if (end_trigger == '}') {
5246 syntax_error_unterm_ch('{');
5247 goto parse_error;
5248 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005249
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005250 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005251 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005252 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005253 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005254 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005255 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005256 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005257 /* (this makes bare "&" cmd a no-op.
5258 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005259 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005260 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005261 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005262 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005263 pi = NULL;
5264 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005265#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005266 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005267 if (pstring)
5268 *pstring = ctx.as_string.data;
5269 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005270 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005271#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005272 // heredoc_cnt must be 0 here anyway
5273 //if (heredoc_cnt_ptr)
5274 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005275 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005276 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005277 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005278 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005279 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005280
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005281 /* Handle "'" and "\" first, as they won't play nice with
5282 * i_peek_and_eat_bkslash_nl() anyway:
5283 * echo z\\
5284 * and
5285 * echo '\
5286 * '
5287 * would break.
5288 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005289 if (ch == '\\') {
5290 ch = i_getch(input);
5291 if (ch == '\n')
5292 continue; /* drop \<newline>, get next char */
5293 nommu_addchr(&ctx.as_string, '\\');
5294 o_addchr(&ctx.word, '\\');
5295 if (ch == EOF) {
5296 /* Testcase: eval 'echo Ok\' */
5297 /* bash-4.3.43 was removing backslash,
5298 * but 4.4.19 retains it, most other shells too
5299 */
5300 continue; /* get next char */
5301 }
5302 /* Example: echo Hello \2>file
5303 * we need to know that word 2 is quoted
5304 */
5305 ctx.word.has_quoted_part = 1;
5306 nommu_addchr(&ctx.as_string, ch);
5307 o_addchr(&ctx.word, ch);
5308 continue; /* get next char */
5309 }
5310 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005311 if (ch == '\'') {
5312 ctx.word.has_quoted_part = 1;
5313 next = i_getch(input);
5314 if (next == '\'' && !ctx.pending_redirect)
5315 goto insert_empty_quoted_str_marker;
5316
5317 ch = next;
5318 while (1) {
5319 if (ch == EOF) {
5320 syntax_error_unterm_ch('\'');
5321 goto parse_error;
5322 }
5323 nommu_addchr(&ctx.as_string, ch);
5324 if (ch == '\'')
5325 break;
5326 if (ch == SPECIAL_VAR_SYMBOL) {
5327 /* Convert raw ^C to corresponding special variable reference */
5328 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5329 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5330 }
5331 o_addqchr(&ctx.word, ch);
5332 ch = i_getch(input);
5333 }
5334 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005335 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005336
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005337 next = '\0';
5338 if (ch != '\n')
5339 next = i_peek_and_eat_bkslash_nl(input);
5340
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005341 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005342 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005343 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005344 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005345 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005346 || ctx.word.length /* word{... - non-special */
5347 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005348 || (next != ';' /* }; - special */
5349 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005350 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005351 && next != '&' /* }& and }&& ... - special */
5352 && next != '|' /* }|| ... - special */
5353 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005354 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005355 ) {
5356 /* They are not special, skip "{}" */
5357 is_special += 2;
5358 }
5359 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005360 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005361
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005362 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005363 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005364 o_addQchr(&ctx.word, ch);
5365 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5366 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005367 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005368 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005369 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005370 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5371 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005372 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005373 continue;
5374 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005375
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005376 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005377#if ENABLE_HUSH_LINENO_VAR
5378/* Case:
5379 * "while ...; do<whitespace><newline>
5380 * cmd ..."
5381 * would think that "cmd" starts in <whitespace> -
5382 * i.e., at the previous line.
5383 * We need to skip all whitespace before newlines.
5384 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005385 while (ch != '\n') {
5386 next = i_peek(input);
5387 if (next != ' ' && next != '\t' && next != '\n')
5388 break; /* next char is not ws */
5389 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005390 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005391 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005392#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005393 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005394 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005395 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005396 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005397 /* Is this a case when newline is simply ignored?
5398 * Some examples:
5399 * "cmd | <newline> cmd ..."
5400 * "case ... in <newline> word) ..."
5401 */
5402 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005403 && ctx.word.length == 0
5404 && !ctx.word.has_quoted_part
5405 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005406 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005407 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005408 * Without check #1, interactive shell
5409 * ignores even bare <newline>,
5410 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005411 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005412 * ps2> _ <=== wrong, should be ps1
5413 * Without check #2, "cmd & <newline>"
5414 * is similarly mistreated.
5415 * (BTW, this makes "cmd & cmd"
5416 * and "cmd && cmd" non-orthogonal.
5417 * Really, ask yourself, why
5418 * "cmd && <newline>" doesn't start
5419 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005420 * The only reason is that it might be
5421 * a "cmd1 && <nl> cmd2 &" construct,
5422 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005423 */
5424 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005425 if (pi->num_cmds != 0 /* check #1 */
5426 && pi->followup != PIPE_BG /* check #2 */
5427 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005428 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005429 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005430 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005431 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005432 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005433 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005434 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005435 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5436 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005437 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005438 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005439 ctx.is_assignment = MAYBE_ASSIGNMENT;
5440 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005441 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005442 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005443 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005444 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005445 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005446
5447 /* "cmd}" or "cmd }..." without semicolon or &:
5448 * } is an ordinary char in this case, even inside { cmd; }
5449 * Pathological example: { ""}; } should exec "}" cmd
5450 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005451 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005452 if (ctx.word.length != 0 /* word} */
5453 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005454 ) {
5455 goto ordinary_char;
5456 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005457 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5458 /* Generally, there should be semicolon: "cmd; }"
5459 * However, bash allows to omit it if "cmd" is
5460 * a group. Examples:
5461 * { { echo 1; } }
5462 * {(echo 1)}
5463 * { echo 0 >&2 | { echo 1; } }
5464 * { while false; do :; done }
5465 * { case a in b) ;; esac }
5466 */
5467 if (ctx.command->group)
5468 goto term_group;
5469 goto ordinary_char;
5470 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005471 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005472 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005473 goto skip_end_trigger;
5474 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005475 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005476 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005477 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005478 && (ch != ';' || heredoc_cnt == 0)
5479#if ENABLE_HUSH_CASE
5480 && (ch != ')'
5481 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005482 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005483 )
5484#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005485 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005486 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005487 goto parse_error;
5488 }
5489 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005490 ctx.is_assignment = MAYBE_ASSIGNMENT;
5491 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005492 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005493 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005494 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005495 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005496 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005497#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005498 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005499 if (pstring)
5500 *pstring = ctx.as_string.data;
5501 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005502 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005503#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005504 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5505 /* Example: bare "{ }", "()" */
5506 G.last_exitcode = 2; /* bash compat */
5507 syntax_error_unexpected_ch(ch);
5508 goto parse_error2;
5509 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005510 if (heredoc_cnt_ptr)
5511 *heredoc_cnt_ptr = heredoc_cnt;
5512 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005513 debug_printf_parse("parse_stream return %p: "
5514 "end_trigger char found\n",
5515 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005516 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005517 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005518 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005519 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005520
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005521 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005522 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005523
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005524 /* Catch <, > before deciding whether this word is
5525 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5526 switch (ch) {
5527 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005528 redir_fd = redirect_opt_num(&ctx.word);
5529 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005530 goto parse_error;
5531 }
5532 redir_style = REDIRECT_OVERWRITE;
5533 if (next == '>') {
5534 redir_style = REDIRECT_APPEND;
5535 ch = i_getch(input);
5536 nommu_addchr(&ctx.as_string, ch);
5537 }
5538#if 0
5539 else if (next == '(') {
5540 syntax_error(">(process) not supported");
5541 goto parse_error;
5542 }
5543#endif
5544 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5545 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005546 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005547 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005548 redir_fd = redirect_opt_num(&ctx.word);
5549 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005550 goto parse_error;
5551 }
5552 redir_style = REDIRECT_INPUT;
5553 if (next == '<') {
5554 redir_style = REDIRECT_HEREDOC;
5555 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005556 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005557 ch = i_getch(input);
5558 nommu_addchr(&ctx.as_string, ch);
5559 } else if (next == '>') {
5560 redir_style = REDIRECT_IO;
5561 ch = i_getch(input);
5562 nommu_addchr(&ctx.as_string, ch);
5563 }
5564#if 0
5565 else if (next == '(') {
5566 syntax_error("<(process) not supported");
5567 goto parse_error;
5568 }
5569#endif
5570 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5571 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005572 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005573 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005574 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005575 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005576 /* note: we do not add it to &ctx.as_string */
5577/* TODO: in bash:
5578 * comment inside $() goes to the next \n, even inside quoted string (!):
5579 * cmd "$(cmd2 #comment)" - syntax error
5580 * cmd "`cmd2 #comment`" - ok
5581 * We accept both (comment ends where command subst ends, in both cases).
5582 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005583 while (1) {
5584 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005585 if (ch == '\n') {
5586 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005587 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005588 }
5589 ch = i_getch(input);
5590 if (ch == EOF)
5591 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005592 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005593 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005594 }
5595 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005596 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005597 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005598
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005599 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005600 /* check that we are not in word in "a=1 2>word b=1": */
5601 && !ctx.pending_redirect
5602 ) {
5603 /* ch is a special char and thus this word
5604 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005605 ctx.is_assignment = NOT_ASSIGNMENT;
5606 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005607 }
5608
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005609 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5610
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005611 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005612 case SPECIAL_VAR_SYMBOL:
5613 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005614 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5615 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005616 /* fall through */
5617 case '#':
5618 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005619 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005620 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005621 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005622 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005623 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005624 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005625 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005626 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005627 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005628 case '"':
5629 ctx.word.has_quoted_part = 1;
5630 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005631 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005632 insert_empty_quoted_str_marker:
5633 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005634 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5635 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005636 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005637 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005638 if (ctx.is_assignment == NOT_ASSIGNMENT)
5639 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005640 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005641 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005642 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005643 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005644#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005645 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005646 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005647
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005648 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5649 o_addchr(&ctx.word, '`');
5650 USE_FOR_NOMMU(pos = ctx.word.length;)
5651 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005652 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005653# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005654 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005655 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005656# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005657 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5658 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005659 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005660 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005661#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005662 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005663#if ENABLE_HUSH_CASE
5664 case_semi:
5665#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005666 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005667 goto parse_error;
5668 }
5669 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005670#if ENABLE_HUSH_CASE
5671 /* Eat multiple semicolons, detect
5672 * whether it means something special */
5673 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005674 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005675 if (ch != ';')
5676 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005677 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005678 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005679 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005680 ctx.ctx_dsemicolon = 1;
5681 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005682 break;
5683 }
5684 }
5685#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005686 new_cmd:
5687 /* We just finished a cmd. New one may start
5688 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005689 ctx.is_assignment = MAYBE_ASSIGNMENT;
5690 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005691 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005692 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005693 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005694 goto parse_error;
5695 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005696 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005697 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005698 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005699 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005700 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005701 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005702 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005703 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005704 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005705 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005706 goto parse_error;
5707 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005708#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005709 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005710 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005711#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005712 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005713 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005714 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005715 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005716 } else {
5717 /* we could pick up a file descriptor choice here
5718 * with redirect_opt_num(), but bash doesn't do it.
5719 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005720 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005721 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005722 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005723 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005724#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005725 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005726 if (ctx.ctx_res_w == RES_MATCH
5727 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005728 && ctx.word.length == 0 /* not word(... */
5729 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005730 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005731 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005732 }
5733#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005734 /* fall through */
5735 case '{': {
5736 int n = parse_group(&ctx, input, ch);
5737 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005738 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005739 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005740 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5741 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005742 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005743 }
Eric Andersen25f27032001-04-26 23:22:31 +00005744 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005745#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005746 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005747 goto case_semi;
5748#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005749
Eric Andersen25f27032001-04-26 23:22:31 +00005750 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005751 /* proper use of this character is caught by end_trigger:
5752 * if we see {, we call parse_group(..., end_trigger='}')
5753 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005754 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005755 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005756 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005757 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005758 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005759 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005760 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005761 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005762
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005763 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005764 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005765 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005766 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005767 struct parse_context *pctx;
5768 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005769
5770 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005771 * Sample for finding leaks on syntax error recovery path.
5772 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005773 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005774 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005775 * while if (true | { true;}); then echo ok; fi; do break; done
5776 * 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 +00005777 */
5778 pctx = &ctx;
5779 do {
5780 /* Update pipe/command counts,
5781 * otherwise freeing may miss some */
5782 done_pipe(pctx, PIPE_SEQ);
5783 debug_printf_clean("freeing list %p from ctx %p\n",
5784 pctx->list_head, pctx);
5785 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005786 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005787 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005788#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005789 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005790#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005791 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005792 if (pctx != &ctx) {
5793 free(pctx);
5794 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005795 IF_HAS_KEYWORDS(pctx = p2;)
5796 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005797
Denys Vlasenko474cb202018-07-24 13:03:03 +02005798 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005799#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005800 if (pstring)
5801 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005802#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005803 debug_leave();
5804 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005805 }
Eric Andersen25f27032001-04-26 23:22:31 +00005806}
5807
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808
5809/*** Execution routines ***/
5810
5811/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005812#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005813#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005814 expand_string_to_string(str)
5815#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005816static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005817#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005818static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005819#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005820static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005821
5822/* expand_strvec_to_strvec() takes a list of strings, expands
5823 * all variable references within and returns a pointer to
5824 * a list of expanded strings, possibly with larger number
5825 * of strings. (Think VAR="a b"; echo $VAR).
5826 * This new list is allocated as a single malloc block.
5827 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005828 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005829 * Caller can deallocate entire list by single free(list). */
5830
Denys Vlasenko238081f2010-10-03 14:26:26 +02005831/* A horde of its helpers come first: */
5832
5833static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5834{
5835 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005836 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005837
Denys Vlasenko9e800222010-10-03 14:28:04 +02005838#if ENABLE_HUSH_BRACE_EXPANSION
5839 if (c == '{' || c == '}') {
5840 /* { -> \{, } -> \} */
5841 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005842 /* And now we want to add { or } and continue:
5843 * o_addchr(o, c);
5844 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005845 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005846 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005847 }
5848#endif
5849 o_addchr(o, c);
5850 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005851 /* \z -> \\\z; \<eol> -> \\<eol> */
5852 o_addchr(o, '\\');
5853 if (len) {
5854 len--;
5855 o_addchr(o, '\\');
5856 o_addchr(o, *str++);
5857 }
5858 }
5859 }
5860}
5861
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005862/* Store given string, finalizing the word and starting new one whenever
5863 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005864 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005865 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005866 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5867 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005868static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005869{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005870 int last_is_ifs = 0;
5871
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005872 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005873 int word_len;
5874
5875 if (!*str) /* EOL - do not finalize word */
5876 break;
5877 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005879 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005880 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005881 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005882 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005883 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005884 * Example: "v='\*'; echo b$v" prints "b\*"
5885 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005886 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005887 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005888 /*/ Why can't we do it easier? */
5889 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5890 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5891 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005892 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005893 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005894 if (!*str) /* EOL - do not finalize word */
5895 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005896 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005897
5898 /* We know str here points to at least one IFS char */
5899 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005900 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005901 if (!*str) /* EOL - do not finalize word */
5902 break;
5903
Denys Vlasenko96786362018-04-11 16:02:58 +02005904 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5905 && strchr(G.ifs, *str) /* the second check would fail */
5906 ) {
5907 /* This is a non-whitespace $IFS char */
5908 /* Skip it and IFS whitespace chars, start new word */
5909 str++;
5910 str += strspn(str, G.ifs_whitespace);
5911 goto new_word;
5912 }
5913
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005914 /* Start new word... but not always! */
5915 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005916 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005917 /*
5918 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005919 * here nothing precedes the space in $v expansion,
5920 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005921 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005922 * It's okay if this accesses the byte before first argv[]:
5923 * past call to o_save_ptr() cleared it to zero byte
5924 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005925 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005926 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005927 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005928 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005929 o_addchr(output, '\0');
5930 debug_print_list("expand_on_ifs", output, n);
5931 n = o_save_ptr(output, n);
5932 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005933 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005934
Denys Vlasenko168579a2018-07-19 13:45:54 +02005935 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005936 debug_print_list("expand_on_ifs[1]", output, n);
5937 return n;
5938}
5939
5940/* Helper to expand $((...)) and heredoc body. These act as if
5941 * they are in double quotes, with the exception that they are not :).
5942 * Just the rules are similar: "expand only $var and `cmd`"
5943 *
5944 * Returns malloced string.
5945 * As an optimization, we return NULL if expansion is not needed.
5946 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005947static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005948{
5949 char *exp_str;
5950 struct in_str input;
5951 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005952 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005953
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005954 cp = str;
5955 for (;;) {
5956 if (!*cp) return NULL; /* string has no special chars */
5957 if (*cp == '$') break;
5958 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005959#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005960 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005961#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005962 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005963 }
5964
5965 /* We need to expand. Example:
5966 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5967 */
5968 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005969 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005970//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005971 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005972 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005973 EXP_FLAG_ESC_GLOB_CHARS,
5974 /*unbackslash:*/ 1
5975 );
5976 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005977 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005978 return exp_str;
5979}
5980
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005981static const char *first_special_char_in_vararg(const char *cp)
5982{
5983 for (;;) {
5984 if (!*cp) return NULL; /* string has no special chars */
5985 if (*cp == '$') return cp;
5986 if (*cp == '\\') return cp;
5987 if (*cp == '\'') return cp;
5988 if (*cp == '"') return cp;
5989#if ENABLE_HUSH_TICK
5990 if (*cp == '`') return cp;
5991#endif
5992 /* dquoted "${x:+ARG}" should not glob, therefore
5993 * '*' et al require some non-literal processing: */
5994 if (*cp == '*') return cp;
5995 if (*cp == '?') return cp;
5996 if (*cp == '[') return cp;
5997 cp++;
5998 }
5999}
6000
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006001/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6002 * These can contain single- and double-quoted strings,
6003 * and treated as if the ARG string is initially unquoted. IOW:
6004 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6005 * a dquoted string: "${var#"zz"}"), the difference only comes later
6006 * (word splitting and globbing of the ${var...} result).
6007 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006008#if !BASH_PATTERN_SUBST
6009#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6010 encode_then_expand_vararg(str, handle_squotes)
6011#endif
6012static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6013{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006014#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006015 const int do_unbackslash = 0;
6016#endif
6017 char *exp_str;
6018 struct in_str input;
6019 o_string dest = NULL_O_STRING;
6020
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006021 if (!first_special_char_in_vararg(str)) {
6022 /* string has no special chars */
6023 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006024 }
6025
Denys Vlasenkob762c782018-07-17 14:21:38 +02006026 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006027 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006028 exp_str = NULL;
6029
6030 for (;;) {
6031 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006032
6033 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006034 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6035 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006036
6037 if (!dest.o_expflags) {
6038 if (ch == EOF)
6039 break;
6040 if (handle_squotes && ch == '\'') {
6041 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006042 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006043 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006044 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006045 }
6046 if (ch == EOF) {
6047 syntax_error_unterm_ch('"');
6048 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006049 }
6050 if (ch == '"') {
6051 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6052 continue;
6053 }
6054 if (ch == '\\') {
6055 ch = i_getch(&input);
6056 if (ch == EOF) {
6057//example? error message? syntax_error_unterm_ch('"');
6058 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6059 goto ret;
6060 }
6061 o_addqchr(&dest, ch);
6062 continue;
6063 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006064 if (ch == '$') {
6065 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6066 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6067 goto ret;
6068 }
6069 continue;
6070 }
6071#if ENABLE_HUSH_TICK
6072 if (ch == '`') {
6073 //unsigned pos = dest->length;
6074 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6075 o_addchr(&dest, 0x80 | '`');
6076 if (!add_till_backquote(&dest, &input,
6077 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6078 )
6079 ) {
6080 goto ret; /* error */
6081 }
6082 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6083 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6084 continue;
6085 }
6086#endif
6087 o_addQchr(&dest, ch);
6088 } /* for (;;) */
6089
6090 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6091 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006092 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6093 do_unbackslash
6094 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006095 ret:
6096 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006097 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006098 return exp_str;
6099}
6100
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006101/* Expanding ARG in ${var+ARG}, ${var-ARG}
6102 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006103static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006104 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006105{
6106 struct in_str input;
6107 o_string dest = NULL_O_STRING;
6108
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006109 if (!first_special_char_in_vararg(str)
6110 && '\0' == str[strcspn(str, G.ifs)]
6111 ) {
6112 /* string has no special chars
6113 * && string has no $IFS chars
6114 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006115 if (dquoted) {
6116 /* Prints 1 (quoted expansion is a "" word, not nothing):
6117 * set -- "${notexist-}"; echo $#
6118 */
6119 output->has_quoted_part = 1;
6120 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006121 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006122 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006123
Denys Vlasenko294eb462018-07-20 16:18:59 +02006124 setup_string_in_str(&input, str);
6125
6126 for (;;) {
6127 int ch;
6128
6129 ch = i_getch(&input);
6130 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6131 __func__, ch, ch, dest.o_expflags);
6132
6133 if (!dest.o_expflags) {
6134 if (ch == EOF)
6135 break;
6136 if (!dquoted && strchr(G.ifs, ch)) {
6137 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6138 * do not assume we are at the start of the word (PREFIX above).
6139 */
6140 if (dest.data) {
6141 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006142 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006143 o_addchr(output, '\0');
6144 n = o_save_ptr(output, n); /* create next word */
6145 } else
6146 if (output->length != o_get_last_ptr(output, n)
6147 || output->has_quoted_part
6148 ) {
6149 /* For these cases:
6150 * f() { for i; do echo "|$i|"; done; }; x=x
6151 * f a${x:+ }b # 1st condition
6152 * |a|
6153 * |b|
6154 * f ""${x:+ }b # 2nd condition
6155 * ||
6156 * |b|
6157 */
6158 o_addchr(output, '\0');
6159 n = o_save_ptr(output, n); /* create next word */
6160 }
6161 continue;
6162 }
6163 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006164 if (!add_till_single_quote_dquoted(&dest, &input))
6165 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006166 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6167 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006168 continue;
6169 }
6170 }
6171 if (ch == EOF) {
6172 syntax_error_unterm_ch('"');
6173 goto ret; /* error */
6174 }
6175 if (ch == '"') {
6176 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006177 if (dest.o_expflags) {
6178 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6179 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6180 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006181 continue;
6182 }
6183 if (ch == '\\') {
6184 ch = i_getch(&input);
6185 if (ch == EOF) {
6186//example? error message? syntax_error_unterm_ch('"');
6187 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6188 goto ret;
6189 }
6190 o_addqchr(&dest, ch);
6191 continue;
6192 }
6193 if (ch == '$') {
6194 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6195 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6196 goto ret;
6197 }
6198 continue;
6199 }
6200#if ENABLE_HUSH_TICK
6201 if (ch == '`') {
6202 //unsigned pos = dest->length;
6203 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6204 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6205 if (!add_till_backquote(&dest, &input,
6206 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6207 )
6208 ) {
6209 goto ret; /* error */
6210 }
6211 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6212 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6213 continue;
6214 }
6215#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006216 if (dquoted) {
6217 /* Always glob-protect if in dquotes:
6218 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6219 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6220 */
6221 o_addqchr(&dest, ch);
6222 } else {
6223 /* Glob-protect only if char is quoted:
6224 * x=x; echo ${x:+/bin/c*} - prints many filenames
6225 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6226 */
6227 o_addQchr(&dest, ch);
6228 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006229 } /* for (;;) */
6230
6231 if (dest.data) {
6232 n = expand_vars_to_list(output, n, dest.data);
6233 }
6234 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006235 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006236 return n;
6237}
6238
Denys Vlasenko0b883582016-12-23 16:49:07 +01006239#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006240static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006241{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006242 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006243 arith_t res;
6244 char *exp_str;
6245
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006246 math_state.lookupvar = get_local_var_value;
6247 math_state.setvar = set_local_var_from_halves;
6248 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006249 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006250 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006251 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006252 if (errmsg_p)
6253 *errmsg_p = math_state.errmsg;
6254 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006255 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006256 return res;
6257}
6258#endif
6259
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006260#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006261/* ${var/[/]pattern[/repl]} helpers */
6262static char *strstr_pattern(char *val, const char *pattern, int *size)
6263{
6264 while (1) {
6265 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6266 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6267 if (end) {
6268 *size = end - val;
6269 return val;
6270 }
6271 if (*val == '\0')
6272 return NULL;
6273 /* Optimization: if "*pat" did not match the start of "string",
6274 * we know that "tring", "ring" etc will not match too:
6275 */
6276 if (pattern[0] == '*')
6277 return NULL;
6278 val++;
6279 }
6280}
6281static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6282{
6283 char *result = NULL;
6284 unsigned res_len = 0;
6285 unsigned repl_len = strlen(repl);
6286
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006287 /* Null pattern never matches, including if "var" is empty */
6288 if (!pattern[0])
6289 return result; /* NULL, no replaces happened */
6290
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006291 while (1) {
6292 int size;
6293 char *s = strstr_pattern(val, pattern, &size);
6294 if (!s)
6295 break;
6296
6297 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006298 strcpy(mempcpy(result + res_len, val, s - val), repl);
6299 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006300 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6301
6302 val = s + size;
6303 if (exp_op == '/')
6304 break;
6305 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006306 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006307 result = xrealloc(result, res_len + strlen(val) + 1);
6308 strcpy(result + res_len, val);
6309 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6310 }
6311 debug_printf_varexp("result:'%s'\n", result);
6312 return result;
6313}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006314#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006315
Denys Vlasenko168579a2018-07-19 13:45:54 +02006316static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006317 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006318{
6319 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6320 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6321 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6322 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006323 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006324 } else { /* quoted "$VAR" */
6325 output->has_quoted_part = 1;
6326 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6327 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6328 if (val && val[0])
6329 o_addQstr(output, val);
6330 }
6331 return n;
6332}
6333
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006334/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006335 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006336static NOINLINE int expand_one_var(o_string *output, int n,
6337 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006338{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006339 const char *val;
6340 char *to_be_freed;
6341 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006342 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343 char exp_op;
6344 char exp_save = exp_save; /* for compiler */
6345 char *exp_saveptr; /* points to expansion operator */
6346 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006347 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006348
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006349 val = NULL;
6350 to_be_freed = NULL;
6351 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006352 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006353 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006354 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006355 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006356 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006357 exp_op = 0;
6358
Denys Vlasenkob762c782018-07-17 14:21:38 +02006359 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006360 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6361 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6362 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006363 ) {
6364 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006365 var++;
6366 exp_op = 'L';
6367 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006368 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006370 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006371 ) {
6372 /* ${?:0}, ${#[:]%0} etc */
6373 exp_saveptr = var + 1;
6374 } else {
6375 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6376 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6377 }
6378 exp_op = exp_save = *exp_saveptr;
6379 if (exp_op) {
6380 exp_word = exp_saveptr + 1;
6381 if (exp_op == ':') {
6382 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006383//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006384 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006385 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006386 ) {
6387 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6388 exp_op = ':';
6389 exp_word--;
6390 }
6391 }
6392 *exp_saveptr = '\0';
6393 } /* else: it's not an expansion op, but bare ${var} */
6394 }
6395
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006396 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006397 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006398 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006399 int nn = xatoi_positive(var);
6400 if (nn < G.global_argc)
6401 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006402 /* else val remains NULL: $N with too big N */
6403 } else {
6404 switch (var[0]) {
6405 case '$': /* pid */
6406 val = utoa(G.root_pid);
6407 break;
6408 case '!': /* bg pid */
6409 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6410 break;
6411 case '?': /* exitcode */
6412 val = utoa(G.last_exitcode);
6413 break;
6414 case '#': /* argc */
6415 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6416 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006417 case '-': { /* active options */
6418 /* Check set_mode() to see what option chars we support */
6419 char *cp;
6420 val = cp = G.optstring_buf;
6421 if (G.o_opt[OPT_O_ERREXIT])
6422 *cp++ = 'e';
6423 if (G_interactive_fd)
6424 *cp++ = 'i';
6425 if (G_x_mode)
6426 *cp++ = 'x';
6427 /* If G.o_opt[OPT_O_NOEXEC] is true,
6428 * commands read but are not executed,
6429 * so $- can not execute too, 'n' is never seen in $-.
6430 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006431 if (G.opt_c)
6432 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006433 if (G.opt_s)
6434 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006435 *cp = '\0';
6436 break;
6437 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006438 default:
6439 val = get_local_var_value(var);
6440 }
6441 }
6442
6443 /* Handle any expansions */
6444 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006445 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006446 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006447 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006448 debug_printf_expand("%s\n", val);
6449 } else if (exp_op) {
6450 if (exp_op == '%' || exp_op == '#') {
6451 /* Standard-mandated substring removal ops:
6452 * ${parameter%word} - remove smallest suffix pattern
6453 * ${parameter%%word} - remove largest suffix pattern
6454 * ${parameter#word} - remove smallest prefix pattern
6455 * ${parameter##word} - remove largest prefix pattern
6456 *
6457 * Word is expanded to produce a glob pattern.
6458 * Then var's value is matched to it and matching part removed.
6459 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006460//FIXME: ${x#...${...}...}
6461//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6462//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006463 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006464 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006465 char *exp_exp_word;
6466 char *loc;
6467 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006468 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006469 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006470 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006471 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006472 if (exp_exp_word)
6473 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006474 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6475 /*
6476 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006477 * G.global_argv and results of utoa and get_local_var_value
6478 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006479 * scan_and_match momentarily stores NULs there.
6480 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006481 t = (char*)val;
6482 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006483 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 +02006484 free(exp_exp_word);
6485 if (loc) { /* match was found */
6486 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006487 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006489 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006490 }
6491 }
6492 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006493#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006494 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006495 /* It's ${var/[/]pattern[/repl]} thing.
6496 * Note that in encoded form it has TWO parts:
6497 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006498 * and if // is used, it is encoded as \:
6499 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006500 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006501 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006502 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006503 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006504 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006505 * >az >bz
6506 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6507 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6508 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6509 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006510 * (note that a*z _pattern_ is never globbed!)
6511 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006512 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006513 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006514 if (!pattern)
6515 pattern = xstrdup(exp_word);
6516 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6517 *p++ = SPECIAL_VAR_SYMBOL;
6518 exp_word = p;
6519 p = strchr(p, SPECIAL_VAR_SYMBOL);
6520 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006521 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006522 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6523 /* HACK ALERT. We depend here on the fact that
6524 * G.global_argv and results of utoa and get_local_var_value
6525 * are actually in writable memory:
6526 * replace_pattern momentarily stores NULs there. */
6527 t = (char*)val;
6528 to_be_freed = replace_pattern(t,
6529 pattern,
6530 (repl ? repl : exp_word),
6531 exp_op);
6532 if (to_be_freed) /* at least one replace happened */
6533 val = to_be_freed;
6534 free(pattern);
6535 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006536 } else {
6537 /* Empty variable always gives nothing */
6538 // "v=''; echo ${v/*/w}" prints "", not "w"
6539 /* Just skip "replace" part */
6540 *p++ = SPECIAL_VAR_SYMBOL;
6541 p = strchr(p, SPECIAL_VAR_SYMBOL);
6542 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006543 }
6544 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006545#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006546 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006547#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006548 /* It's ${var:N[:M]} bashism.
6549 * Note that in encoded form it has TWO parts:
6550 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6551 */
6552 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006553 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006554
Denys Vlasenko063847d2010-09-15 13:33:02 +02006555 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6556 if (errmsg)
6557 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6559 *p++ = SPECIAL_VAR_SYMBOL;
6560 exp_word = p;
6561 p = strchr(p, SPECIAL_VAR_SYMBOL);
6562 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006563 len = expand_and_evaluate_arith(exp_word, &errmsg);
6564 if (errmsg)
6565 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006566 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006567 if (beg < 0) {
6568 /* negative beg counts from the end */
6569 beg = (arith_t)strlen(val) + beg;
6570 if (beg < 0) /* ${v: -999999} is "" */
6571 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006572 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006573 debug_printf_varexp("from val:'%s'\n", val);
6574 if (len < 0) {
6575 /* in bash, len=-n means strlen()-n */
6576 len = (arith_t)strlen(val) - beg + len;
6577 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006578 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006579 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006580 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006581 arith_err:
6582 val = NULL;
6583 } else {
6584 /* Paranoia. What if user entered 9999999999999
6585 * which fits in arith_t but not int? */
6586 if (len >= INT_MAX)
6587 len = INT_MAX;
6588 val = to_be_freed = xstrndup(val + beg, len);
6589 }
6590 debug_printf_varexp("val:'%s'\n", val);
6591#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006592 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006593 val = NULL;
6594#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006595 } else { /* one of "-=+?" */
6596 /* Standard-mandated substitution ops:
6597 * ${var?word} - indicate error if unset
6598 * If var is unset, word (or a message indicating it is unset
6599 * if word is null) is written to standard error
6600 * and the shell exits with a non-zero exit status.
6601 * Otherwise, the value of var is substituted.
6602 * ${var-word} - use default value
6603 * If var is unset, word is substituted.
6604 * ${var=word} - assign and use default value
6605 * If var is unset, word is assigned to var.
6606 * In all cases, final value of var is substituted.
6607 * ${var+word} - use alternative value
6608 * If var is unset, null is substituted.
6609 * Otherwise, word is substituted.
6610 *
6611 * Word is subjected to tilde expansion, parameter expansion,
6612 * command substitution, and arithmetic expansion.
6613 * If word is not needed, it is not expanded.
6614 *
6615 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6616 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006617 *
6618 * Word-splitting and single quote behavior:
6619 *
6620 * $ f() { for i; do echo "|$i|"; done; };
6621 *
6622 * $ x=; f ${x:?'x y' z}
6623 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6624 * $ x=; f "${x:?'x y' z}"
6625 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6626 *
6627 * $ x=; f ${x:='x y' z}
6628 * |x|
6629 * |y|
6630 * |z|
6631 * $ x=; f "${x:='x y' z}"
6632 * |'x y' z|
6633 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006634 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006635 * |x y|
6636 * |z|
6637 * $ x=x; f "${x:+'x y' z}"
6638 * |'x y' z|
6639 *
6640 * $ x=; f ${x:-'x y' z}
6641 * |x y|
6642 * |z|
6643 * $ x=; f "${x:-'x y' z}"
6644 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006645 */
6646 int use_word = (!val || ((exp_save == ':') && !val[0]));
6647 if (exp_op == '+')
6648 use_word = !use_word;
6649 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6650 (exp_save == ':') ? "true" : "false", use_word);
6651 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006652 if (exp_op == '+' || exp_op == '-') {
6653 /* ${var+word} - use alternative value */
6654 /* ${var-word} - use default value */
6655 n = encode_then_append_var_plusminus(output, n, exp_word,
6656 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006657 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006658 val = NULL;
6659 } else {
6660 /* ${var?word} - indicate error if unset */
6661 /* ${var=word} - assign and use default value */
6662 to_be_freed = encode_then_expand_vararg(exp_word,
6663 /*handle_squotes:*/ !(arg0 & 0x80),
6664 /*unbackslash:*/ 0
6665 );
6666 if (to_be_freed)
6667 exp_word = to_be_freed;
6668 if (exp_op == '?') {
6669 /* mimic bash message */
6670 msg_and_die_if_script("%s: %s",
6671 var,
6672 exp_word[0]
6673 ? exp_word
6674 : "parameter null or not set"
6675 /* ash has more specific messages, a-la: */
6676 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6677 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006678//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006679//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006680// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6681// bash: x: x y z
6682// $
6683// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006684 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006685 val = exp_word;
6686 }
6687 if (exp_op == '=') {
6688 /* ${var=[word]} or ${var:=[word]} */
6689 if (isdigit(var[0]) || var[0] == '#') {
6690 /* mimic bash message */
6691 msg_and_die_if_script("$%s: cannot assign in this way", var);
6692 val = NULL;
6693 } else {
6694 char *new_var = xasprintf("%s=%s", var, val);
6695 set_local_var(new_var, /*flag:*/ 0);
6696 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006697 }
6698 }
6699 }
6700 } /* one of "-=+?" */
6701
6702 *exp_saveptr = exp_save;
6703 } /* if (exp_op) */
6704
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006705 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006706 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006707
Denys Vlasenko168579a2018-07-19 13:45:54 +02006708 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006709
6710 free(to_be_freed);
6711 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006712}
6713
6714/* Expand all variable references in given string, adding words to list[]
6715 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6716 * to be filled). This routine is extremely tricky: has to deal with
6717 * variables/parameters with whitespace, $* and $@, and constructs like
6718 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006719static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006720{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006721 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006722 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006723 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006724 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006725 char *p;
6726
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006727 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6728 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006729 debug_print_list("expand_vars_to_list[0]", output, n);
6730
6731 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6732 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006733#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006734 char arith_buf[sizeof(arith_t)*3 + 2];
6735#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006736
Denys Vlasenko168579a2018-07-19 13:45:54 +02006737 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006738 o_addchr(output, '\0');
6739 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006740 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006741 }
6742
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006743 o_addblock(output, arg, p - arg);
6744 debug_print_list("expand_vars_to_list[1]", output, n);
6745 arg = ++p;
6746 p = strchr(p, SPECIAL_VAR_SYMBOL);
6747
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006748 /* Fetch special var name (if it is indeed one of them)
6749 * and quote bit, force the bit on if singleword expansion -
6750 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006751 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006752
6753 /* Is this variable quoted and thus expansion can't be null?
6754 * "$@" is special. Even if quoted, it can still
6755 * expand to nothing (not even an empty string),
6756 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006757 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006758 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006759
6760 switch (first_ch & 0x7f) {
6761 /* Highest bit in first_ch indicates that var is double-quoted */
6762 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006763 case '@': {
6764 int i;
6765 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006766 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006767 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006768 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006770 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006771 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006772 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6773 if (G.global_argv[i++][0] && G.global_argv[i]) {
6774 /* this argv[] is not empty and not last:
6775 * put terminating NUL, start new word */
6776 o_addchr(output, '\0');
6777 debug_print_list("expand_vars_to_list[2]", output, n);
6778 n = o_save_ptr(output, n);
6779 debug_print_list("expand_vars_to_list[3]", output, n);
6780 }
6781 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006782 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006783 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006785 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006786 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006787 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788 while (1) {
6789 o_addQstr(output, G.global_argv[i]);
6790 if (++i >= G.global_argc)
6791 break;
6792 o_addchr(output, '\0');
6793 debug_print_list("expand_vars_to_list[4]", output, n);
6794 n = o_save_ptr(output, n);
6795 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006796 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006797 while (1) {
6798 o_addQstr(output, G.global_argv[i]);
6799 if (!G.global_argv[++i])
6800 break;
6801 if (G.ifs[0])
6802 o_addchr(output, G.ifs[0]);
6803 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006804 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006805 }
6806 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006807 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006808 case SPECIAL_VAR_SYMBOL: {
6809 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006810 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006811 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006812 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006813 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006814 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006815 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006816 case SPECIAL_VAR_QUOTED_SVS:
6817 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006818 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006819 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006820 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006821 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006822#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006823 case '`': {
6824 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006825 o_string subst_result = NULL_O_STRING;
6826
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006827 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006828 arg++;
6829 /* Can't just stuff it into output o_string,
6830 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006831 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006832 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6833 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006834 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006835 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006836 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006837 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006838 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006839 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006840#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006841#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006842 case '+': {
6843 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006845
6846 arg++; /* skip '+' */
6847 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6848 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006849 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006850 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6851 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006852 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006853 break;
6854 }
6855#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006856 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006857 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006858 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006859 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006860 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6861
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006862 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6863 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006864 if (*p != SPECIAL_VAR_SYMBOL)
6865 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006866 arg = ++p;
6867 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6868
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006869 if (*arg) {
6870 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006871 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006872 o_addchr(output, '\0');
6873 n = o_save_ptr(output, n);
6874 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006875 debug_print_list("expand_vars_to_list[a]", output, n);
6876 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006877 * if needed (much earlier), do not use o_addQstr here!
6878 */
6879 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006880 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006881 } else
6882 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006883 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6884 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006885 ) {
6886 n--;
6887 /* allow to reuse list[n] later without re-growth */
6888 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006889 }
6890
6891 return n;
6892}
6893
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006894static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006895{
6896 int n;
6897 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006898 o_string output = NULL_O_STRING;
6899
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006900 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006901
6902 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006903 for (;;) {
6904 /* go to next list[n] */
6905 output.ended_in_ifs = 0;
6906 n = o_save_ptr(&output, n);
6907
6908 if (!*argv)
6909 break;
6910
6911 /* expand argv[i] */
6912 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006913 /* if (!output->has_empty_slot) -- need this?? */
6914 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915 }
6916 debug_print_list("expand_variables", &output, n);
6917
6918 /* output.data (malloced in one block) gets returned in "list" */
6919 list = o_finalize_list(&output, n);
6920 debug_print_strings("expand_variables[1]", list);
6921 return list;
6922}
6923
6924static char **expand_strvec_to_strvec(char **argv)
6925{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006926 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006927}
6928
Denys Vlasenko11752d42018-04-03 08:20:58 +02006929#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006930static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6931{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006932 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006933}
6934#endif
6935
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006936/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006937 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006938 *
6939 * NB: should NOT do globbing!
6940 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6941 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006942static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006943{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006944#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006945 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006946 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006947#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006948 char *argv[2], **list;
6949
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006950 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006951 /* This is generally an optimization, but it also
6952 * handles "", which otherwise trips over !list[0] check below.
6953 * (is this ever happens that we actually get str="" here?)
6954 */
6955 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6956 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006957 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958 return xstrdup(str);
6959 }
6960
6961 argv[0] = (char*)str;
6962 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006963 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006964 if (!list[0]) {
6965 /* Example where it happens:
6966 * x=; echo ${x:-"$@"}
6967 */
6968 ((char*)list)[0] = '\0';
6969 } else {
6970 if (HUSH_DEBUG)
6971 if (list[1])
James Byrne69374872019-07-02 11:35:03 +02006972 bb_simple_error_msg_and_die("BUG in varexp2");
Denys Vlasenko2e711012018-07-18 16:02:25 +02006973 /* actually, just move string 2*sizeof(char*) bytes back */
6974 overlapping_strcpy((char*)list, list[0]);
6975 if (do_unbackslash)
6976 unbackslash((char*)list);
6977 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006978 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006979 return (char*)list;
6980}
6981
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006982#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006983static char* expand_strvec_to_string(char **argv)
6984{
6985 char **list;
6986
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006987 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006988 /* Convert all NULs to spaces */
6989 if (list[0]) {
6990 int n = 1;
6991 while (list[n]) {
6992 if (HUSH_DEBUG)
6993 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6994 bb_error_msg_and_die("BUG in varexp3");
6995 /* bash uses ' ' regardless of $IFS contents */
6996 list[n][-1] = ' ';
6997 n++;
6998 }
6999 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02007000 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007001 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
7002 return (char*)list;
7003}
Denys Vlasenko1f191122018-01-11 13:17:30 +01007004#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007005
7006static char **expand_assignments(char **argv, int count)
7007{
7008 int i;
7009 char **p;
7010
7011 G.expanded_assignments = p = NULL;
7012 /* Expand assignments into one string each */
7013 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007014 p = add_string_to_strings(p,
7015 expand_string_to_string(argv[i],
7016 EXP_FLAG_ESC_GLOB_CHARS,
7017 /*unbackslash:*/ 1
7018 )
7019 );
7020 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007021 }
7022 G.expanded_assignments = NULL;
7023 return p;
7024}
7025
7026
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007027static void switch_off_special_sigs(unsigned mask)
7028{
7029 unsigned sig = 0;
7030 while ((mask >>= 1) != 0) {
7031 sig++;
7032 if (!(mask & 1))
7033 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007034#if ENABLE_HUSH_TRAP
7035 if (G_traps) {
7036 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007037 /* trap is '', has to remain SIG_IGN */
7038 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007039 free(G_traps[sig]);
7040 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007041 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007042#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007043 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007044 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007045 }
7046}
7047
Denys Vlasenkob347df92011-08-09 22:49:15 +02007048#if BB_MMU
7049/* never called */
7050void re_execute_shell(char ***to_free, const char *s,
7051 char *g_argv0, char **g_argv,
7052 char **builtin_argv) NORETURN;
7053
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007054static void reset_traps_to_defaults(void)
7055{
7056 /* This function is always called in a child shell
7057 * after fork (not vfork, NOMMU doesn't use this function).
7058 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007059 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007060 unsigned mask;
7061
7062 /* Child shells are not interactive.
7063 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7064 * Testcase: (while :; do :; done) + ^Z should background.
7065 * Same goes for SIGTERM, SIGHUP, SIGINT.
7066 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007067 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007068 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007069 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007070
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007071 /* Switch off special sigs */
7072 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007073# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007074 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007075# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007076 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007077 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7078 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007080# if ENABLE_HUSH_TRAP
7081 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007082 return;
7083
7084 /* Reset all sigs to default except ones with empty traps */
7085 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007086 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007087 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007088 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007089 continue; /* empty trap: has to remain SIG_IGN */
7090 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007091 free(G_traps[sig]);
7092 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007093 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007094 if (sig == 0)
7095 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007096 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007097 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007098# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007099}
7100
7101#else /* !BB_MMU */
7102
7103static void re_execute_shell(char ***to_free, const char *s,
7104 char *g_argv0, char **g_argv,
7105 char **builtin_argv) NORETURN;
7106static void re_execute_shell(char ***to_free, const char *s,
7107 char *g_argv0, char **g_argv,
7108 char **builtin_argv)
7109{
7110# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7111 /* delims + 2 * (number of bytes in printed hex numbers) */
7112 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7113 char *heredoc_argv[4];
7114 struct variable *cur;
7115# if ENABLE_HUSH_FUNCTIONS
7116 struct function *funcp;
7117# endif
7118 char **argv, **pp;
7119 unsigned cnt;
7120 unsigned long long empty_trap_mask;
7121
7122 if (!g_argv0) { /* heredoc */
7123 argv = heredoc_argv;
7124 argv[0] = (char *) G.argv0_for_re_execing;
7125 argv[1] = (char *) "-<";
7126 argv[2] = (char *) s;
7127 argv[3] = NULL;
7128 pp = &argv[3]; /* used as pointer to empty environment */
7129 goto do_exec;
7130 }
7131
7132 cnt = 0;
7133 pp = builtin_argv;
7134 if (pp) while (*pp++)
7135 cnt++;
7136
7137 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007138 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007139 int sig;
7140 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007141 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007142 empty_trap_mask |= 1LL << sig;
7143 }
7144 }
7145
7146 sprintf(param_buf, NOMMU_HACK_FMT
7147 , (unsigned) G.root_pid
7148 , (unsigned) G.root_ppid
7149 , (unsigned) G.last_bg_pid
7150 , (unsigned) G.last_exitcode
7151 , cnt
7152 , empty_trap_mask
7153 IF_HUSH_LOOPS(, G.depth_of_loop)
7154 );
7155# undef NOMMU_HACK_FMT
7156 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7157 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7158 */
7159 cnt += 6;
7160 for (cur = G.top_var; cur; cur = cur->next) {
7161 if (!cur->flg_export || cur->flg_read_only)
7162 cnt += 2;
7163 }
7164# if ENABLE_HUSH_FUNCTIONS
7165 for (funcp = G.top_func; funcp; funcp = funcp->next)
7166 cnt += 3;
7167# endif
7168 pp = g_argv;
7169 while (*pp++)
7170 cnt++;
7171 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7172 *pp++ = (char *) G.argv0_for_re_execing;
7173 *pp++ = param_buf;
7174 for (cur = G.top_var; cur; cur = cur->next) {
7175 if (strcmp(cur->varstr, hush_version_str) == 0)
7176 continue;
7177 if (cur->flg_read_only) {
7178 *pp++ = (char *) "-R";
7179 *pp++ = cur->varstr;
7180 } else if (!cur->flg_export) {
7181 *pp++ = (char *) "-V";
7182 *pp++ = cur->varstr;
7183 }
7184 }
7185# if ENABLE_HUSH_FUNCTIONS
7186 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7187 *pp++ = (char *) "-F";
7188 *pp++ = funcp->name;
7189 *pp++ = funcp->body_as_string;
7190 }
7191# endif
7192 /* We can pass activated traps here. Say, -Tnn:trap_string
7193 *
7194 * However, POSIX says that subshells reset signals with traps
7195 * to SIG_DFL.
7196 * I tested bash-3.2 and it not only does that with true subshells
7197 * of the form ( list ), but with any forked children shells.
7198 * I set trap "echo W" WINCH; and then tried:
7199 *
7200 * { echo 1; sleep 20; echo 2; } &
7201 * while true; do echo 1; sleep 20; echo 2; break; done &
7202 * true | { echo 1; sleep 20; echo 2; } | cat
7203 *
7204 * In all these cases sending SIGWINCH to the child shell
7205 * did not run the trap. If I add trap "echo V" WINCH;
7206 * _inside_ group (just before echo 1), it works.
7207 *
7208 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007209 */
7210 *pp++ = (char *) "-c";
7211 *pp++ = (char *) s;
7212 if (builtin_argv) {
7213 while (*++builtin_argv)
7214 *pp++ = *builtin_argv;
7215 *pp++ = (char *) "";
7216 }
7217 *pp++ = g_argv0;
7218 while (*g_argv)
7219 *pp++ = *g_argv++;
7220 /* *pp = NULL; - is already there */
7221 pp = environ;
7222
7223 do_exec:
7224 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007225 /* Don't propagate SIG_IGN to the child */
7226 if (SPECIAL_JOBSTOP_SIGS != 0)
7227 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007228 execve(bb_busybox_exec_path, argv, pp);
7229 /* Fallback. Useful for init=/bin/hush usage etc */
7230 if (argv[0][0] == '/')
7231 execve(argv[0], argv, pp);
7232 xfunc_error_retval = 127;
James Byrne69374872019-07-02 11:35:03 +02007233 bb_simple_error_msg_and_die("can't re-execute the shell");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007234}
7235#endif /* !BB_MMU */
7236
7237
7238static int run_and_free_list(struct pipe *pi);
7239
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007240/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007241 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7242 * end_trigger controls how often we stop parsing
7243 * NUL: parse all, execute, return
7244 * ';': parse till ';' or newline, execute, repeat till EOF
7245 */
7246static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007247{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007248 /* Why we need empty flag?
7249 * An obscure corner case "false; ``; echo $?":
7250 * empty command in `` should still set $? to 0.
7251 * But we can't just set $? to 0 at the start,
7252 * this breaks "false; echo `echo $?`" case.
7253 */
7254 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007255 while (1) {
7256 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007257
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007258#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007259 if (end_trigger == ';') {
7260 G.promptmode = 0; /* PS1 */
7261 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7262 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007263#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007264 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007265 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7266 /* If we are in "big" script
7267 * (not in `cmd` or something similar)...
7268 */
7269 if (pipe_list == ERR_PTR && end_trigger == ';') {
7270 /* Discard cached input (rest of line) */
7271 int ch = inp->last_char;
7272 while (ch != EOF && ch != '\n') {
7273 //bb_error_msg("Discarded:'%c'", ch);
7274 ch = i_getch(inp);
7275 }
7276 /* Force prompt */
7277 inp->p = NULL;
7278 /* This stream isn't empty */
7279 empty = 0;
7280 continue;
7281 }
7282 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007283 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007284 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007285 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007286 debug_print_tree(pipe_list, 0);
7287 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7288 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007289 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007290 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007291 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007292 }
Eric Andersen25f27032001-04-26 23:22:31 +00007293}
7294
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007295static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007296{
7297 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007298 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007299
Eric Andersen25f27032001-04-26 23:22:31 +00007300 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007301 parse_and_run_stream(&input, '\0');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007302 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007303}
7304
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007305static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007306{
Eric Andersen25f27032001-04-26 23:22:31 +00007307 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007308 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007309
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007310 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007311 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007312 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007313 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007314}
7315
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007316#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007317static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007318{
7319 pid_t pid;
7320 int channel[2];
7321# if !BB_MMU
7322 char **to_free = NULL;
7323# endif
7324
7325 xpipe(channel);
7326 pid = BB_MMU ? xfork() : xvfork();
7327 if (pid == 0) { /* child */
7328 disable_restore_tty_pgrp_on_exit();
7329 /* Process substitution is not considered to be usual
7330 * 'command execution'.
7331 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7332 */
7333 bb_signals(0
7334 + (1 << SIGTSTP)
7335 + (1 << SIGTTIN)
7336 + (1 << SIGTTOU)
7337 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007338 close(channel[0]); /* NB: close _first_, then move fd! */
7339 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007340# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007341 /* Awful hack for `trap` or $(trap).
7342 *
7343 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7344 * contains an example where "trap" is executed in a subshell:
7345 *
7346 * save_traps=$(trap)
7347 * ...
7348 * eval "$save_traps"
7349 *
7350 * Standard does not say that "trap" in subshell shall print
7351 * parent shell's traps. It only says that its output
7352 * must have suitable form, but then, in the above example
7353 * (which is not supposed to be normative), it implies that.
7354 *
7355 * bash (and probably other shell) does implement it
7356 * (traps are reset to defaults, but "trap" still shows them),
7357 * but as a result, "trap" logic is hopelessly messed up:
7358 *
7359 * # trap
7360 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7361 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7362 * # true | trap <--- trap is in subshell - no output (ditto)
7363 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7364 * trap -- 'echo Ho' SIGWINCH
7365 * # echo `(trap)` <--- in subshell in subshell - output
7366 * trap -- 'echo Ho' SIGWINCH
7367 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7368 * trap -- 'echo Ho' SIGWINCH
7369 *
7370 * The rules when to forget and when to not forget traps
7371 * get really complex and nonsensical.
7372 *
7373 * Our solution: ONLY bare $(trap) or `trap` is special.
7374 */
7375 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007376 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007377 && skip_whitespace(s + 4)[0] == '\0'
7378 ) {
7379 static const char *const argv[] = { NULL, NULL };
7380 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007381 fflush_all(); /* important */
7382 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007383 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007384# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007385# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007386 /* Prevent it from trying to handle ctrl-z etc */
7387 IF_HUSH_JOB(G.run_list_level = 1;)
7388 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007389 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007390 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007391 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007392 parse_and_run_string(s);
7393 _exit(G.last_exitcode);
7394# else
7395 /* We re-execute after vfork on NOMMU. This makes this script safe:
7396 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7397 * huge=`cat BIG` # was blocking here forever
7398 * echo OK
7399 */
7400 re_execute_shell(&to_free,
7401 s,
7402 G.global_argv[0],
7403 G.global_argv + 1,
7404 NULL);
7405# endif
7406 }
7407
7408 /* parent */
7409 *pid_p = pid;
7410# if ENABLE_HUSH_FAST
7411 G.count_SIGCHLD++;
7412//bb_error_msg("[%d] fork in generate_stream_from_string:"
7413// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7414// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7415# endif
7416 enable_restore_tty_pgrp_on_exit();
7417# if !BB_MMU
7418 free(to_free);
7419# endif
7420 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007421 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007422}
7423
7424/* Return code is exit status of the process that is run. */
7425static int process_command_subs(o_string *dest, const char *s)
7426{
7427 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007428 pid_t pid;
7429 int status, ch, eol_cnt;
7430
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007431 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007432
7433 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007434 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007435 while ((ch = getc(fp)) != EOF) {
7436 if (ch == '\0')
7437 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007438 if (ch == '\n') {
7439 eol_cnt++;
7440 continue;
7441 }
7442 while (eol_cnt) {
7443 o_addchr(dest, '\n');
7444 eol_cnt--;
7445 }
7446 o_addQchr(dest, ch);
7447 }
7448
7449 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007450 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007451 /* We need to extract exitcode. Test case
7452 * "true; echo `sleep 1; false` $?"
7453 * should print 1 */
7454 safe_waitpid(pid, &status, 0);
7455 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7456 return WEXITSTATUS(status);
7457}
7458#endif /* ENABLE_HUSH_TICK */
7459
7460
7461static void setup_heredoc(struct redir_struct *redir)
7462{
7463 struct fd_pair pair;
7464 pid_t pid;
7465 int len, written;
7466 /* the _body_ of heredoc (misleading field name) */
7467 const char *heredoc = redir->rd_filename;
7468 char *expanded;
7469#if !BB_MMU
7470 char **to_free;
7471#endif
7472
7473 expanded = NULL;
7474 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007475 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007476 if (expanded)
7477 heredoc = expanded;
7478 }
7479 len = strlen(heredoc);
7480
7481 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7482 xpiped_pair(pair);
7483 xmove_fd(pair.rd, redir->rd_fd);
7484
7485 /* Try writing without forking. Newer kernels have
7486 * dynamically growing pipes. Must use non-blocking write! */
7487 ndelay_on(pair.wr);
7488 while (1) {
7489 written = write(pair.wr, heredoc, len);
7490 if (written <= 0)
7491 break;
7492 len -= written;
7493 if (len == 0) {
7494 close(pair.wr);
7495 free(expanded);
7496 return;
7497 }
7498 heredoc += written;
7499 }
7500 ndelay_off(pair.wr);
7501
7502 /* Okay, pipe buffer was not big enough */
7503 /* Note: we must not create a stray child (bastard? :)
7504 * for the unsuspecting parent process. Child creates a grandchild
7505 * and exits before parent execs the process which consumes heredoc
7506 * (that exec happens after we return from this function) */
7507#if !BB_MMU
7508 to_free = NULL;
7509#endif
7510 pid = xvfork();
7511 if (pid == 0) {
7512 /* child */
7513 disable_restore_tty_pgrp_on_exit();
7514 pid = BB_MMU ? xfork() : xvfork();
7515 if (pid != 0)
7516 _exit(0);
7517 /* grandchild */
7518 close(redir->rd_fd); /* read side of the pipe */
7519#if BB_MMU
7520 full_write(pair.wr, heredoc, len); /* may loop or block */
7521 _exit(0);
7522#else
7523 /* Delegate blocking writes to another process */
7524 xmove_fd(pair.wr, STDOUT_FILENO);
7525 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7526#endif
7527 }
7528 /* parent */
7529#if ENABLE_HUSH_FAST
7530 G.count_SIGCHLD++;
7531//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7532#endif
7533 enable_restore_tty_pgrp_on_exit();
7534#if !BB_MMU
7535 free(to_free);
7536#endif
7537 close(pair.wr);
7538 free(expanded);
7539 wait(NULL); /* wait till child has died */
7540}
7541
Denys Vlasenko2db74612017-07-07 22:07:28 +02007542struct squirrel {
7543 int orig_fd;
7544 int moved_to;
7545 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7546 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7547};
7548
Denys Vlasenko621fc502017-07-24 12:42:17 +02007549static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7550{
7551 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7552 sq[i].orig_fd = orig;
7553 sq[i].moved_to = moved;
7554 sq[i+1].orig_fd = -1; /* end marker */
7555 return sq;
7556}
7557
Denys Vlasenko2db74612017-07-07 22:07:28 +02007558static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7559{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007560 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007561 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007562
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007563 i = 0;
7564 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007565 /* If we collide with an already moved fd... */
7566 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007567 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007568 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7569 if (sq[i].moved_to < 0) /* what? */
7570 xfunc_die();
7571 return sq;
7572 }
7573 if (fd == sq[i].orig_fd) {
7574 /* Example: echo Hello >/dev/null 1>&2 */
7575 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7576 return sq;
7577 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007578 }
7579
Denys Vlasenko2db74612017-07-07 22:07:28 +02007580 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007581 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007582 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7583 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007584 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007585 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007586}
7587
Denys Vlasenko657e9002017-07-30 23:34:04 +02007588static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7589{
7590 int i;
7591
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007592 i = 0;
7593 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007594 /* If we collide with an already moved fd... */
7595 if (fd == sq[i].orig_fd) {
7596 /* Examples:
7597 * "echo 3>FILE 3>&- 3>FILE"
7598 * "echo 3>&- 3>FILE"
7599 * No need for last redirect to insert
7600 * another "need to close 3" indicator.
7601 */
7602 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7603 return sq;
7604 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007605 }
7606
7607 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7608 return append_squirrel(sq, i, fd, -1);
7609}
7610
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007611/* fd: redirect wants this fd to be used (e.g. 3>file).
7612 * Move all conflicting internally used fds,
7613 * and remember them so that we can restore them later.
7614 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007615static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007616{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007617 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7618 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007619
7620#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko21806562019-11-01 14:16:07 +01007621 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7622 && fd == G_interactive_fd
7623 ) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007624 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007625 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7626 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007627 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007628 }
7629#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007630 /* Are we called from setup_redirects(squirrel==NULL)
7631 * in redirect in a [v]forked child?
7632 */
7633 if (sqp == NULL) {
7634 /* No need to move script fds.
7635 * For NOMMU case, it's actively wrong: we'd change ->fd
7636 * fields in memory for the parent, but parent's fds
Denys Vlasenko21806562019-11-01 14:16:07 +01007637 * aren't moved, it would use wrong fd!
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007638 * Reproducer: "cmd 3>FILE" in script.
7639 * If we would call move_HFILEs_on_redirect(), child would:
7640 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7641 * close(3) = 0
7642 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7643 */
7644 //bb_error_msg("sqp == NULL: [v]forked child");
7645 return 0;
7646 }
7647
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007648 /* If this one of script's fds? */
7649 if (move_HFILEs_on_redirect(fd, avoid_fd))
7650 return 1; /* yes. "we closed fd" (actually moved it) */
7651
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007652 /* Are we called for "exec 3>FILE"? Came through
7653 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7654 * This case used to fail for this script:
7655 * exec 3>FILE
7656 * echo Ok
7657 * ...100000 more lines...
7658 * echo Ok
7659 * as follows:
7660 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7661 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7662 * dup2(4, 3) = 3
7663 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7664 * close(4) = 0
7665 * write(1, "Ok\n", 3) = 3
7666 * ... = 3
7667 * write(1, "Ok\n", 3) = 3
7668 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7669 * ^^^^^^^^ oops, wrong fd!!!
7670 * With this case separate from sqp == NULL and *after* move_HFILEs,
7671 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007672 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007673 if (sqp == ERR_PTR) {
7674 /* Don't preserve redirected fds: exec is _meant_ to change these */
7675 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007676 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007677 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007678
Denys Vlasenko2db74612017-07-07 22:07:28 +02007679 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7680 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7681 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007682}
7683
Denys Vlasenko2db74612017-07-07 22:07:28 +02007684static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007685{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007686 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007687 int i;
7688 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007689 if (sq[i].moved_to >= 0) {
7690 /* We simply die on error */
7691 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7692 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7693 } else {
7694 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7695 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7696 close(sq[i].orig_fd);
7697 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007698 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007699 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007700 }
Denys Vlasenko21806562019-11-01 14:16:07 +01007701 if (G.HFILE_stdin
7702 && G.HFILE_stdin->fd != STDIN_FILENO
7703 ) {
7704 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7705 * Redirect moves ->fd to e.g. 10,
7706 * and it is not restored above (we do not restore script fds
7707 * after redirects, we just use new, "moved" fds).
7708 * However for stdin, get_user_input() -> read_line_input(),
7709 * and read builtin, depend on fd == STDIN_FILENO.
7710 */
7711 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7712 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
7713 G.HFILE_stdin->fd = STDIN_FILENO;
7714 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007715
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007716 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007717}
7718
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007719#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007720static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007721{
7722 if (G_interactive_fd)
7723 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007724 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007725}
7726#endif
7727
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007728static int internally_opened_fd(int fd, struct squirrel *sq)
7729{
7730 int i;
7731
7732#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007733 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007734 return 1;
7735#endif
7736 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007737 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007738 return 1;
7739
7740 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7741 if (fd == sq[i].moved_to)
7742 return 1;
7743 }
7744 return 0;
7745}
7746
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007747/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7748 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007749static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007750{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007751 struct redir_struct *redir;
7752
7753 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007754 int newfd;
7755 int closed;
7756
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007757 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007758 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007759 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007760 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7761 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007762 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007763 redir->rd_filename);
7764 setup_heredoc(redir);
7765 continue;
7766 }
7767
7768 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007769 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007770 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007771 int mode;
7772
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007773 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007774 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007775 * "cmd >" (no filename)
7776 * "cmd > <file" (2nd redirect starts too early)
7777 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007778 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007779 continue;
7780 }
7781 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007782 p = expand_string_to_string(redir->rd_filename,
7783 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007784 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007785 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007786 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007787 /* Error message from open_or_warn can be lost
7788 * if stderr has been redirected, but bash
7789 * and ash both lose it as well
7790 * (though zsh doesn't!)
7791 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007792 return 1;
7793 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007794 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007795 /* open() gave us precisely the fd we wanted.
7796 * This means that this fd was not busy
7797 * (not opened to anywhere).
7798 * Remember to close it on restore:
7799 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007800 *sqp = add_squirrel_closed(*sqp, newfd);
7801 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007802 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007803 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007804 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7805 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007806 }
7807
Denys Vlasenko657e9002017-07-30 23:34:04 +02007808 if (newfd == redir->rd_fd)
7809 continue;
7810
7811 /* if "N>FILE": move newfd to redir->rd_fd */
7812 /* if "N>&M": dup newfd to redir->rd_fd */
7813 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7814
7815 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7816 if (newfd == REDIRFD_CLOSE) {
7817 /* "N>&-" means "close me" */
7818 if (!closed) {
7819 /* ^^^ optimization: saving may already
7820 * have closed it. If not... */
7821 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007822 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007823 /* Sometimes we do another close on restore, getting EBADF.
7824 * Consider "echo 3>FILE 3>&-"
7825 * first redirect remembers "need to close 3",
7826 * and second redirect closes 3! Restore code then closes 3 again.
7827 */
7828 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007829 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007830 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007831 //errno = EBADF;
7832 //bb_perror_msg_and_die("can't duplicate file descriptor");
7833 newfd = -1; /* same effect as code above */
7834 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007835 xdup2(newfd, redir->rd_fd);
7836 if (redir->rd_dup == REDIRFD_TO_FILE)
7837 /* "rd_fd > FILE" */
7838 close(newfd);
7839 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007840 }
7841 }
7842 return 0;
7843}
7844
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007845static char *find_in_path(const char *arg)
7846{
7847 char *ret = NULL;
7848 const char *PATH = get_local_var_value("PATH");
7849
7850 if (!PATH)
7851 return NULL;
7852
7853 while (1) {
7854 const char *end = strchrnul(PATH, ':');
7855 int sz = end - PATH; /* must be int! */
7856
7857 free(ret);
7858 if (sz != 0) {
7859 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7860 } else {
7861 /* We have xxx::yyyy in $PATH,
7862 * it means "use current dir" */
7863 ret = xstrdup(arg);
7864 }
7865 if (access(ret, F_OK) == 0)
7866 break;
7867
7868 if (*end == '\0') {
7869 free(ret);
7870 return NULL;
7871 }
7872 PATH = end + 1;
7873 }
7874
7875 return ret;
7876}
7877
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007878static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879 const struct built_in_command *x,
7880 const struct built_in_command *end)
7881{
7882 while (x != end) {
7883 if (strcmp(name, x->b_cmd) != 0) {
7884 x++;
7885 continue;
7886 }
7887 debug_printf_exec("found builtin '%s'\n", name);
7888 return x;
7889 }
7890 return NULL;
7891}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007892static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007893{
7894 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7895}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007896static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007897{
7898 const struct built_in_command *x = find_builtin1(name);
7899 if (x)
7900 return x;
7901 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7902}
7903
Ron Yorston9e2a5662020-01-21 16:01:58 +00007904#if EDITING_HAS_get_exe_name
7905static const char * FAST_FUNC get_builtin_name(int i)
7906{
7907 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
7908 return bltins1[i].b_cmd;
7909 }
7910 i -= ARRAY_SIZE(bltins1);
7911 if (i < ARRAY_SIZE(bltins2)) {
7912 return bltins2[i].b_cmd;
7913 }
7914 return NULL;
7915}
7916#endif
7917
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007918static void remove_nested_vars(void)
7919{
7920 struct variable *cur;
7921 struct variable **cur_pp;
7922
7923 cur_pp = &G.top_var;
7924 while ((cur = *cur_pp) != NULL) {
7925 if (cur->var_nest_level <= G.var_nest_level) {
7926 cur_pp = &cur->next;
7927 continue;
7928 }
7929 /* Unexport */
7930 if (cur->flg_export) {
7931 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7932 bb_unsetenv(cur->varstr);
7933 }
7934 /* Remove from global list */
7935 *cur_pp = cur->next;
7936 /* Free */
7937 if (!cur->max_len) {
7938 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7939 free(cur->varstr);
7940 }
7941 free(cur);
7942 }
7943}
7944
7945static void enter_var_nest_level(void)
7946{
7947 G.var_nest_level++;
7948 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7949
7950 /* Try: f() { echo -n .; f; }; f
7951 * struct variable::var_nest_level is uint16_t,
7952 * thus limiting recursion to < 2^16.
7953 * In any case, with 8 Mbyte stack SEGV happens
7954 * not too long after 2^16 recursions anyway.
7955 */
7956 if (G.var_nest_level > 0xff00)
7957 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7958}
7959
7960static void leave_var_nest_level(void)
7961{
7962 G.var_nest_level--;
7963 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7964 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
James Byrne69374872019-07-02 11:35:03 +02007965 bb_simple_error_msg_and_die("BUG: nesting underflow");
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007966
7967 remove_nested_vars();
7968}
7969
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007970#if ENABLE_HUSH_FUNCTIONS
7971static struct function **find_function_slot(const char *name)
7972{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007973 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007974 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007975
7976 while ((funcp = *funcpp) != NULL) {
7977 if (strcmp(name, funcp->name) == 0) {
7978 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007979 break;
7980 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007981 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007982 }
7983 return funcpp;
7984}
7985
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007986static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007987{
7988 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007989 return funcp;
7990}
7991
7992/* Note: takes ownership on name ptr */
7993static struct function *new_function(char *name)
7994{
7995 struct function **funcpp = find_function_slot(name);
7996 struct function *funcp = *funcpp;
7997
7998 if (funcp != NULL) {
7999 struct command *cmd = funcp->parent_cmd;
8000 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
8001 if (!cmd) {
8002 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
8003 free(funcp->name);
8004 /* Note: if !funcp->body, do not free body_as_string!
8005 * This is a special case of "-F name body" function:
8006 * body_as_string was not malloced! */
8007 if (funcp->body) {
8008 free_pipe_list(funcp->body);
8009# if !BB_MMU
8010 free(funcp->body_as_string);
8011# endif
8012 }
8013 } else {
8014 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8015 cmd->argv[0] = funcp->name;
8016 cmd->group = funcp->body;
8017# if !BB_MMU
8018 cmd->group_as_string = funcp->body_as_string;
8019# endif
8020 }
8021 } else {
8022 debug_printf_exec("remembering new function '%s'\n", name);
8023 funcp = *funcpp = xzalloc(sizeof(*funcp));
8024 /*funcp->next = NULL;*/
8025 }
8026
8027 funcp->name = name;
8028 return funcp;
8029}
8030
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008031# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008032static void unset_func(const char *name)
8033{
8034 struct function **funcpp = find_function_slot(name);
8035 struct function *funcp = *funcpp;
8036
8037 if (funcp != NULL) {
8038 debug_printf_exec("freeing function '%s'\n", funcp->name);
8039 *funcpp = funcp->next;
8040 /* funcp is unlinked now, deleting it.
8041 * Note: if !funcp->body, the function was created by
8042 * "-F name body", do not free ->body_as_string
8043 * and ->name as they were not malloced. */
8044 if (funcp->body) {
8045 free_pipe_list(funcp->body);
8046 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008047# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008048 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008049# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008050 }
8051 free(funcp);
8052 }
8053}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008054# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008055
8056# if BB_MMU
8057#define exec_function(to_free, funcp, argv) \
8058 exec_function(funcp, argv)
8059# endif
8060static void exec_function(char ***to_free,
8061 const struct function *funcp,
8062 char **argv) NORETURN;
8063static void exec_function(char ***to_free,
8064 const struct function *funcp,
8065 char **argv)
8066{
8067# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008068 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008069
8070 argv[0] = G.global_argv[0];
8071 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008072 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008073
8074// Example when we are here: "cmd | func"
8075// func will run with saved-redirect fds open.
8076// $ f() { echo /proc/self/fd/*; }
8077// $ true | f
8078// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8079// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8080// Same in script:
8081// $ . ./SCRIPT
8082// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8083// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8084// They are CLOEXEC so external programs won't see them, but
8085// for "more correctness" we might want to close those extra fds here:
8086//? close_saved_fds_and_FILE_fds();
8087
Denys Vlasenko332e4112018-04-04 22:32:59 +02008088 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008089 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008090 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008091 IF_HUSH_LOCAL(G.func_nest_level++;)
8092
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008093 /* On MMU, funcp->body is always non-NULL */
8094 n = run_list(funcp->body);
8095 fflush_all();
8096 _exit(n);
8097# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008098//? close_saved_fds_and_FILE_fds();
8099
8100//TODO: check whether "true | func_with_return" works
8101
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008102 re_execute_shell(to_free,
8103 funcp->body_as_string,
8104 G.global_argv[0],
8105 argv + 1,
8106 NULL);
8107# endif
8108}
8109
8110static int run_function(const struct function *funcp, char **argv)
8111{
8112 int rc;
8113 save_arg_t sv;
8114 smallint sv_flg;
8115
8116 save_and_replace_G_args(&sv, argv);
8117
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008118 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008119 sv_flg = G_flag_return_in_progress;
8120 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008121
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008122 /* Make "local" variables properly shadow previous ones */
8123 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008124 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008125
8126 /* On MMU, funcp->body is always non-NULL */
8127# if !BB_MMU
8128 if (!funcp->body) {
8129 /* Function defined by -F */
8130 parse_and_run_string(funcp->body_as_string);
8131 rc = G.last_exitcode;
8132 } else
8133# endif
8134 {
8135 rc = run_list(funcp->body);
8136 }
8137
Denys Vlasenko332e4112018-04-04 22:32:59 +02008138 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008139 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008140
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008141 G_flag_return_in_progress = sv_flg;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01008142# if ENABLE_HUSH_TRAP
8143 debug_printf_exec("G.return_exitcode=-1\n");
8144 G.return_exitcode = -1; /* invalidate stashed return value */
8145# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008146
8147 restore_G_args(&sv, argv);
8148
8149 return rc;
8150}
8151#endif /* ENABLE_HUSH_FUNCTIONS */
8152
8153
8154#if BB_MMU
8155#define exec_builtin(to_free, x, argv) \
8156 exec_builtin(x, argv)
8157#else
8158#define exec_builtin(to_free, x, argv) \
8159 exec_builtin(to_free, argv)
8160#endif
8161static void exec_builtin(char ***to_free,
8162 const struct built_in_command *x,
8163 char **argv) NORETURN;
8164static void exec_builtin(char ***to_free,
8165 const struct built_in_command *x,
8166 char **argv)
8167{
8168#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008169 int rcode;
8170 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008171//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008172 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008173 fflush_all();
8174 _exit(rcode);
8175#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008176 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008177 /* On NOMMU, we must never block!
8178 * Example: { sleep 99 | read line; } & echo Ok
8179 */
8180 re_execute_shell(to_free,
8181 argv[0],
8182 G.global_argv[0],
8183 G.global_argv + 1,
8184 argv);
8185#endif
8186}
8187
8188
8189static void execvp_or_die(char **argv) NORETURN;
8190static void execvp_or_die(char **argv)
8191{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008192 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008193 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008194 /* Don't propagate SIG_IGN to the child */
8195 if (SPECIAL_JOBSTOP_SIGS != 0)
8196 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008197 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008198 e = 2;
8199 if (errno == EACCES) e = 126;
8200 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008201 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008202 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008203}
8204
8205#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008206static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008207{
8208 unsigned len;
8209 const char *cp;
8210
8211 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008212
8213 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8214 /* test a char with: bash -c 'set -x; echo "CH"' */
8215 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8216 " " "\001\002\003\004\005\006\007"
8217 "\010\011\012\013\014\015\016\017"
8218 "\020\021\022\023\024\025\026\027"
8219 "\030\031\032\033\034\035\036\037"
8220 )
8221 ] == '\0'
8222 ) {
8223 /* string has no special chars */
8224 x_mode_addstr(str);
8225 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008226 }
8227
8228 cp = str;
8229 for (;;) {
8230 /* print '....' up to EOL or first squote */
8231 len = (int)(strchrnul(cp, '\'') - cp);
8232 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008233 x_mode_addchr('\'');
8234 x_mode_addblock(cp, len);
8235 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008236 cp += len;
8237 }
8238 if (*cp == '\0')
8239 break;
8240 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008241 x_mode_addchr('\\');
8242 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008243 cp++;
8244 }
8245}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008246static void dump_cmd_in_x_mode(char **argv)
8247{
8248 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008249 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008250
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008251 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008252 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008253 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008254 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008255 x_mode_addchr(' ');
8256 if (argv[n][0] == '\0') {
8257 x_mode_addchr('\'');
8258 x_mode_addchr('\'');
8259 } else {
8260 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008261 }
8262 n++;
8263 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008264 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008265 }
8266}
8267#else
8268# define dump_cmd_in_x_mode(argv) ((void)0)
8269#endif
8270
Denys Vlasenko57000292018-01-12 14:41:45 +01008271#if ENABLE_HUSH_COMMAND
8272static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8273{
8274 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008275
Denys Vlasenko57000292018-01-12 14:41:45 +01008276 if (!opt_vV)
8277 return;
8278
8279 to_free = NULL;
8280 if (!explanation) {
8281 char *path = getenv("PATH");
8282 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008283 if (!explanation)
8284 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008285 if (opt_vV != 'V')
8286 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8287 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008288 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008289 free(to_free);
8290 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008291 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008292}
8293#else
8294# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8295#endif
8296
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008297#if BB_MMU
8298#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8299 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8300#define pseudo_exec(nommu_save, command, argv_expanded) \
8301 pseudo_exec(command, argv_expanded)
8302#endif
8303
8304/* Called after [v]fork() in run_pipe, or from builtin_exec.
8305 * Never returns.
8306 * Don't exit() here. If you don't exec, use _exit instead.
8307 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008308 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008309 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008310static void pseudo_exec_argv(nommu_save_t *nommu_save,
8311 char **argv, int assignment_cnt,
8312 char **argv_expanded) NORETURN;
8313static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8314 char **argv, int assignment_cnt,
8315 char **argv_expanded)
8316{
Denys Vlasenko57000292018-01-12 14:41:45 +01008317 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008318 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008319 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008320 IF_HUSH_COMMAND(char opt_vV = 0;)
8321 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008322
8323 new_env = expand_assignments(argv, assignment_cnt);
8324 dump_cmd_in_x_mode(new_env);
8325
8326 if (!argv[assignment_cnt]) {
8327 /* Case when we are here: ... | var=val | ...
8328 * (note that we do not exit early, i.e., do not optimize out
8329 * expand_assignments(): think about ... | var=`sleep 1` | ...
8330 */
8331 free_strings(new_env);
8332 _exit(EXIT_SUCCESS);
8333 }
8334
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008335 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008336#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008337 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008338#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008339 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008340 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008341#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008342 set_vars_and_save_old(new_env);
8343 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008344
8345 if (argv_expanded) {
8346 argv = argv_expanded;
8347 } else {
8348 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8349#if !BB_MMU
8350 nommu_save->argv = argv;
8351#endif
8352 }
8353 dump_cmd_in_x_mode(argv);
8354
8355#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8356 if (strchr(argv[0], '/') != NULL)
8357 goto skip;
8358#endif
8359
Denys Vlasenko75481d32017-07-31 05:27:09 +02008360#if ENABLE_HUSH_FUNCTIONS
8361 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008362 funcp = find_function(argv[0]);
8363 if (funcp)
8364 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008365#endif
8366
Denys Vlasenko57000292018-01-12 14:41:45 +01008367#if ENABLE_HUSH_COMMAND
8368 /* "command BAR": run BAR without looking it up among functions
8369 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8370 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8371 */
8372 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8373 char *p;
8374
8375 argv++;
8376 p = *argv;
8377 if (p[0] != '-' || !p[1])
8378 continue; /* bash allows "command command command [-OPT] BAR" */
8379
8380 for (;;) {
8381 p++;
8382 switch (*p) {
8383 case '\0':
8384 argv++;
8385 p = *argv;
8386 if (p[0] != '-' || !p[1])
8387 goto after_opts;
8388 continue; /* next arg is also -opts, process it too */
8389 case 'v':
8390 case 'V':
8391 opt_vV = *p;
8392 continue;
8393 default:
8394 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8395 }
8396 }
8397 }
8398 after_opts:
8399# if ENABLE_HUSH_FUNCTIONS
8400 if (opt_vV && find_function(argv[0]))
8401 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8402# endif
8403#endif
8404
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008405 /* Check if the command matches any of the builtins.
8406 * Depending on context, this might be redundant. But it's
8407 * easier to waste a few CPU cycles than it is to figure out
8408 * if this is one of those cases.
8409 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008410 /* Why "BB_MMU ? :" difference in logic? -
8411 * On NOMMU, it is more expensive to re-execute shell
8412 * just in order to run echo or test builtin.
8413 * It's better to skip it here and run corresponding
8414 * non-builtin later. */
8415 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8416 if (x) {
8417 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8418 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008419 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008420
8421#if ENABLE_FEATURE_SH_STANDALONE
8422 /* Check if the command matches any busybox applets */
8423 {
8424 int a = find_applet_by_name(argv[0]);
8425 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008426 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008427# if BB_MMU /* see above why on NOMMU it is not allowed */
8428 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008429 /* Do not leak open fds from opened script files etc.
8430 * Testcase: interactive "ls -l /proc/self/fd"
8431 * should not show tty fd open.
8432 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008433 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008434//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008435//This casuses test failures in
8436//redir_children_should_not_see_saved_fd_2.tests
8437//redir_children_should_not_see_saved_fd_3.tests
8438//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008439 /* Without this, "rm -i FILE" can't be ^C'ed: */
8440 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008441 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008442 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008443 }
8444# endif
8445 /* Re-exec ourselves */
8446 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008447 /* Don't propagate SIG_IGN to the child */
8448 if (SPECIAL_JOBSTOP_SIGS != 0)
8449 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008450 execv(bb_busybox_exec_path, argv);
8451 /* If they called chroot or otherwise made the binary no longer
8452 * executable, fall through */
8453 }
8454 }
8455#endif
8456
8457#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8458 skip:
8459#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008460 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008461 execvp_or_die(argv);
8462}
8463
8464/* Called after [v]fork() in run_pipe
8465 */
8466static void pseudo_exec(nommu_save_t *nommu_save,
8467 struct command *command,
8468 char **argv_expanded) NORETURN;
8469static void pseudo_exec(nommu_save_t *nommu_save,
8470 struct command *command,
8471 char **argv_expanded)
8472{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008473#if ENABLE_HUSH_FUNCTIONS
8474 if (command->cmd_type == CMD_FUNCDEF) {
8475 /* Ignore funcdefs in pipes:
8476 * true | f() { cmd }
8477 */
8478 _exit(0);
8479 }
8480#endif
8481
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008482 if (command->argv) {
8483 pseudo_exec_argv(nommu_save, command->argv,
8484 command->assignment_cnt, argv_expanded);
8485 }
8486
8487 if (command->group) {
8488 /* Cases when we are here:
8489 * ( list )
8490 * { list } &
8491 * ... | ( list ) | ...
8492 * ... | { list } | ...
8493 */
8494#if BB_MMU
8495 int rcode;
8496 debug_printf_exec("pseudo_exec: run_list\n");
8497 reset_traps_to_defaults();
8498 rcode = run_list(command->group);
8499 /* OK to leak memory by not calling free_pipe_list,
8500 * since this process is about to exit */
8501 _exit(rcode);
8502#else
8503 re_execute_shell(&nommu_save->argv_from_re_execing,
8504 command->group_as_string,
8505 G.global_argv[0],
8506 G.global_argv + 1,
8507 NULL);
8508#endif
8509 }
8510
8511 /* Case when we are here: ... | >file */
8512 debug_printf_exec("pseudo_exec'ed null command\n");
8513 _exit(EXIT_SUCCESS);
8514}
8515
8516#if ENABLE_HUSH_JOB
8517static const char *get_cmdtext(struct pipe *pi)
8518{
8519 char **argv;
8520 char *p;
8521 int len;
8522
8523 /* This is subtle. ->cmdtext is created only on first backgrounding.
8524 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8525 * On subsequent bg argv is trashed, but we won't use it */
8526 if (pi->cmdtext)
8527 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008528
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008529 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008530 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008531 pi->cmdtext = xzalloc(1);
8532 return pi->cmdtext;
8533 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008534 len = 0;
8535 do {
8536 len += strlen(*argv) + 1;
8537 } while (*++argv);
8538 p = xmalloc(len);
8539 pi->cmdtext = p;
8540 argv = pi->cmds[0].argv;
8541 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008542 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008543 *p++ = ' ';
8544 } while (*++argv);
8545 p[-1] = '\0';
8546 return pi->cmdtext;
8547}
8548
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008549static void remove_job_from_table(struct pipe *pi)
8550{
8551 struct pipe *prev_pipe;
8552
8553 if (pi == G.job_list) {
8554 G.job_list = pi->next;
8555 } else {
8556 prev_pipe = G.job_list;
8557 while (prev_pipe->next != pi)
8558 prev_pipe = prev_pipe->next;
8559 prev_pipe->next = pi->next;
8560 }
8561 G.last_jobid = 0;
8562 if (G.job_list)
8563 G.last_jobid = G.job_list->jobid;
8564}
8565
8566static void delete_finished_job(struct pipe *pi)
8567{
8568 remove_job_from_table(pi);
8569 free_pipe(pi);
8570}
8571
8572static void clean_up_last_dead_job(void)
8573{
8574 if (G.job_list && !G.job_list->alive_cmds)
8575 delete_finished_job(G.job_list);
8576}
8577
Denys Vlasenko16096292017-07-10 10:00:28 +02008578static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008579{
8580 struct pipe *job, **jobp;
8581 int i;
8582
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008583 clean_up_last_dead_job();
8584
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008585 /* Find the end of the list, and find next job ID to use */
8586 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008587 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008588 while ((job = *jobp) != NULL) {
8589 if (job->jobid > i)
8590 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008591 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008592 }
8593 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008594
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008595 /* Create a new job struct at the end */
8596 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008597 job->next = NULL;
8598 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8599 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8600 for (i = 0; i < pi->num_cmds; i++) {
8601 job->cmds[i].pid = pi->cmds[i].pid;
8602 /* all other fields are not used and stay zero */
8603 }
8604 job->cmdtext = xstrdup(get_cmdtext(pi));
8605
8606 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008607 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008608 G.last_jobid = job->jobid;
8609}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008610#endif /* JOB */
8611
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008612static int job_exited_or_stopped(struct pipe *pi)
8613{
8614 int rcode, i;
8615
8616 if (pi->alive_cmds != pi->stopped_cmds)
8617 return -1;
8618
8619 /* All processes in fg pipe have exited or stopped */
8620 rcode = 0;
8621 i = pi->num_cmds;
8622 while (--i >= 0) {
8623 rcode = pi->cmds[i].cmd_exitcode;
8624 /* usually last process gives overall exitstatus,
8625 * but with "set -o pipefail", last *failed* process does */
8626 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8627 break;
8628 }
8629 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8630 return rcode;
8631}
8632
Denys Vlasenko7e675362016-10-28 21:57:31 +02008633static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008634{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008635#if ENABLE_HUSH_JOB
8636 struct pipe *pi;
8637#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008638 int i, dead;
8639
8640 dead = WIFEXITED(status) || WIFSIGNALED(status);
8641
8642#if DEBUG_JOBS
8643 if (WIFSTOPPED(status))
8644 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8645 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8646 if (WIFSIGNALED(status))
8647 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8648 childpid, WTERMSIG(status), WEXITSTATUS(status));
8649 if (WIFEXITED(status))
8650 debug_printf_jobs("pid %d exited, exitcode %d\n",
8651 childpid, WEXITSTATUS(status));
8652#endif
8653 /* Were we asked to wait for a fg pipe? */
8654 if (fg_pipe) {
8655 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008656
Denys Vlasenko7e675362016-10-28 21:57:31 +02008657 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008658 int rcode;
8659
Denys Vlasenko7e675362016-10-28 21:57:31 +02008660 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8661 if (fg_pipe->cmds[i].pid != childpid)
8662 continue;
8663 if (dead) {
8664 int ex;
8665 fg_pipe->cmds[i].pid = 0;
8666 fg_pipe->alive_cmds--;
8667 ex = WEXITSTATUS(status);
8668 /* bash prints killer signal's name for *last*
8669 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8670 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8671 */
8672 if (WIFSIGNALED(status)) {
8673 int sig = WTERMSIG(status);
8674 if (i == fg_pipe->num_cmds-1)
8675 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8676 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8677 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8678 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8679 * Maybe we need to use sig | 128? */
8680 ex = sig + 128;
8681 }
8682 fg_pipe->cmds[i].cmd_exitcode = ex;
8683 } else {
8684 fg_pipe->stopped_cmds++;
8685 }
8686 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8687 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008688 rcode = job_exited_or_stopped(fg_pipe);
8689 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008690/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8691 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8692 * and "killall -STOP cat" */
8693 if (G_interactive_fd) {
8694#if ENABLE_HUSH_JOB
8695 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008696 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008697#endif
8698 return rcode;
8699 }
8700 if (fg_pipe->alive_cmds == 0)
8701 return rcode;
8702 }
8703 /* There are still running processes in the fg_pipe */
8704 return -1;
8705 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008706 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008707 }
8708
8709#if ENABLE_HUSH_JOB
8710 /* We were asked to wait for bg or orphaned children */
8711 /* No need to remember exitcode in this case */
8712 for (pi = G.job_list; pi; pi = pi->next) {
8713 for (i = 0; i < pi->num_cmds; i++) {
8714 if (pi->cmds[i].pid == childpid)
8715 goto found_pi_and_prognum;
8716 }
8717 }
8718 /* Happens when shell is used as init process (init=/bin/sh) */
8719 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8720 return -1; /* this wasn't a process from fg_pipe */
8721
8722 found_pi_and_prognum:
8723 if (dead) {
8724 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008725 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008726 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008727 rcode = 128 + WTERMSIG(status);
8728 pi->cmds[i].cmd_exitcode = rcode;
8729 if (G.last_bg_pid == pi->cmds[i].pid)
8730 G.last_bg_pid_exitcode = rcode;
8731 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008732 pi->alive_cmds--;
8733 if (!pi->alive_cmds) {
Denys Vlasenko259747c2019-11-28 10:28:14 +01008734# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008735 G.dead_job_exitcode = job_exited_or_stopped(pi);
Denys Vlasenko259747c2019-11-28 10:28:14 +01008736# endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008737 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008738 printf(JOB_STATUS_FORMAT, pi->jobid,
8739 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008740 delete_finished_job(pi);
8741 } else {
8742/*
8743 * bash deletes finished jobs from job table only in interactive mode,
8744 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8745 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8746 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8747 * We only retain one "dead" job, if it's the single job on the list.
8748 * This covers most of real-world scenarios where this is useful.
8749 */
8750 if (pi != G.job_list)
8751 delete_finished_job(pi);
8752 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008753 }
8754 } else {
8755 /* child stopped */
8756 pi->stopped_cmds++;
8757 }
8758#endif
8759 return -1; /* this wasn't a process from fg_pipe */
8760}
8761
8762/* Check to see if any processes have exited -- if they have,
8763 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008764 *
8765 * If non-NULL fg_pipe: wait for its completion or stop.
8766 * Return its exitcode or zero if stopped.
8767 *
8768 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8769 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8770 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8771 * or 0 if no children changed status.
8772 *
8773 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8774 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8775 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008776 */
8777static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8778{
8779 int attributes;
8780 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008781 int rcode = 0;
8782
8783 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8784
8785 attributes = WUNTRACED;
8786 if (fg_pipe == NULL)
8787 attributes |= WNOHANG;
8788
8789 errno = 0;
8790#if ENABLE_HUSH_FAST
8791 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8792//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8793//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8794 /* There was neither fork nor SIGCHLD since last waitpid */
8795 /* Avoid doing waitpid syscall if possible */
8796 if (!G.we_have_children) {
8797 errno = ECHILD;
8798 return -1;
8799 }
8800 if (fg_pipe == NULL) { /* is WNOHANG set? */
8801 /* We have children, but they did not exit
8802 * or stop yet (we saw no SIGCHLD) */
8803 return 0;
8804 }
8805 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8806 }
8807#endif
8808
8809/* Do we do this right?
8810 * bash-3.00# sleep 20 | false
8811 * <ctrl-Z pressed>
8812 * [3]+ Stopped sleep 20 | false
8813 * bash-3.00# echo $?
8814 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8815 * [hush 1.14.0: yes we do it right]
8816 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008817 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008818 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008819#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008820 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008821 i = G.count_SIGCHLD;
8822#endif
8823 childpid = waitpid(-1, &status, attributes);
8824 if (childpid <= 0) {
8825 if (childpid && errno != ECHILD)
James Byrne69374872019-07-02 11:35:03 +02008826 bb_simple_perror_msg("waitpid");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008827#if ENABLE_HUSH_FAST
8828 else { /* Until next SIGCHLD, waitpid's are useless */
8829 G.we_have_children = (childpid == 0);
8830 G.handled_SIGCHLD = i;
8831//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8832 }
8833#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008834 /* ECHILD (no children), or 0 (no change in children status) */
8835 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008836 break;
8837 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008838 rcode = process_wait_result(fg_pipe, childpid, status);
8839 if (rcode >= 0) {
8840 /* fg_pipe exited or stopped */
8841 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008842 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008843 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008844 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008845 rcode = WEXITSTATUS(status);
8846 if (WIFSIGNALED(status))
8847 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008848 if (WIFSTOPPED(status))
8849 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8850 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008851 rcode++;
8852 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008853 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008854#if ENABLE_HUSH_BASH_COMPAT
8855 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8856 && G.dead_job_exitcode >= 0 /* some job did finish */
8857 ) {
8858 debug_printf_exec("waitfor_pid:-1\n");
8859 rcode = G.dead_job_exitcode + 1;
8860 break;
8861 }
8862#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008863 /* This wasn't one of our processes, or */
8864 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008865 } /* while (waitpid succeeds)... */
8866
8867 return rcode;
8868}
8869
8870#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008871static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008872{
8873 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008874 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008875 if (G_saved_tty_pgrp) {
8876 /* Job finished, move the shell to the foreground */
8877 p = getpgrp(); /* our process group id */
8878 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8879 tcsetpgrp(G_interactive_fd, p);
8880 }
8881 return rcode;
8882}
8883#endif
8884
8885/* Start all the jobs, but don't wait for anything to finish.
8886 * See checkjobs().
8887 *
8888 * Return code is normally -1, when the caller has to wait for children
8889 * to finish to determine the exit status of the pipe. If the pipe
8890 * is a simple builtin command, however, the action is done by the
8891 * time run_pipe returns, and the exit code is provided as the
8892 * return value.
8893 *
8894 * Returns -1 only if started some children. IOW: we have to
8895 * mask out retvals of builtins etc with 0xff!
8896 *
8897 * The only case when we do not need to [v]fork is when the pipe
8898 * is single, non-backgrounded, non-subshell command. Examples:
8899 * cmd ; ... { list } ; ...
8900 * cmd && ... { list } && ...
8901 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008902 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008903 * or (if SH_STANDALONE) an applet, and we can run the { list }
8904 * with run_list. If it isn't one of these, we fork and exec cmd.
8905 *
8906 * Cases when we must fork:
8907 * non-single: cmd | cmd
8908 * backgrounded: cmd & { list } &
8909 * subshell: ( list ) [&]
8910 */
8911#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008912#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8913 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008914#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008915static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008916 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008917 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008918 char **argv_expanded)
8919{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008920 /* Assignments occur before redirects. Try:
8921 * a=`sleep 1` sleep 2 3>/qwe/rty
8922 */
8923
8924 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8925 dump_cmd_in_x_mode(new_env);
8926 dump_cmd_in_x_mode(argv_expanded);
8927 /* this takes ownership of new_env[i] elements, and frees new_env: */
8928 set_vars_and_save_old(new_env);
8929
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008930 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008931}
8932static NOINLINE int run_pipe(struct pipe *pi)
8933{
8934 static const char *const null_ptr = NULL;
8935
8936 int cmd_no;
8937 int next_infd;
8938 struct command *command;
8939 char **argv_expanded;
8940 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008941 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008942 int rcode;
8943
8944 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8945 debug_enter();
8946
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008947 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8948 * Result should be 3 lines: q w e, qwe, q w e
8949 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008950 if (G.ifs_whitespace != G.ifs)
8951 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008952 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008953 if (G.ifs) {
8954 char *p;
8955 G.ifs_whitespace = (char*)G.ifs;
8956 p = skip_whitespace(G.ifs);
8957 if (*p) {
8958 /* Not all $IFS is whitespace */
8959 char *d;
8960 int len = p - G.ifs;
8961 p = skip_non_whitespace(p);
8962 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8963 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8964 while (*p) {
8965 if (isspace(*p))
8966 *d++ = *p;
8967 p++;
8968 }
8969 *d = '\0';
8970 }
8971 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008972 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008973 G.ifs_whitespace = (char*)G.ifs;
8974 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008975
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008976 IF_HUSH_JOB(pi->pgrp = -1;)
8977 pi->stopped_cmds = 0;
8978 command = &pi->cmds[0];
8979 argv_expanded = NULL;
8980
8981 if (pi->num_cmds != 1
8982 || pi->followup == PIPE_BG
8983 || command->cmd_type == CMD_SUBSHELL
8984 ) {
8985 goto must_fork;
8986 }
8987
8988 pi->alive_cmds = 1;
8989
8990 debug_printf_exec(": group:%p argv:'%s'\n",
8991 command->group, command->argv ? command->argv[0] : "NONE");
8992
8993 if (command->group) {
8994#if ENABLE_HUSH_FUNCTIONS
8995 if (command->cmd_type == CMD_FUNCDEF) {
8996 /* "executing" func () { list } */
8997 struct function *funcp;
8998
8999 funcp = new_function(command->argv[0]);
9000 /* funcp->name is already set to argv[0] */
9001 funcp->body = command->group;
9002# if !BB_MMU
9003 funcp->body_as_string = command->group_as_string;
9004 command->group_as_string = NULL;
9005# endif
9006 command->group = NULL;
9007 command->argv[0] = NULL;
9008 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
9009 funcp->parent_cmd = command;
9010 command->child_func = funcp;
9011
9012 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
9013 debug_leave();
9014 return EXIT_SUCCESS;
9015 }
9016#endif
9017 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009018 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009019 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009020 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009021 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02009022//FIXME: we need to pass squirrel down into run_list()
9023//for SH_STANDALONE case, or else this construct:
9024// { find /proc/self/fd; true; } >FILE; cmd2
9025//has no way of closing saved fd#1 for "find",
9026//and in SH_STANDALONE mode, "find" is not execed,
9027//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009028 rcode = run_list(command->group) & 0xff;
9029 }
9030 restore_redirects(squirrel);
9031 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9032 debug_leave();
9033 debug_printf_exec("run_pipe: return %d\n", rcode);
9034 return rcode;
9035 }
9036
9037 argv = command->argv ? command->argv : (char **) &null_ptr;
9038 {
9039 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009040 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9041 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009042 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009043 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009044
Denys Vlasenko5807e182018-02-08 19:19:04 +01009045#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009046 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009047#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009048
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009049 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009050 /* Assignments, but no command.
9051 * Ensure redirects take effect (that is, create files).
9052 * Try "a=t >file"
9053 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009054 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009055 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009056 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009057 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009058 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009059
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009060 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009061 i = 0;
9062 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009063 char *p = expand_string_to_string(argv[i],
9064 EXP_FLAG_ESC_GLOB_CHARS,
9065 /*unbackslash:*/ 1
9066 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009067#if ENABLE_HUSH_MODE_X
9068 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009069 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009070 if (i == 0)
9071 x_mode_prefix();
9072 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009073 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009074 if (*eq) eq++;
9075 x_mode_addblock(p, (eq - p));
9076 x_mode_print_optionally_squoted(eq);
9077 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009078 }
9079#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009080 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009081 if (set_local_var(p, /*flag:*/ 0)) {
9082 /* assignment to readonly var / putenv error? */
9083 rcode = 1;
9084 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009085 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009086 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009087 /* Redirect error sets $? to 1. Otherwise,
9088 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009089 * Else, clear $?:
9090 * false; q=`exit 2`; echo $? - should print 2
9091 * false; x=1; echo $? - should print 0
9092 * Because of the 2nd case, we can't just use G.last_exitcode.
9093 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009094 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009095 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009096 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9097 debug_leave();
9098 debug_printf_exec("run_pipe: return %d\n", rcode);
9099 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009100 }
9101
9102 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02009103#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009104 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009105 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009106 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009107#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009108 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009109
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009110 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009111 if (!argv_expanded[0]) {
9112 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009113 /* `false` still has to set exitcode 1 */
9114 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009115 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009116 }
9117
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009118 old_vars = NULL;
9119 sv_shadowed = G.shadowed_vars_pp;
9120
Denys Vlasenko75481d32017-07-31 05:27:09 +02009121 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009122 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9123 IF_HUSH_FUNCTIONS(x = NULL;)
9124 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009125 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009126 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009127 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9128 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009129 /*
9130 * Variable assignments are executed, but then "forgotten":
9131 * a=`sleep 1;echo A` exec 3>&-; echo $a
9132 * sleeps, but prints nothing.
9133 */
9134 enter_var_nest_level();
9135 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009136 rcode = redirect_and_varexp_helper(command,
9137 /*squirrel:*/ ERR_PTR,
9138 argv_expanded
9139 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009140 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009141 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009142
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009143 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009144 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009145
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009146 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009147 * a=b true; env | grep ^a=
9148 */
9149 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009150 /* Collect all variables "shadowed" by helper
9151 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9152 * into old_vars list:
9153 */
9154 G.shadowed_vars_pp = &old_vars;
9155 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009156 if (rcode == 0) {
9157 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009158 /* Do not collect *to old_vars list* vars shadowed
9159 * by e.g. "local VAR" builtin (collect them
9160 * in the previously nested list instead):
9161 * don't want them to be restored immediately
9162 * after "local" completes.
9163 */
9164 G.shadowed_vars_pp = sv_shadowed;
9165
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009166 debug_printf_exec(": builtin '%s' '%s'...\n",
9167 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009168 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009169 rcode = x->b_function(argv_expanded) & 0xff;
9170 fflush_all();
9171 }
9172#if ENABLE_HUSH_FUNCTIONS
9173 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009174 debug_printf_exec(": function '%s' '%s'...\n",
9175 funcp->name, argv_expanded[1]);
9176 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009177 /*
9178 * But do collect *to old_vars list* vars shadowed
9179 * within function execution. To that end, restore
9180 * this pointer _after_ function run:
9181 */
9182 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009183 }
9184#endif
9185 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009186 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009187 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009188 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009189 if (n < 0 || !APPLET_IS_NOFORK(n))
9190 goto must_fork;
9191
9192 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009193 /* Collect all variables "shadowed" by helper into old_vars list */
9194 G.shadowed_vars_pp = &old_vars;
9195 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9196 G.shadowed_vars_pp = sv_shadowed;
9197
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009198 if (rcode == 0) {
9199 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9200 argv_expanded[0], argv_expanded[1]);
9201 /*
9202 * Note: signals (^C) can't interrupt here.
9203 * We remember them and they will be acted upon
9204 * after applet returns.
9205 * This makes applets which can run for a long time
9206 * and/or wait for user input ineligible for NOFORK:
9207 * for example, "yes" or "rm" (rm -i waits for input).
9208 */
9209 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009210 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009211 } else
9212 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009213
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009214 restore_redirects(squirrel);
9215 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009216 leave_var_nest_level();
9217 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009218
9219 /*
9220 * Try "usleep 99999999" + ^C + "echo $?"
9221 * with FEATURE_SH_NOFORK=y.
9222 */
9223 if (!funcp) {
9224 /* It was builtin or nofork.
9225 * if this would be a real fork/execed program,
9226 * it should have died if a fatal sig was received.
9227 * But OTOH, there was no separate process,
9228 * the sig was sent to _shell_, not to non-existing
9229 * child.
9230 * Let's just handle ^C only, this one is obvious:
9231 * we aren't ok with exitcode 0 when ^C was pressed
9232 * during builtin/nofork.
9233 */
9234 if (sigismember(&G.pending_set, SIGINT))
9235 rcode = 128 + SIGINT;
9236 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009237 free(argv_expanded);
9238 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9239 debug_leave();
9240 debug_printf_exec("run_pipe return %d\n", rcode);
9241 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009242 }
9243
9244 must_fork:
9245 /* NB: argv_expanded may already be created, and that
9246 * might include `cmd` runs! Do not rerun it! We *must*
9247 * use argv_expanded if it's non-NULL */
9248
9249 /* Going to fork a child per each pipe member */
9250 pi->alive_cmds = 0;
9251 next_infd = 0;
9252
9253 cmd_no = 0;
9254 while (cmd_no < pi->num_cmds) {
9255 struct fd_pair pipefds;
9256#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009257 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009258 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009259 nommu_save.old_vars = NULL;
9260 nommu_save.argv = NULL;
9261 nommu_save.argv_from_re_execing = NULL;
9262#endif
9263 command = &pi->cmds[cmd_no];
9264 cmd_no++;
9265 if (command->argv) {
9266 debug_printf_exec(": pipe member '%s' '%s'...\n",
9267 command->argv[0], command->argv[1]);
9268 } else {
9269 debug_printf_exec(": pipe member with no argv\n");
9270 }
9271
9272 /* pipes are inserted between pairs of commands */
9273 pipefds.rd = 0;
9274 pipefds.wr = 1;
9275 if (cmd_no < pi->num_cmds)
9276 xpiped_pair(pipefds);
9277
Denys Vlasenko5807e182018-02-08 19:19:04 +01009278#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009279 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009280#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009281
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009282 command->pid = BB_MMU ? fork() : vfork();
9283 if (!command->pid) { /* child */
9284#if ENABLE_HUSH_JOB
9285 disable_restore_tty_pgrp_on_exit();
9286 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9287
9288 /* Every child adds itself to new process group
9289 * with pgid == pid_of_first_child_in_pipe */
9290 if (G.run_list_level == 1 && G_interactive_fd) {
9291 pid_t pgrp;
9292 pgrp = pi->pgrp;
9293 if (pgrp < 0) /* true for 1st process only */
9294 pgrp = getpid();
9295 if (setpgid(0, pgrp) == 0
9296 && pi->followup != PIPE_BG
9297 && G_saved_tty_pgrp /* we have ctty */
9298 ) {
9299 /* We do it in *every* child, not just first,
9300 * to avoid races */
9301 tcsetpgrp(G_interactive_fd, pgrp);
9302 }
9303 }
9304#endif
9305 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9306 /* 1st cmd in backgrounded pipe
9307 * should have its stdin /dev/null'ed */
9308 close(0);
9309 if (open(bb_dev_null, O_RDONLY))
9310 xopen("/", O_RDONLY);
9311 } else {
9312 xmove_fd(next_infd, 0);
9313 }
9314 xmove_fd(pipefds.wr, 1);
9315 if (pipefds.rd > 1)
9316 close(pipefds.rd);
9317 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009318 * and the pipe fd (fd#1) is available for dup'ing:
9319 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9320 * of cmd1 goes into pipe.
9321 */
9322 if (setup_redirects(command, NULL)) {
9323 /* Happens when redir file can't be opened:
9324 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9325 * FOO
9326 * hush: can't open '/qwe/rty': No such file or directory
9327 * BAZ
9328 * (echo BAR is not executed, it hits _exit(1) below)
9329 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009330 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009331 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009332
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009333 /* Stores to nommu_save list of env vars putenv'ed
9334 * (NOMMU, on MMU we don't need that) */
9335 /* cast away volatility... */
9336 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9337 /* pseudo_exec() does not return */
9338 }
9339
9340 /* parent or error */
9341#if ENABLE_HUSH_FAST
9342 G.count_SIGCHLD++;
9343//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9344#endif
9345 enable_restore_tty_pgrp_on_exit();
9346#if !BB_MMU
9347 /* Clean up after vforked child */
9348 free(nommu_save.argv);
9349 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009350 G.var_nest_level = sv_var_nest_level;
9351 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009352 add_vars(nommu_save.old_vars);
9353#endif
9354 free(argv_expanded);
9355 argv_expanded = NULL;
9356 if (command->pid < 0) { /* [v]fork failed */
9357 /* Clearly indicate, was it fork or vfork */
James Byrne69374872019-07-02 11:35:03 +02009358 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009359 } else {
9360 pi->alive_cmds++;
9361#if ENABLE_HUSH_JOB
9362 /* Second and next children need to know pid of first one */
9363 if (pi->pgrp < 0)
9364 pi->pgrp = command->pid;
9365#endif
9366 }
9367
9368 if (cmd_no > 1)
9369 close(next_infd);
9370 if (cmd_no < pi->num_cmds)
9371 close(pipefds.wr);
9372 /* Pass read (output) pipe end to next iteration */
9373 next_infd = pipefds.rd;
9374 }
9375
9376 if (!pi->alive_cmds) {
9377 debug_leave();
9378 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9379 return 1;
9380 }
9381
9382 debug_leave();
9383 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9384 return -1;
9385}
9386
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009387/* NB: called by pseudo_exec, and therefore must not modify any
9388 * global data until exec/_exit (we can be a child after vfork!) */
9389static int run_list(struct pipe *pi)
9390{
9391#if ENABLE_HUSH_CASE
9392 char *case_word = NULL;
9393#endif
9394#if ENABLE_HUSH_LOOPS
9395 struct pipe *loop_top = NULL;
9396 char **for_lcur = NULL;
9397 char **for_list = NULL;
9398#endif
9399 smallint last_followup;
9400 smalluint rcode;
9401#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9402 smalluint cond_code = 0;
9403#else
9404 enum { cond_code = 0 };
9405#endif
9406#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009407 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009408 smallint last_rword; /* ditto */
9409#endif
9410
9411 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9412 debug_enter();
9413
9414#if ENABLE_HUSH_LOOPS
9415 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009416 {
9417 struct pipe *cpipe;
9418 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9419 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9420 continue;
9421 /* current word is FOR or IN (BOLD in comments below) */
9422 if (cpipe->next == NULL) {
9423 syntax_error("malformed for");
9424 debug_leave();
9425 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9426 return 1;
9427 }
9428 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9429 if (cpipe->next->res_word == RES_DO)
9430 continue;
9431 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9432 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9433 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9434 ) {
9435 syntax_error("malformed for");
9436 debug_leave();
9437 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9438 return 1;
9439 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009440 }
9441 }
9442#endif
9443
9444 /* Past this point, all code paths should jump to ret: label
9445 * in order to return, no direct "return" statements please.
9446 * This helps to ensure that no memory is leaked. */
9447
9448#if ENABLE_HUSH_JOB
9449 G.run_list_level++;
9450#endif
9451
9452#if HAS_KEYWORDS
9453 rword = RES_NONE;
9454 last_rword = RES_XXXX;
9455#endif
9456 last_followup = PIPE_SEQ;
9457 rcode = G.last_exitcode;
9458
9459 /* Go through list of pipes, (maybe) executing them. */
9460 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009461 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009462 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009463
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009464 if (G.flag_SIGINT)
9465 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009466 if (G_flag_return_in_progress == 1)
9467 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009468
9469 IF_HAS_KEYWORDS(rword = pi->res_word;)
9470 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9471 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009472
9473 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009474 if (
9475#if ENABLE_HUSH_IF
9476 rword == RES_IF || rword == RES_ELIF ||
9477#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009478 pi->followup != PIPE_SEQ
9479 ) {
9480 G.errexit_depth++;
9481 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009482#if ENABLE_HUSH_LOOPS
9483 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9484 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9485 ) {
9486 /* start of a loop: remember where loop starts */
9487 loop_top = pi;
9488 G.depth_of_loop++;
9489 }
9490#endif
9491 /* Still in the same "if...", "then..." or "do..." branch? */
9492 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9493 if ((rcode == 0 && last_followup == PIPE_OR)
9494 || (rcode != 0 && last_followup == PIPE_AND)
9495 ) {
9496 /* It is "<true> || CMD" or "<false> && CMD"
9497 * and we should not execute CMD */
9498 debug_printf_exec("skipped cmd because of || or &&\n");
9499 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009500 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009501 }
9502 }
9503 last_followup = pi->followup;
9504 IF_HAS_KEYWORDS(last_rword = rword;)
9505#if ENABLE_HUSH_IF
9506 if (cond_code) {
9507 if (rword == RES_THEN) {
9508 /* if false; then ... fi has exitcode 0! */
9509 G.last_exitcode = rcode = EXIT_SUCCESS;
9510 /* "if <false> THEN cmd": skip cmd */
9511 continue;
9512 }
9513 } else {
9514 if (rword == RES_ELSE || rword == RES_ELIF) {
9515 /* "if <true> then ... ELSE/ELIF cmd":
9516 * skip cmd and all following ones */
9517 break;
9518 }
9519 }
9520#endif
9521#if ENABLE_HUSH_LOOPS
9522 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9523 if (!for_lcur) {
9524 /* first loop through for */
9525
9526 static const char encoded_dollar_at[] ALIGN1 = {
9527 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9528 }; /* encoded representation of "$@" */
9529 static const char *const encoded_dollar_at_argv[] = {
9530 encoded_dollar_at, NULL
9531 }; /* argv list with one element: "$@" */
9532 char **vals;
9533
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009534 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009535 vals = (char**)encoded_dollar_at_argv;
9536 if (pi->next->res_word == RES_IN) {
9537 /* if no variable values after "in" we skip "for" */
9538 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009539 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9540 break;
9541 }
9542 vals = pi->next->cmds[0].argv;
9543 } /* else: "for var; do..." -> assume "$@" list */
9544 /* create list of variable values */
9545 debug_print_strings("for_list made from", vals);
9546 for_list = expand_strvec_to_strvec(vals);
9547 for_lcur = for_list;
9548 debug_print_strings("for_list", for_list);
9549 }
9550 if (!*for_lcur) {
9551 /* "for" loop is over, clean up */
9552 free(for_list);
9553 for_list = NULL;
9554 for_lcur = NULL;
9555 break;
9556 }
9557 /* Insert next value from for_lcur */
9558 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009559 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009560 continue;
9561 }
9562 if (rword == RES_IN) {
9563 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9564 }
9565 if (rword == RES_DONE) {
9566 continue; /* "done" has no cmds too */
9567 }
9568#endif
9569#if ENABLE_HUSH_CASE
9570 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009571 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009572 case_word = expand_string_to_string(pi->cmds->argv[0],
9573 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009574 debug_printf_exec("CASE word1:'%s'\n", case_word);
9575 //unbackslash(case_word);
9576 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009577 continue;
9578 }
9579 if (rword == RES_MATCH) {
9580 char **argv;
9581
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009582 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009583 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9584 break;
9585 /* all prev words didn't match, does this one match? */
9586 argv = pi->cmds->argv;
9587 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009588 char *pattern;
9589 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9590 pattern = expand_string_to_string(*argv,
9591 EXP_FLAG_ESC_GLOB_CHARS,
9592 /*unbackslash:*/ 0
9593 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009594 /* TODO: which FNM_xxx flags to use? */
9595 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009596 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9597 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009598 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009599 if (cond_code == 0) {
9600 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009601 free(case_word);
9602 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009603 break;
9604 }
9605 argv++;
9606 }
9607 continue;
9608 }
9609 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009610 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009611 if (cond_code != 0)
9612 continue; /* not matched yet, skip this pipe */
9613 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009614 if (rword == RES_ESAC) {
9615 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9616 if (case_word) {
9617 /* "case" did not match anything: still set $? (to 0) */
9618 G.last_exitcode = rcode = EXIT_SUCCESS;
9619 }
9620 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009621#endif
9622 /* Just pressing <enter> in shell should check for jobs.
9623 * OTOH, in non-interactive shell this is useless
9624 * and only leads to extra job checks */
9625 if (pi->num_cmds == 0) {
9626 if (G_interactive_fd)
9627 goto check_jobs_and_continue;
9628 continue;
9629 }
9630
9631 /* After analyzing all keywords and conditions, we decided
9632 * to execute this pipe. NB: have to do checkjobs(NULL)
9633 * after run_pipe to collect any background children,
9634 * even if list execution is to be stopped. */
9635 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009636#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009637 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009638#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009639 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9640 if (r != -1) {
9641 /* We ran a builtin, function, or group.
9642 * rcode is already known
9643 * and we don't need to wait for anything. */
9644 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9645 G.last_exitcode = rcode;
9646 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009647#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9648 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9649#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009650#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009651 /* Was it "break" or "continue"? */
9652 if (G.flag_break_continue) {
9653 smallint fbc = G.flag_break_continue;
9654 /* We might fall into outer *loop*,
9655 * don't want to break it too */
9656 if (loop_top) {
9657 G.depth_break_continue--;
9658 if (G.depth_break_continue == 0)
9659 G.flag_break_continue = 0;
9660 /* else: e.g. "continue 2" should *break* once, *then* continue */
9661 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9662 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009663 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009664 break;
9665 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009666 /* "continue": simulate end of loop */
9667 rword = RES_DONE;
9668 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009669 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009670#endif
9671 if (G_flag_return_in_progress == 1) {
9672 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9673 break;
9674 }
9675 } else if (pi->followup == PIPE_BG) {
9676 /* What does bash do with attempts to background builtins? */
9677 /* even bash 3.2 doesn't do that well with nested bg:
9678 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9679 * I'm NOT treating inner &'s as jobs */
9680#if ENABLE_HUSH_JOB
9681 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009682 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009683#endif
9684 /* Last command's pid goes to $! */
9685 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009686 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009687 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009688/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009689 rcode = EXIT_SUCCESS;
9690 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009691 } else {
9692#if ENABLE_HUSH_JOB
9693 if (G.run_list_level == 1 && G_interactive_fd) {
9694 /* Waits for completion, then fg's main shell */
9695 rcode = checkjobs_and_fg_shell(pi);
9696 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009697 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009698 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009699#endif
9700 /* This one just waits for completion */
9701 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9702 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9703 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009704 G.last_exitcode = rcode;
9705 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009706#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9707 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9708#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009709 }
9710
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009711 /* Handle "set -e" */
9712 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9713 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9714 if (G.errexit_depth == 0)
9715 hush_exit(rcode);
9716 }
9717 G.errexit_depth = sv_errexit_depth;
9718
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009719 /* Analyze how result affects subsequent commands */
9720#if ENABLE_HUSH_IF
9721 if (rword == RES_IF || rword == RES_ELIF)
9722 cond_code = rcode;
9723#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009724 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009725 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009726 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009727#if ENABLE_HUSH_LOOPS
9728 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009729 if (pi->next
9730 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009731 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009732 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009733 if (rword == RES_WHILE) {
9734 if (rcode) {
9735 /* "while false; do...done" - exitcode 0 */
9736 G.last_exitcode = rcode = EXIT_SUCCESS;
9737 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009738 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009739 }
9740 }
9741 if (rword == RES_UNTIL) {
9742 if (!rcode) {
9743 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009744 break;
9745 }
9746 }
9747 }
9748#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009749 } /* for (pi) */
9750
9751#if ENABLE_HUSH_JOB
9752 G.run_list_level--;
9753#endif
9754#if ENABLE_HUSH_LOOPS
9755 if (loop_top)
9756 G.depth_of_loop--;
9757 free(for_list);
9758#endif
9759#if ENABLE_HUSH_CASE
9760 free(case_word);
9761#endif
9762 debug_leave();
9763 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9764 return rcode;
9765}
9766
9767/* Select which version we will use */
9768static int run_and_free_list(struct pipe *pi)
9769{
9770 int rcode = 0;
9771 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009772 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009773 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9774 rcode = run_list(pi);
9775 }
9776 /* free_pipe_list has the side effect of clearing memory.
9777 * In the long run that function can be merged with run_list,
9778 * but doing that now would hobble the debugging effort. */
9779 free_pipe_list(pi);
9780 debug_printf_exec("run_and_free_list return %d\n", rcode);
9781 return rcode;
9782}
9783
9784
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009785static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009786{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009787 sighandler_t old_handler;
9788 unsigned sig = 0;
9789 while ((mask >>= 1) != 0) {
9790 sig++;
9791 if (!(mask & 1))
9792 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009793 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009794 /* POSIX allows shell to re-enable SIGCHLD
9795 * even if it was SIG_IGN on entry.
9796 * Therefore we skip IGN check for it:
9797 */
9798 if (sig == SIGCHLD)
9799 continue;
Denys Vlasenko23bc5622020-02-18 16:46:01 +01009800 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
9801 * Try:
9802 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
9803 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009804 */
Denys Vlasenko23bc5622020-02-18 16:46:01 +01009805 if (sig == SIGHUP && G_interactive_fd)
9806 continue;
9807 /* Unless one of the above signals, is it SIG_IGN? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009808 if (old_handler == SIG_IGN) {
9809 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009810 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009811#if ENABLE_HUSH_TRAP
9812 if (!G_traps)
9813 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9814 free(G_traps[sig]);
9815 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9816#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009817 }
9818 }
9819}
9820
9821/* Called a few times only (or even once if "sh -c") */
9822static void install_special_sighandlers(void)
9823{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009824 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009825
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009826 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009827 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009828 if (G_interactive_fd) {
9829 mask |= SPECIAL_INTERACTIVE_SIGS;
9830 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009831 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009832 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009833 /* Careful, do not re-install handlers we already installed */
9834 if (G.special_sig_mask != mask) {
9835 unsigned diff = mask & ~G.special_sig_mask;
9836 G.special_sig_mask = mask;
9837 install_sighandlers(diff);
9838 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009839}
9840
9841#if ENABLE_HUSH_JOB
9842/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009843/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009844static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009845{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009846 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009847
9848 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009849 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009850 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9851 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009852 + (1 << SIGBUS ) * HUSH_DEBUG
9853 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009854 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009855 + (1 << SIGABRT)
9856 /* bash 3.2 seems to handle these just like 'fatal' ones */
9857 + (1 << SIGPIPE)
9858 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009859 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009860 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009861 * we never want to restore pgrp on exit, and this fn is not called
9862 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009863 /*+ (1 << SIGHUP )*/
9864 /*+ (1 << SIGTERM)*/
9865 /*+ (1 << SIGINT )*/
9866 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009867 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009868
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009869 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009870}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009871#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009872
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009873static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009874{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009875 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009876 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009877 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009878 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009879 break;
9880 case 'x':
9881 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009882 IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009883 break;
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009884 case 'e':
9885 G.o_opt[OPT_O_ERREXIT] = state;
9886 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009887 case 'o':
9888 if (!o_opt) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009889 /* "set -o" or "set +o" without parameter.
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009890 * in bash, set -o produces this output:
9891 * pipefail off
9892 * and set +o:
9893 * set +o pipefail
9894 * We always use the second form.
9895 */
9896 const char *p = o_opt_strings;
9897 idx = 0;
9898 while (*p) {
9899 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9900 idx++;
9901 p += strlen(p) + 1;
9902 }
9903 break;
9904 }
9905 idx = index_in_strings(o_opt_strings, o_opt);
9906 if (idx >= 0) {
9907 G.o_opt[idx] = state;
9908 break;
9909 }
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009910 /* fall through to error */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009911 default:
9912 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009913 }
9914 return EXIT_SUCCESS;
9915}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009916
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009917int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009918int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009919{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009920 enum {
9921 OPT_login = (1 << 0),
9922 };
9923 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009924 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009925 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009926 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009927 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009928
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009929 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009930 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009931 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01009932#if ENABLE_HUSH_TRAP
9933# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009934 G.return_exitcode = -1;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01009935# endif
9936 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009937#endif
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009938
Denys Vlasenko10c01312011-05-11 11:49:21 +02009939#if ENABLE_HUSH_FAST
9940 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9941#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009942#if !BB_MMU
9943 G.argv0_for_re_execing = argv[0];
9944#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009945
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009946 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009947 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9948 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009949 shell_ver = xzalloc(sizeof(*shell_ver));
9950 shell_ver->flg_export = 1;
9951 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009952 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009953 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009954 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009955
Denys Vlasenko605067b2010-09-06 12:10:51 +02009956 /* Create shell local variables from the values
9957 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009958 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009959 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009960 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009961 if (e) while (*e) {
9962 char *value = strchr(*e, '=');
9963 if (value) { /* paranoia */
9964 cur_var->next = xzalloc(sizeof(*cur_var));
9965 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009966 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009967 cur_var->max_len = strlen(*e);
9968 cur_var->flg_export = 1;
9969 }
9970 e++;
9971 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009972 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009973 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9974 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009975
9976 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009977 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009978
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009979#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009980 /* Set (but not export) HOSTNAME unless already set */
9981 if (!get_local_var_value("HOSTNAME")) {
9982 struct utsname uts;
9983 uname(&uts);
9984 set_local_var_from_halves("HOSTNAME", uts.nodename);
9985 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02009986#endif
9987 /* IFS is not inherited from the parent environment */
9988 set_local_var_from_halves("IFS", defifs);
9989
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02009990 if (!get_local_var_value("PATH"))
9991 set_local_var_from_halves("PATH", bb_default_root_path);
9992
Denys Vlasenko0c360192019-05-19 15:37:50 +02009993 /* PS1/PS2 are set later, if we determine that we are interactive */
9994
Denys Vlasenko6db47842009-09-05 20:15:17 +02009995 /* bash also exports SHLVL and _,
9996 * and sets (but doesn't export) the following variables:
9997 * BASH=/bin/bash
9998 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9999 * BASH_VERSION='3.2.0(1)-release'
10000 * HOSTTYPE=i386
10001 * MACHTYPE=i386-pc-linux-gnu
10002 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +020010003 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +020010004 * EUID=<NNNNN>
10005 * UID=<NNNNN>
10006 * GROUPS=()
10007 * LINES=<NNN>
10008 * COLUMNS=<NNN>
10009 * BASH_ARGC=()
10010 * BASH_ARGV=()
10011 * BASH_LINENO=()
10012 * BASH_SOURCE=()
10013 * DIRSTACK=()
10014 * PIPESTATUS=([0]="0")
10015 * HISTFILE=/<xxx>/.bash_history
10016 * HISTFILESIZE=500
10017 * HISTSIZE=500
10018 * MAILCHECK=60
10019 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
10020 * SHELL=/bin/bash
10021 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
10022 * TERM=dumb
10023 * OPTERR=1
10024 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +020010025 * PS4='+ '
10026 */
10027
Eric Andersen94ac2442001-05-22 19:05:18 +000010028 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010029 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +000010030
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010031 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010032 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010033 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010034 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010035 * in order to intercept (more) signals.
10036 */
10037
10038 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010039 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010040 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010041 builtin_argc = 0;
Ron Yorston71df2d32018-11-27 14:34:25 +000010042#if NUM_SCRIPTS > 0
10043 if (argc < 0) {
10044 optarg = get_script_content(-argc - 1);
10045 optind = 0;
10046 argc = string_array_len(argv);
10047 goto run_script;
10048 }
10049#endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010050 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010051 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010052#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010053 "<:$:R:V:"
10054# if ENABLE_HUSH_FUNCTIONS
10055 "F:"
10056# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010057#endif
10058 );
10059 if (opt <= 0)
10060 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010061 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010062 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010063 /* Possibilities:
10064 * sh ... -c 'script'
10065 * sh ... -c 'script' ARG0 [ARG1...]
10066 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +010010067 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010068 * "" needs to be replaced with NULL
10069 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +010010070 * Note: the form without ARG0 never happens:
10071 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010072 */
Ron Yorston71df2d32018-11-27 14:34:25 +000010073#if NUM_SCRIPTS > 0
10074 run_script:
10075#endif
Denys Vlasenkodea47882009-10-09 15:40:49 +020010076 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010077 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010078 G.root_ppid = getppid();
10079 }
Denis Vlasenko87a86552008-07-29 19:43:10 +000010080 G.global_argv = argv + optind;
10081 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010082 if (builtin_argc) {
10083 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10084 const struct built_in_command *x;
10085
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010086 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010087 x = find_builtin(optarg);
10088 if (x) { /* paranoia */
10089 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10090 G.global_argv += builtin_argc;
10091 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +010010092 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +010010093 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010094 }
10095 goto final_return;
10096 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010097 G.opt_c = 1;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010098 if (!G.global_argv[0]) {
10099 /* -c 'script' (no params): prevent empty $0 */
10100 G.global_argv--; /* points to argv[i] of 'script' */
10101 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +020010102 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010103 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010104 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010105 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010106 goto final_return;
10107 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010108 /* Well, we cannot just declare interactiveness,
10109 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010110 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010111 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010112 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010113 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010114 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010115 case 'l':
10116 flags |= OPT_login;
10117 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010118#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010119 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010120 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010121 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010122 case '$': {
10123 unsigned long long empty_trap_mask;
10124
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010125 G.root_pid = bb_strtou(optarg, &optarg, 16);
10126 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010127 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10128 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010129 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10130 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010131 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010132 optarg++;
10133 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010134 optarg++;
10135 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10136 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010137 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010138 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010139# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010140 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010141 for (sig = 1; sig < NSIG; sig++) {
10142 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010143 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010144 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010145 }
10146 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010147# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010148 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010149# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010150 optarg++;
10151 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010152# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010153# if ENABLE_HUSH_FUNCTIONS
10154 /* nommu uses re-exec trick for "... | func | ...",
10155 * should allow "return".
10156 * This accidentally allows returns in subshells.
10157 */
10158 G_flag_return_in_progress = -1;
10159# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010160 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010161 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010162 case 'R':
10163 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010164 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010165 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010166# if ENABLE_HUSH_FUNCTIONS
10167 case 'F': {
10168 struct function *funcp = new_function(optarg);
10169 /* funcp->name is already set to optarg */
10170 /* funcp->body is set to NULL. It's a special case. */
10171 funcp->body_as_string = argv[optind];
10172 optind++;
10173 break;
10174 }
10175# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010176#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010177 case 'n':
10178 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010179 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010180 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010181 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010182 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010183#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010184 fprintf(stderr, "Usage: sh [FILE]...\n"
10185 " or: sh -c command [args]...\n\n");
10186 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010187#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010188 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010189#endif
Eric Andersen25f27032001-04-26 23:22:31 +000010190 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010191 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010192
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010193 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10194 G.global_argc = argc - (optind - 1);
10195 G.global_argv = argv + (optind - 1);
10196 G.global_argv[0] = argv[0];
10197
Denys Vlasenkodea47882009-10-09 15:40:49 +020010198 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010199 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010200 G.root_ppid = getppid();
10201 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010202
10203 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010204 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010205 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010206 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010207 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010208 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010209 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010210 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010211 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010212 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010213 /* bash: after sourcing /etc/profile,
10214 * tries to source (in the given order):
10215 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010216 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010217 * bash also sources ~/.bash_logout on exit.
10218 * If called as sh, skips .bash_XXX files.
10219 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010220 }
10221
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010222 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010223 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010224 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010225 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010226 * "bash <script>" (which is never interactive (unless -i?))
10227 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010228 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010229 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010230 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010231 G.global_argc--;
10232 G.global_argv++;
10233 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010234 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010235 input = hfopen(G.global_argv[0]);
10236 if (!input) {
10237 bb_simple_perror_msg_and_die(G.global_argv[0]);
10238 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010239 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010240 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010241 parse_and_run_file(input);
10242#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010243 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010244#endif
10245 goto final_return;
10246 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010247 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010248 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010249
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010250 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010251 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010252 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010253
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010254 /* A shell is interactive if the '-i' flag was given,
10255 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010256 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010257 * no arguments remaining or the -s flag given
10258 * standard input is a terminal
10259 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010260 * Refer to Posix.2, the description of the 'sh' utility.
10261 */
10262#if ENABLE_HUSH_JOB
10263 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010264 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10265 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10266 if (G_saved_tty_pgrp < 0)
10267 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010268
10269 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010270 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010271 if (G_interactive_fd < 0) {
10272 /* try to dup to any fd */
10273 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010274 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010275 /* give up */
10276 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010277 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010278 }
10279 }
Eric Andersen25f27032001-04-26 23:22:31 +000010280 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010281 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010282 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010283 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010284
Mike Frysinger38478a62009-05-20 04:48:06 -040010285 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010286 /* If we were run as 'hush &', sleep until we are
10287 * in the foreground (tty pgrp == our pgrp).
10288 * If we get started under a job aware app (like bash),
10289 * make sure we are now in charge so we don't fight over
10290 * who gets the foreground */
10291 while (1) {
10292 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010293 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10294 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010295 break;
10296 /* send TTIN to ourself (should stop us) */
10297 kill(- shell_pgrp, SIGTTIN);
10298 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010299 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010300
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010301 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010302 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010303
Mike Frysinger38478a62009-05-20 04:48:06 -040010304 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010305 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010306 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010307 /* Put ourselves in our own process group
10308 * (bash, too, does this only if ctty is available) */
10309 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10310 /* Grab control of the terminal */
10311 tcsetpgrp(G_interactive_fd, getpid());
10312 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010313 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010314
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010315# if ENABLE_FEATURE_EDITING
10316 G.line_input_state = new_line_input_t(FOR_SHELL);
Ron Yorston9e2a5662020-01-21 16:01:58 +000010317# if EDITING_HAS_get_exe_name
10318 G.line_input_state->get_exe_name = get_builtin_name;
10319# endif
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010320# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010321# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10322 {
10323 const char *hp = get_local_var_value("HISTFILE");
10324 if (!hp) {
10325 hp = get_local_var_value("HOME");
10326 if (hp)
10327 hp = concat_path_file(hp, ".hush_history");
10328 } else {
10329 hp = xstrdup(hp);
10330 }
10331 if (hp) {
10332 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010333 //set_local_var(xasprintf("HISTFILE=%s", ...));
10334 }
10335# if ENABLE_FEATURE_SH_HISTFILESIZE
10336 hp = get_local_var_value("HISTFILESIZE");
10337 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10338# endif
10339 }
10340# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010341 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010342 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010343 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010344#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010345 /* No job control compiled in, only prompt/line editing */
10346 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010347 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010348 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010349 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010350 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010351 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010352 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010353 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010354 }
10355 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010356 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010357 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010358 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010359 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010360#else
10361 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010362 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010363#endif
10364 /* bash:
10365 * if interactive but not a login shell, sources ~/.bashrc
10366 * (--norc turns this off, --rcfile <file> overrides)
10367 */
10368
Denys Vlasenko0c360192019-05-19 15:37:50 +020010369 if (G_interactive_fd) {
10370#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10371 /* Set (but not export) PS1/2 unless already set */
10372 if (!get_local_var_value("PS1"))
10373 set_local_var_from_halves("PS1", "\\w \\$ ");
10374 if (!get_local_var_value("PS2"))
10375 set_local_var_from_halves("PS2", "> ");
10376#endif
10377 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10378 /* note: ash and hush share this string */
10379 printf("\n\n%s %s\n"
10380 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10381 "\n",
10382 bb_banner,
10383 "hush - the humble shell"
10384 );
10385 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010386 }
10387
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010388 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010389
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010390 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010391 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010392}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010393
10394
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010395/*
10396 * Built-ins
10397 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010398static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010399{
10400 return 0;
10401}
10402
Denys Vlasenko265062d2017-01-10 15:13:30 +010010403#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010404static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010405{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010406 int argc = string_array_len(argv);
10407 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010408}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010409#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010410#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010411static int FAST_FUNC builtin_test(char **argv)
10412{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010413 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010414}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010415#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010416#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010417static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010418{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010419 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010420}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010421#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010422#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010423static int FAST_FUNC builtin_printf(char **argv)
10424{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010425 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010426}
10427#endif
10428
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010429#if ENABLE_HUSH_HELP
10430static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10431{
10432 const struct built_in_command *x;
10433
10434 printf(
10435 "Built-in commands:\n"
10436 "------------------\n");
10437 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10438 if (x->b_descr)
10439 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10440 }
10441 return EXIT_SUCCESS;
10442}
10443#endif
10444
10445#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10446static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10447{
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010448 if (G.line_input_state)
10449 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010450 return EXIT_SUCCESS;
10451}
10452#endif
10453
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010454static char **skip_dash_dash(char **argv)
10455{
10456 argv++;
10457 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10458 argv++;
10459 return argv;
10460}
10461
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010462static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010463{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010464 const char *newdir;
10465
10466 argv = skip_dash_dash(argv);
10467 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010468 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010469 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010470 * bash says "bash: cd: HOME not set" and does nothing
10471 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010472 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010473 const char *home = get_local_var_value("HOME");
10474 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010475 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010476 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010477 /* Mimic bash message exactly */
10478 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010479 return EXIT_FAILURE;
10480 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010481 /* Read current dir (get_cwd(1) is inside) and set PWD.
10482 * Note: do not enforce exporting. If PWD was unset or unexported,
10483 * set it again, but do not export. bash does the same.
10484 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010485 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010486 return EXIT_SUCCESS;
10487}
10488
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010489static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10490{
10491 puts(get_cwd(0));
10492 return EXIT_SUCCESS;
10493}
10494
10495static int FAST_FUNC builtin_eval(char **argv)
10496{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010497 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010498
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010499 if (!argv[0])
10500 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010501
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010502 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010503 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010504 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010505 /* bash:
10506 * eval "echo Hi; done" ("done" is syntax error):
10507 * "echo Hi" will not execute too.
10508 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010509 parse_and_run_string(argv[0]);
10510 } else {
10511 /* "The eval utility shall construct a command by
10512 * concatenating arguments together, separating
10513 * each with a <space> character."
10514 */
10515 char *str, *p;
10516 unsigned len = 0;
10517 char **pp = argv;
10518 do
10519 len += strlen(*pp) + 1;
10520 while (*++pp);
10521 str = p = xmalloc(len);
10522 pp = argv;
10523 for (;;) {
10524 p = stpcpy(p, *pp);
10525 pp++;
10526 if (!*pp)
10527 break;
10528 *p++ = ' ';
10529 }
10530 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010531 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010532 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010533 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010534 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010535 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010536}
10537
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010538static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010539{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010540 argv = skip_dash_dash(argv);
10541 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010542 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010543
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010544 /* Careful: we can end up here after [v]fork. Do not restore
10545 * tty pgrp then, only top-level shell process does that */
10546 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10547 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10548
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010549 /* Saved-redirect fds, script fds and G_interactive_fd are still
10550 * open here. However, they are all CLOEXEC, and execv below
10551 * closes them. Try interactive "exec ls -l /proc/self/fd",
10552 * it should show no extra open fds in the "ls" process.
10553 * If we'd try to run builtins/NOEXECs, this would need improving.
10554 */
10555 //close_saved_fds_and_FILE_fds();
10556
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010557 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010558 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010559 * and tcsetpgrp, and this is inherently racy.
10560 */
10561 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010562}
10563
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010564static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010565{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010566 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010567
10568 /* interactive bash:
10569 * # trap "echo EEE" EXIT
10570 * # exit
10571 * exit
10572 * There are stopped jobs.
10573 * (if there are _stopped_ jobs, running ones don't count)
10574 * # exit
10575 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010576 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010577 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010578 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010579 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010580
10581 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010582 argv = skip_dash_dash(argv);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010583 if (argv[0] == NULL) {
10584#if ENABLE_HUSH_TRAP
10585 if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
10586 hush_exit(G.pre_trap_exitcode);
10587#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010588 hush_exit(G.last_exitcode);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010589 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010590 /* mimic bash: exit 123abc == exit 255 + error msg */
10591 xfunc_error_retval = 255;
10592 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010593 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010594}
10595
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010596#if ENABLE_HUSH_TYPE
10597/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10598static int FAST_FUNC builtin_type(char **argv)
10599{
10600 int ret = EXIT_SUCCESS;
10601
10602 while (*++argv) {
10603 const char *type;
10604 char *path = NULL;
10605
10606 if (0) {} /* make conditional compile easier below */
10607 /*else if (find_alias(*argv))
10608 type = "an alias";*/
Denys Vlasenko259747c2019-11-28 10:28:14 +010010609# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010610 else if (find_function(*argv))
10611 type = "a function";
Denys Vlasenko259747c2019-11-28 10:28:14 +010010612# endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010613 else if (find_builtin(*argv))
10614 type = "a shell builtin";
10615 else if ((path = find_in_path(*argv)) != NULL)
10616 type = path;
10617 else {
10618 bb_error_msg("type: %s: not found", *argv);
10619 ret = EXIT_FAILURE;
10620 continue;
10621 }
10622
10623 printf("%s is %s\n", *argv, type);
10624 free(path);
10625 }
10626
10627 return ret;
10628}
10629#endif
10630
10631#if ENABLE_HUSH_READ
10632/* Interruptibility of read builtin in bash
10633 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10634 *
10635 * Empty trap makes read ignore corresponding signal, for any signal.
10636 *
10637 * SIGINT:
10638 * - terminates non-interactive shell;
10639 * - interrupts read in interactive shell;
10640 * if it has non-empty trap:
10641 * - executes trap and returns to command prompt in interactive shell;
10642 * - executes trap and returns to read in non-interactive shell;
10643 * SIGTERM:
10644 * - is ignored (does not interrupt) read in interactive shell;
10645 * - terminates non-interactive shell;
10646 * if it has non-empty trap:
10647 * - executes trap and returns to read;
10648 * SIGHUP:
10649 * - terminates shell (regardless of interactivity);
10650 * if it has non-empty trap:
10651 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010652 * SIGCHLD from children:
10653 * - does not interrupt read regardless of interactivity:
10654 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010655 */
10656static int FAST_FUNC builtin_read(char **argv)
10657{
10658 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010659 struct builtin_read_params params;
10660
10661 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010662
10663 /* "!": do not abort on errors.
10664 * Option string must start with "sr" to match BUILTIN_READ_xxx
10665 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010666 params.read_flags = getopt32(argv,
Denys Vlasenko259747c2019-11-28 10:28:14 +010010667# if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010668 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko259747c2019-11-28 10:28:14 +010010669# else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010670 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko259747c2019-11-28 10:28:14 +010010671# endif
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010672 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010673 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010674 return EXIT_FAILURE;
10675 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010676 params.argv = argv;
10677 params.setvar = set_local_var_from_halves;
10678 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010679
10680 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010681 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010682
10683 if ((uintptr_t)r == 1 && errno == EINTR) {
10684 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010685 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010686 goto again;
10687 }
10688
10689 if ((uintptr_t)r > 1) {
James Byrne69374872019-07-02 11:35:03 +020010690 bb_simple_error_msg(r);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010691 r = (char*)(uintptr_t)1;
10692 }
10693
10694 return (uintptr_t)r;
10695}
10696#endif
10697
10698#if ENABLE_HUSH_UMASK
10699static int FAST_FUNC builtin_umask(char **argv)
10700{
10701 int rc;
10702 mode_t mask;
10703
10704 rc = 1;
10705 mask = umask(0);
10706 argv = skip_dash_dash(argv);
10707 if (argv[0]) {
10708 mode_t old_mask = mask;
10709
10710 /* numeric umasks are taken as-is */
10711 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10712 if (!isdigit(argv[0][0]))
10713 mask ^= 0777;
10714 mask = bb_parse_mode(argv[0], mask);
10715 if (!isdigit(argv[0][0]))
10716 mask ^= 0777;
10717 if ((unsigned)mask > 0777) {
10718 mask = old_mask;
10719 /* bash messages:
10720 * bash: umask: 'q': invalid symbolic mode operator
10721 * bash: umask: 999: octal number out of range
10722 */
10723 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10724 rc = 0;
10725 }
10726 } else {
10727 /* Mimic bash */
10728 printf("%04o\n", (unsigned) mask);
10729 /* fall through and restore mask which we set to 0 */
10730 }
10731 umask(mask);
10732
10733 return !rc; /* rc != 0 - success */
10734}
10735#endif
10736
Denys Vlasenko41ade052017-01-08 18:56:24 +010010737#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010738static void print_escaped(const char *s)
10739{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010740 if (*s == '\'')
10741 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010742 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010743 const char *p = strchrnul(s, '\'');
10744 /* print 'xxxx', possibly just '' */
10745 printf("'%.*s'", (int)(p - s), s);
10746 if (*p == '\0')
10747 break;
10748 s = p;
10749 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010750 /* s points to '; print "'''...'''" */
10751 putchar('"');
10752 do putchar('\''); while (*++s == '\'');
10753 putchar('"');
10754 } while (*s);
10755}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010756#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010757
Denys Vlasenko1e660422017-07-17 21:10:50 +020010758#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010759static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010760{
10761 do {
10762 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010763 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010764
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010765 if (*name_end == '\0') {
10766 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010767
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010768 vpp = get_ptr_to_local_var(name, name_end - name);
10769 var = vpp ? *vpp : NULL;
10770
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010771 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010772 /* export -n NAME (without =VALUE) */
10773 if (var) {
10774 var->flg_export = 0;
10775 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10776 unsetenv(name);
10777 } /* else: export -n NOT_EXISTING_VAR: no-op */
10778 continue;
10779 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010780 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010781 /* export NAME (without =VALUE) */
10782 if (var) {
10783 var->flg_export = 1;
10784 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10785 putenv(var->varstr);
10786 continue;
10787 }
10788 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010789 if (flags & SETFLAG_MAKE_RO) {
10790 /* readonly NAME (without =VALUE) */
10791 if (var) {
10792 var->flg_read_only = 1;
10793 continue;
10794 }
10795 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010796# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010797 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010798 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010799 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10800 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010801 /* "local x=abc; ...; local x" - ignore second local decl */
10802 continue;
10803 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010804 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010805# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010806 /* Exporting non-existing variable.
10807 * bash does not put it in environment,
10808 * but remembers that it is exported,
10809 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010810 * We just set it to "" and export.
10811 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010812 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010813 * bash sets the value to "".
10814 */
10815 /* Or, it's "readonly NAME" (without =VALUE).
10816 * bash remembers NAME and disallows its creation
10817 * in the future.
10818 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010819 name = xasprintf("%s=", name);
10820 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010821 if (*name_end != '=') {
10822 bb_error_msg("'%s': bad variable name", name);
10823 /* do not parse following argv[]s: */
10824 return 1;
10825 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020010826 /* (Un)exporting/making local NAME=VALUE */
10827 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010828 /* Testcase: export PS1='\w \$ ' */
10829 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010830 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010831 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010832 if (set_local_var(name, flags))
10833 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010834 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010835 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010836}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010837#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010838
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010839#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010840static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010841{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010842 unsigned opt_unexport;
10843
Denys Vlasenko259747c2019-11-28 10:28:14 +010010844# if ENABLE_HUSH_EXPORT_N
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010845 /* "!": do not abort on errors */
10846 opt_unexport = getopt32(argv, "!n");
10847 if (opt_unexport == (uint32_t)-1)
10848 return EXIT_FAILURE;
10849 argv += optind;
Denys Vlasenko259747c2019-11-28 10:28:14 +010010850# else
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010851 opt_unexport = 0;
10852 argv++;
Denys Vlasenko259747c2019-11-28 10:28:14 +010010853# endif
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010854
10855 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010856 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010857 if (e) {
10858 while (*e) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010010859# if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010860 puts(*e++);
Denys Vlasenko259747c2019-11-28 10:28:14 +010010861# else
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010862 /* ash emits: export VAR='VAL'
10863 * bash: declare -x VAR="VAL"
10864 * we follow ash example */
10865 const char *s = *e++;
10866 const char *p = strchr(s, '=');
10867
10868 if (!p) /* wtf? take next variable */
10869 continue;
10870 /* export var= */
10871 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010872 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010873 putchar('\n');
Denys Vlasenko259747c2019-11-28 10:28:14 +010010874# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010875 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010876 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010877 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010878 return EXIT_SUCCESS;
10879 }
10880
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010881 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010882}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010883#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010884
Denys Vlasenko295fef82009-06-03 12:47:26 +020010885#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010886static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010887{
10888 if (G.func_nest_level == 0) {
10889 bb_error_msg("%s: not in a function", argv[0]);
10890 return EXIT_FAILURE; /* bash compat */
10891 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010892 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010893 /* Since all builtins run in a nested variable level,
10894 * need to use level - 1 here. Or else the variable will be removed at once
10895 * after builtin returns.
10896 */
10897 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010898}
10899#endif
10900
Denys Vlasenko1e660422017-07-17 21:10:50 +020010901#if ENABLE_HUSH_READONLY
10902static int FAST_FUNC builtin_readonly(char **argv)
10903{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010904 argv++;
10905 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010906 /* bash: readonly [-p]: list all readonly VARs
10907 * (-p has no effect in bash)
10908 */
10909 struct variable *e;
10910 for (e = G.top_var; e; e = e->next) {
10911 if (e->flg_read_only) {
10912//TODO: quote value: readonly VAR='VAL'
10913 printf("readonly %s\n", e->varstr);
10914 }
10915 }
10916 return EXIT_SUCCESS;
10917 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010918 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010919}
10920#endif
10921
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010922#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010923/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10924static int FAST_FUNC builtin_unset(char **argv)
10925{
10926 int ret;
10927 unsigned opts;
10928
10929 /* "!": do not abort on errors */
10930 /* "+": stop at 1st non-option */
10931 opts = getopt32(argv, "!+vf");
10932 if (opts == (unsigned)-1)
10933 return EXIT_FAILURE;
10934 if (opts == 3) {
James Byrne69374872019-07-02 11:35:03 +020010935 bb_simple_error_msg("unset: -v and -f are exclusive");
Denys Vlasenko61508d92016-10-02 21:12:02 +020010936 return EXIT_FAILURE;
10937 }
10938 argv += optind;
10939
10940 ret = EXIT_SUCCESS;
10941 while (*argv) {
10942 if (!(opts & 2)) { /* not -f */
10943 if (unset_local_var(*argv)) {
10944 /* unset <nonexistent_var> doesn't fail.
10945 * Error is when one tries to unset RO var.
10946 * Message was printed by unset_local_var. */
10947 ret = EXIT_FAILURE;
10948 }
10949 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010950# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010951 else {
10952 unset_func(*argv);
10953 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010954# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010955 argv++;
10956 }
10957 return ret;
10958}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010959#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010960
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010961#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010962/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10963 * built-in 'set' handler
10964 * SUSv3 says:
10965 * set [-abCefhmnuvx] [-o option] [argument...]
10966 * set [+abCefhmnuvx] [+o option] [argument...]
10967 * set -- [argument...]
10968 * set -o
10969 * set +o
10970 * Implementations shall support the options in both their hyphen and
10971 * plus-sign forms. These options can also be specified as options to sh.
10972 * Examples:
10973 * Write out all variables and their values: set
10974 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10975 * Turn on the -x and -v options: set -xv
10976 * Unset all positional parameters: set --
10977 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10978 * Set the positional parameters to the expansion of x, even if x expands
10979 * with a leading '-' or '+': set -- $x
10980 *
10981 * So far, we only support "set -- [argument...]" and some of the short names.
10982 */
10983static int FAST_FUNC builtin_set(char **argv)
10984{
10985 int n;
10986 char **pp, **g_argv;
10987 char *arg = *++argv;
10988
10989 if (arg == NULL) {
10990 struct variable *e;
10991 for (e = G.top_var; e; e = e->next)
10992 puts(e->varstr);
10993 return EXIT_SUCCESS;
10994 }
10995
10996 do {
10997 if (strcmp(arg, "--") == 0) {
10998 ++argv;
10999 goto set_argv;
11000 }
11001 if (arg[0] != '+' && arg[0] != '-')
11002 break;
11003 for (n = 1; arg[n]; ++n) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020011004 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
11005 bb_error_msg("%s: %s: invalid option", "set", arg);
11006 return EXIT_FAILURE;
11007 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011008 if (arg[n] == 'o' && argv[1])
11009 argv++;
11010 }
11011 } while ((arg = *++argv) != NULL);
11012 /* Now argv[0] is 1st argument */
11013
11014 if (arg == NULL)
11015 return EXIT_SUCCESS;
11016 set_argv:
11017
11018 /* NB: G.global_argv[0] ($0) is never freed/changed */
11019 g_argv = G.global_argv;
11020 if (G.global_args_malloced) {
11021 pp = g_argv;
11022 while (*++pp)
11023 free(*pp);
11024 g_argv[1] = NULL;
11025 } else {
11026 G.global_args_malloced = 1;
11027 pp = xzalloc(sizeof(pp[0]) * 2);
11028 pp[0] = g_argv[0]; /* retain $0 */
11029 g_argv = pp;
11030 }
11031 /* This realloc's G.global_argv */
11032 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
11033
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020011034 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020011035
11036 return EXIT_SUCCESS;
Denys Vlasenko61508d92016-10-02 21:12:02 +020011037}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011038#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011039
11040static int FAST_FUNC builtin_shift(char **argv)
11041{
11042 int n = 1;
11043 argv = skip_dash_dash(argv);
11044 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020011045 n = bb_strtou(argv[0], NULL, 10);
11046 if (errno || n < 0) {
11047 /* shared string with ash.c */
11048 bb_error_msg("Illegal number: %s", argv[0]);
11049 /*
11050 * ash aborts in this case.
11051 * bash prints error message and set $? to 1.
11052 * Interestingly, for "shift 99999" bash does not
11053 * print error message, but does set $? to 1
11054 * (and does no shifting at all).
11055 */
11056 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011057 }
11058 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010011059 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020011060 int m = 1;
11061 while (m <= n)
11062 free(G.global_argv[m++]);
11063 }
11064 G.global_argc -= n;
11065 memmove(&G.global_argv[1], &G.global_argv[n+1],
11066 G.global_argc * sizeof(G.global_argv[0]));
11067 return EXIT_SUCCESS;
11068 }
11069 return EXIT_FAILURE;
11070}
11071
Denys Vlasenko74d40582017-08-11 01:32:46 +020011072#if ENABLE_HUSH_GETOPTS
11073static int FAST_FUNC builtin_getopts(char **argv)
11074{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011075/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11076
Denys Vlasenko74d40582017-08-11 01:32:46 +020011077TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011078If a required argument is not found, and getopts is not silent,
11079a question mark (?) is placed in VAR, OPTARG is unset, and a
11080diagnostic message is printed. If getopts is silent, then a
11081colon (:) is placed in VAR and OPTARG is set to the option
11082character found.
11083
11084Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011085
11086"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011087*/
11088 char cbuf[2];
11089 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011090 int c, n, exitcode, my_opterr;
11091 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011092
11093 optstring = *++argv;
11094 if (!optstring || !(var = *++argv)) {
James Byrne69374872019-07-02 11:35:03 +020011095 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
Denys Vlasenko74d40582017-08-11 01:32:46 +020011096 return EXIT_FAILURE;
11097 }
11098
Denys Vlasenko238ff982017-08-29 13:38:30 +020011099 if (argv[1])
11100 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11101 else
11102 argv = G.global_argv;
11103 cbuf[1] = '\0';
11104
11105 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011106 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011107 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011108 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011109 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011110 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011111
11112 /* getopts stops on first non-option. Add "+" to force that */
11113 /*if (optstring[0] != '+')*/ {
11114 char *s = alloca(strlen(optstring) + 2);
11115 sprintf(s, "+%s", optstring);
11116 optstring = s;
11117 }
11118
Denys Vlasenko238ff982017-08-29 13:38:30 +020011119 /* Naively, now we should just
11120 * cp = get_local_var_value("OPTIND");
11121 * optind = cp ? atoi(cp) : 0;
11122 * optarg = NULL;
11123 * opterr = my_opterr;
11124 * c = getopt(string_array_len(argv), argv, optstring);
11125 * and be done? Not so fast...
11126 * Unlike normal getopt() usage in C programs, here
11127 * each successive call will (usually) have the same argv[] CONTENTS,
11128 * but not the ADDRESSES. Worse yet, it's possible that between
11129 * invocations of "getopts", there will be calls to shell builtins
11130 * which use getopt() internally. Example:
11131 * while getopts "abc" RES -a -bc -abc de; do
11132 * unset -ff func
11133 * done
11134 * This would not work correctly: getopt() call inside "unset"
11135 * modifies internal libc state which is tracking position in
11136 * multi-option strings ("-abc"). At best, it can skip options
11137 * or return the same option infinitely. With glibc implementation
11138 * of getopt(), it would use outright invalid pointers and return
11139 * garbage even _without_ "unset" mangling internal state.
11140 *
11141 * We resort to resetting getopt() state and calling it N times,
11142 * until we get Nth result (or failure).
11143 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11144 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011145 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011146 count = 0;
11147 n = string_array_len(argv);
11148 do {
11149 optarg = NULL;
11150 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11151 c = getopt(n, argv, optstring);
11152 if (c < 0)
11153 break;
11154 count++;
11155 } while (count <= G.getopt_count);
11156
11157 /* Set OPTIND. Prevent resetting of the magic counter! */
11158 set_local_var_from_halves("OPTIND", utoa(optind));
11159 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011160 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011161
11162 /* Set OPTARG */
11163 /* Always set or unset, never left as-is, even on exit/error:
11164 * "If no option was found, or if the option that was found
11165 * does not have an option-argument, OPTARG shall be unset."
11166 */
11167 cp = optarg;
11168 if (c == '?') {
11169 /* If ":optstring" and unknown option is seen,
11170 * it is stored to OPTARG.
11171 */
11172 if (optstring[1] == ':') {
11173 cbuf[0] = optopt;
11174 cp = cbuf;
11175 }
11176 }
11177 if (cp)
11178 set_local_var_from_halves("OPTARG", cp);
11179 else
11180 unset_local_var("OPTARG");
11181
11182 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011183 exitcode = EXIT_SUCCESS;
11184 if (c < 0) { /* -1: end of options */
11185 exitcode = EXIT_FAILURE;
11186 c = '?';
11187 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011188
Denys Vlasenko238ff982017-08-29 13:38:30 +020011189 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011190 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011191 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011192
Denys Vlasenko74d40582017-08-11 01:32:46 +020011193 return exitcode;
11194}
11195#endif
11196
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011197static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011198{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011199 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011200 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011201 save_arg_t sv;
11202 char *args_need_save;
11203#if ENABLE_HUSH_FUNCTIONS
11204 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011205#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011206
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011207 argv = skip_dash_dash(argv);
11208 filename = argv[0];
11209 if (!filename) {
11210 /* bash says: "bash: .: filename argument required" */
11211 return 2; /* bash compat */
11212 }
11213 arg_path = NULL;
11214 if (!strchr(filename, '/')) {
11215 arg_path = find_in_path(filename);
11216 if (arg_path)
11217 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011218 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011219 errno = ENOENT;
11220 bb_simple_perror_msg(filename);
11221 return EXIT_FAILURE;
11222 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011223 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011224 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011225 free(arg_path);
11226 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011227 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011228 /* POSIX: non-interactive shell should abort here,
11229 * not merely fail. So far no one complained :)
11230 */
11231 return EXIT_FAILURE;
11232 }
11233
11234#if ENABLE_HUSH_FUNCTIONS
11235 sv_flg = G_flag_return_in_progress;
11236 /* "we are inside sourced file, ok to use return" */
11237 G_flag_return_in_progress = -1;
11238#endif
11239 args_need_save = argv[1]; /* used as a boolean variable */
11240 if (args_need_save)
11241 save_and_replace_G_args(&sv, argv);
11242
11243 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11244 G.last_exitcode = 0;
11245 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011246 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011247
11248 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11249 restore_G_args(&sv, argv);
11250#if ENABLE_HUSH_FUNCTIONS
11251 G_flag_return_in_progress = sv_flg;
11252#endif
11253
11254 return G.last_exitcode;
11255}
11256
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011257#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011258static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011259{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011260 int sig;
11261 char *new_cmd;
11262
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011263 if (!G_traps)
11264 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011265
11266 argv++;
11267 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011268 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011269 /* No args: print all trapped */
11270 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011271 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011272 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011273 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011274 /* note: bash adds "SIG", but only if invoked
11275 * as "bash". If called as "sh", or if set -o posix,
11276 * then it prints short signal names.
11277 * We are printing short names: */
11278 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011279 }
11280 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011281 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011282 return EXIT_SUCCESS;
11283 }
11284
11285 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011286 /* If first arg is a number: reset all specified signals */
11287 sig = bb_strtou(*argv, NULL, 10);
11288 if (errno == 0) {
11289 int ret;
11290 process_sig_list:
11291 ret = EXIT_SUCCESS;
11292 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011293 sighandler_t handler;
11294
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011295 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011296 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011297 ret = EXIT_FAILURE;
11298 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011299 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011300 continue;
11301 }
11302
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011303 free(G_traps[sig]);
11304 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011305
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011306 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011307 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011308
11309 /* There is no signal for 0 (EXIT) */
11310 if (sig == 0)
11311 continue;
11312
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011313 if (new_cmd)
11314 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11315 else
11316 /* We are removing trap handler */
11317 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011318 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011319 }
11320 return ret;
11321 }
11322
11323 if (!argv[1]) { /* no second arg */
James Byrne69374872019-07-02 11:35:03 +020011324 bb_simple_error_msg("trap: invalid arguments");
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011325 return EXIT_FAILURE;
11326 }
11327
11328 /* First arg is "-": reset all specified to default */
11329 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11330 /* Everything else: set arg as signal handler
11331 * (includes "" case, which ignores signal) */
11332 if (argv[0][0] == '-') {
11333 if (argv[0][1] == '\0') { /* "-" */
11334 /* new_cmd remains NULL: "reset these sigs" */
11335 goto reset_traps;
11336 }
11337 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11338 argv++;
11339 }
11340 /* else: "-something", no special meaning */
11341 }
11342 new_cmd = *argv;
11343 reset_traps:
11344 argv++;
11345 goto process_sig_list;
11346}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011347#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011348
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011349#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011350static struct pipe *parse_jobspec(const char *str)
11351{
11352 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011353 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011354
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011355 if (sscanf(str, "%%%u", &jobnum) != 1) {
11356 if (str[0] != '%'
11357 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11358 ) {
11359 bb_error_msg("bad argument '%s'", str);
11360 return NULL;
11361 }
11362 /* It is "%%", "%+" or "%" - current job */
11363 jobnum = G.last_jobid;
11364 if (jobnum == 0) {
James Byrne69374872019-07-02 11:35:03 +020011365 bb_simple_error_msg("no current job");
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011366 return NULL;
11367 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011368 }
11369 for (pi = G.job_list; pi; pi = pi->next) {
11370 if (pi->jobid == jobnum) {
11371 return pi;
11372 }
11373 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011374 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011375 return NULL;
11376}
11377
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011378static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11379{
11380 struct pipe *job;
11381 const char *status_string;
11382
11383 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11384 for (job = G.job_list; job; job = job->next) {
11385 if (job->alive_cmds == job->stopped_cmds)
11386 status_string = "Stopped";
11387 else
11388 status_string = "Running";
11389
11390 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11391 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011392
11393 clean_up_last_dead_job();
11394
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011395 return EXIT_SUCCESS;
11396}
11397
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011398/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011399static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011400{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011401 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011402 struct pipe *pi;
11403
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011404 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011405 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011406
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011407 /* If they gave us no args, assume they want the last backgrounded task */
11408 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011409 for (pi = G.job_list; pi; pi = pi->next) {
11410 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011411 goto found;
11412 }
11413 }
11414 bb_error_msg("%s: no current job", argv[0]);
11415 return EXIT_FAILURE;
11416 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011417
11418 pi = parse_jobspec(argv[1]);
11419 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011420 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011421 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011422 /* TODO: bash prints a string representation
11423 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011424 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011425 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011426 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011427 }
11428
11429 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011430 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11431 for (i = 0; i < pi->num_cmds; i++) {
11432 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011433 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011434 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011435
11436 i = kill(- pi->pgrp, SIGCONT);
11437 if (i < 0) {
11438 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011439 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011440 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011441 }
James Byrne69374872019-07-02 11:35:03 +020011442 bb_simple_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011443 }
11444
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011445 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011446 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011447 return checkjobs_and_fg_shell(pi);
11448 }
11449 return EXIT_SUCCESS;
11450}
11451#endif
11452
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011453#if ENABLE_HUSH_KILL
11454static int FAST_FUNC builtin_kill(char **argv)
11455{
11456 int ret = 0;
11457
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011458# if ENABLE_HUSH_JOB
11459 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11460 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011461
11462 do {
11463 struct pipe *pi;
11464 char *dst;
11465 int j, n;
11466
11467 if (argv[i][0] != '%')
11468 continue;
11469 /*
11470 * "kill %N" - job kill
11471 * Converting to pgrp / pid kill
11472 */
11473 pi = parse_jobspec(argv[i]);
11474 if (!pi) {
11475 /* Eat bad jobspec */
11476 j = i;
11477 do {
11478 j++;
11479 argv[j - 1] = argv[j];
11480 } while (argv[j]);
11481 ret = 1;
11482 i--;
11483 continue;
11484 }
11485 /*
11486 * In jobs started under job control, we signal
11487 * entire process group by kill -PGRP_ID.
11488 * This happens, f.e., in interactive shell.
11489 *
11490 * Otherwise, we signal each child via
11491 * kill PID1 PID2 PID3.
11492 * Testcases:
11493 * sh -c 'sleep 1|sleep 1 & kill %1'
11494 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11495 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11496 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011497 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011498 dst = alloca(n * sizeof(int)*4);
11499 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011500 if (G_interactive_fd)
11501 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011502 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011503 struct command *cmd = &pi->cmds[j];
11504 /* Skip exited members of the job */
11505 if (cmd->pid == 0)
11506 continue;
11507 /*
11508 * kill_main has matching code to expect
11509 * leading space. Needed to not confuse
11510 * negative pids with "kill -SIGNAL_NO" syntax
11511 */
11512 dst += sprintf(dst, " %u", (int)cmd->pid);
11513 }
11514 *dst = '\0';
11515 } while (argv[++i]);
11516 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011517# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011518
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011519 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011520 ret = run_applet_main(argv, kill_main);
11521 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011522 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011523 return ret;
11524}
11525#endif
11526
11527#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011528/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011529# if !ENABLE_HUSH_JOB
11530# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11531# endif
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011532static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011533{
11534 int ret = 0;
11535 for (;;) {
11536 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011537 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011538
Denys Vlasenko830ea352016-11-08 04:59:11 +010011539 if (!sigisemptyset(&G.pending_set))
11540 goto check_sig;
11541
Denys Vlasenko7e675362016-10-28 21:57:31 +020011542 /* waitpid is not interruptible by SA_RESTARTed
11543 * signals which we use. Thus, this ugly dance:
11544 */
11545
11546 /* Make sure possible SIGCHLD is stored in kernel's
11547 * pending signal mask before we call waitpid.
11548 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011549 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011550 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011551 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011552 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011553
11554 if (!sigisemptyset(&G.pending_set)) {
11555 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011556 goto restore;
11557 }
11558
11559 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011560/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011561 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011562 debug_printf_exec("checkjobs:%d\n", ret);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011563# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011564 if (waitfor_pipe) {
11565 int rcode = job_exited_or_stopped(waitfor_pipe);
11566 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11567 if (rcode >= 0) {
11568 ret = rcode;
11569 sigprocmask(SIG_SETMASK, &oldset, NULL);
11570 break;
11571 }
11572 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011573# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011574 /* if ECHILD, there are no children (ret is -1 or 0) */
11575 /* if ret == 0, no children changed state */
11576 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011577 if (errno == ECHILD || ret) {
11578 ret--;
11579 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011580 ret = 0;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011581# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011582 if (waitfor_pid == -1 && errno == ECHILD) {
11583 /* exitcode of "wait -n" with no children is 127, not 0 */
11584 ret = 127;
11585 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011586# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011587 sigprocmask(SIG_SETMASK, &oldset, NULL);
11588 break;
11589 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011590 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011591 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11592 /* Note: sigsuspend invokes signal handler */
11593 sigsuspend(&oldset);
Denys Vlasenko23bc5622020-02-18 16:46:01 +010011594 /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
11595 * to make sure SIGCHLD is not masked off?
11596 * It was reported that this:
11597 * fn() { : | return; }
11598 * shopt -s lastpipe
11599 * fn
11600 * exec hush SCRIPT
11601 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
11602 * making "wait" commands in SCRIPT block forever.
11603 */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011604 restore:
11605 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011606 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011607 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011608 sig = check_and_run_traps();
11609 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011610 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011611 ret = 128 + sig;
11612 break;
11613 }
11614 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11615 }
11616 return ret;
11617}
11618
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011619static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011620{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011621 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011622 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011623
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011624 argv = skip_dash_dash(argv);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011625# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011626 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011627 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011628 /* (bash accepts "wait -n PID" too and ignores PID) */
11629 G.dead_job_exitcode = -1;
11630 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011631 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011632# endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011633 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011634 /* Don't care about wait results */
11635 /* Note 1: must wait until there are no more children */
11636 /* Note 2: must be interruptible */
11637 /* Examples:
11638 * $ sleep 3 & sleep 6 & wait
11639 * [1] 30934 sleep 3
11640 * [2] 30935 sleep 6
11641 * [1] Done sleep 3
11642 * [2] Done sleep 6
11643 * $ sleep 3 & sleep 6 & wait
11644 * [1] 30936 sleep 3
11645 * [2] 30937 sleep 6
11646 * [1] Done sleep 3
11647 * ^C <-- after ~4 sec from keyboard
11648 * $
11649 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011650 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011651 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011652
Denys Vlasenko7e675362016-10-28 21:57:31 +020011653 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011654 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011655 if (errno || pid <= 0) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011656# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011657 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011658 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011659 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011660 wait_pipe = parse_jobspec(*argv);
11661 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011662 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011663 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011664 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011665 } else {
11666 /* waiting on "last dead job" removes it */
11667 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011668 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011669 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011670 /* else: parse_jobspec() already emitted error msg */
11671 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011672 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011673# endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011674 /* mimic bash message */
11675 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011676 ret = EXIT_FAILURE;
11677 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011678 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011679
Denys Vlasenko7e675362016-10-28 21:57:31 +020011680 /* Do we have such child? */
11681 ret = waitpid(pid, &status, WNOHANG);
11682 if (ret < 0) {
11683 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011684 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011685 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011686 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011687 /* "wait $!" but last bg task has already exited. Try:
11688 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11689 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011690 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011691 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011692 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011693 } else {
11694 /* Example: "wait 1". mimic bash message */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011695 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011696 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011697 } else {
11698 /* ??? */
11699 bb_perror_msg("wait %s", *argv);
11700 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011701 continue; /* bash checks all argv[] */
11702 }
11703 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011704 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011705 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011706 } else {
11707 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011708 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011709 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011710 if (WIFSIGNALED(status))
11711 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011712 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011713 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011714
11715 return ret;
11716}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011717#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011718
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011719#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11720static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11721{
11722 if (argv[1]) {
11723 def = bb_strtou(argv[1], NULL, 10);
11724 if (errno || def < def_min || argv[2]) {
11725 bb_error_msg("%s: bad arguments", argv[0]);
11726 def = UINT_MAX;
11727 }
11728 }
11729 return def;
11730}
11731#endif
11732
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011733#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011734static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011735{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011736 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011737 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011738 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011739 /* if we came from builtin_continue(), need to undo "= 1" */
11740 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011741 return EXIT_SUCCESS; /* bash compat */
11742 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011743 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011744
11745 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11746 if (depth == UINT_MAX)
11747 G.flag_break_continue = BC_BREAK;
11748 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011749 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011750
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011751 return EXIT_SUCCESS;
11752}
11753
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011754static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011755{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011756 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11757 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011758}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011759#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011760
11761#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011762static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011763{
11764 int rc;
11765
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011766 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011767 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11768 return EXIT_FAILURE; /* bash compat */
11769 }
11770
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011771 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011772
11773 /* bash:
11774 * out of range: wraps around at 256, does not error out
11775 * non-numeric param:
11776 * f() { false; return qwe; }; f; echo $?
11777 * bash: return: qwe: numeric argument required <== we do this
11778 * 255 <== we also do this
11779 */
11780 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
Denys Vlasenkobb095f42020-02-20 16:37:59 +010011781# if ENABLE_HUSH_TRAP
11782 if (argv[1]) { /* "return ARG" inside a running trap sets $? */
11783 debug_printf_exec("G.return_exitcode=%d\n", rc);
11784 G.return_exitcode = rc;
11785 }
11786# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011787 return rc;
11788}
11789#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011790
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011791#if ENABLE_HUSH_TIMES
11792static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11793{
11794 static const uint8_t times_tbl[] ALIGN1 = {
11795 ' ', offsetof(struct tms, tms_utime),
11796 '\n', offsetof(struct tms, tms_stime),
11797 ' ', offsetof(struct tms, tms_cutime),
11798 '\n', offsetof(struct tms, tms_cstime),
11799 0
11800 };
11801 const uint8_t *p;
11802 unsigned clk_tck;
11803 struct tms buf;
11804
11805 clk_tck = bb_clk_tck();
11806
11807 times(&buf);
11808 p = times_tbl;
11809 do {
11810 unsigned sec, frac;
11811 unsigned long t;
11812 t = *(clock_t *)(((char *) &buf) + p[1]);
11813 sec = t / clk_tck;
11814 frac = t % clk_tck;
11815 printf("%um%u.%03us%c",
11816 sec / 60, sec % 60,
11817 (frac * 1000) / clk_tck,
11818 p[0]);
11819 p += 2;
11820 } while (*p);
11821
11822 return EXIT_SUCCESS;
11823}
11824#endif
11825
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011826#if ENABLE_HUSH_MEMLEAK
11827static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11828{
11829 void *p;
11830 unsigned long l;
11831
11832# ifdef M_TRIM_THRESHOLD
11833 /* Optional. Reduces probability of false positives */
11834 malloc_trim(0);
11835# endif
11836 /* Crude attempt to find where "free memory" starts,
11837 * sans fragmentation. */
11838 p = malloc(240);
11839 l = (unsigned long)p;
11840 free(p);
11841 p = malloc(3400);
11842 if (l < (unsigned long)p) l = (unsigned long)p;
11843 free(p);
11844
11845
11846# if 0 /* debug */
11847 {
11848 struct mallinfo mi = mallinfo();
11849 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11850 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11851 }
11852# endif
11853
11854 if (!G.memleak_value)
11855 G.memleak_value = l;
11856
11857 l -= G.memleak_value;
11858 if ((long)l < 0)
11859 l = 0;
11860 l /= 1024;
11861 if (l > 127)
11862 l = 127;
11863
11864 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11865 return l;
11866}
11867#endif