blob: f82747f74bedc8e3a8a80adb782694066dd090a0 [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;
576 int is_stdin;
577 int fd;
578 char buf[1024];
579} HFILE;
580
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000581typedef struct in_str {
582 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200583 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200584 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200585 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000586} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000587
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200588/* The descrip member of this structure is only used to make
589 * debugging output pretty */
590static const struct {
591 int mode;
592 signed char default_fd;
593 char descrip[3];
594} redir_table[] = {
595 { O_RDONLY, 0, "<" },
596 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
597 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
598 { O_CREAT|O_RDWR, 1, "<>" },
599 { O_RDONLY, 0, "<<" },
600/* Should not be needed. Bogus default_fd helps in debugging */
601/* { O_RDONLY, 77, "<<" }, */
602};
603
Eric Andersen25f27032001-04-26 23:22:31 +0000604struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000605 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000606 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000607 int rd_fd; /* fd to redirect */
608 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
609 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000610 smallint rd_type; /* (enum redir_type) */
611 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000612 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200613 * bit 0: do we need to trim leading tabs?
614 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000615 */
Eric Andersen25f27032001-04-26 23:22:31 +0000616};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000617typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200618 REDIRECT_INPUT = 0,
619 REDIRECT_OVERWRITE = 1,
620 REDIRECT_APPEND = 2,
621 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000622 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200623 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000624
625 REDIRFD_CLOSE = -3,
626 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000627 REDIRFD_TO_FILE = -1,
628 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000629
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000630 HEREDOC_SKIPTABS = 1,
631 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000632} redir_type;
633
Eric Andersen25f27032001-04-26 23:22:31 +0000634
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000635struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000636 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200637 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100638#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100639 unsigned lineno;
640#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200641 smallint cmd_type; /* CMD_xxx */
642#define CMD_NORMAL 0
643#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200644#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
645/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
646 * "export v=t*"
647 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200648# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000649#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200650#if ENABLE_HUSH_FUNCTIONS
651# define CMD_FUNCDEF 3
652#endif
653
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100654 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200655 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
656 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000657#if !BB_MMU
658 char *group_as_string;
659#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660#if ENABLE_HUSH_FUNCTIONS
661 struct function *child_func;
662/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200663 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000664 * When we execute "f1() {a;}" cmd, we create new function and clear
665 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200666 * When we execute "f1() {b;}", we notice that f1 exists,
667 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000668 * we put those fields back into cmd->xxx
669 * (struct function has ->parent_cmd ptr to facilitate that).
670 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
671 * Without this trick, loop would execute a;b;b;b;...
672 * instead of correct sequence a;b;a;b;...
673 * When command is freed, it severs the link
674 * (sets ->child_func->parent_cmd to NULL).
675 */
676#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000677 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000678/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
679 * and on execution these are substituted with their values.
680 * Substitution can make _several_ words out of one argv[n]!
681 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000682 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000683 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000684 struct redir_struct *redirects; /* I/O redirections */
685};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000686/* Is there anything in this command at all? */
687#define IS_NULL_CMD(cmd) \
688 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
689
Eric Andersen25f27032001-04-26 23:22:31 +0000690struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000691 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000692 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000693 int alive_cmds; /* number of commands running (not exited) */
694 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000695#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100696 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000697 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000698 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000699#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000700 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000701 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000702 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
703 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000704};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000705typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100706 PIPE_SEQ = 0,
707 PIPE_AND = 1,
708 PIPE_OR = 2,
709 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000710} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000711/* Is there anything in this pipe at all? */
712#define IS_NULL_PIPE(pi) \
713 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000714
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715/* This holds pointers to the various results of parsing */
716struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000717 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000718 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000719 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000720 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000721 /* last command in pipe (being constructed right now) */
722 struct command *command;
723 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000724 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200725 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000726#if !BB_MMU
727 o_string as_string;
728#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200729 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000730#if HAS_KEYWORDS
731 smallint ctx_res_w;
732 smallint ctx_inverted; /* "! cmd | cmd" */
733#if ENABLE_HUSH_CASE
734 smallint ctx_dsemicolon; /* ";;" seen */
735#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000736 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
737 int old_flag;
738 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000739 * example: "if pipe1; pipe2; then pipe3; fi"
740 * when we see "if" or "then", we malloc and copy current context,
741 * and make ->stack point to it. then we parse pipeN.
742 * when closing "then" / fi" / whatever is found,
743 * we move list_head into ->stack->command->group,
744 * copy ->stack into current context, and delete ->stack.
745 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000746 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000747 struct parse_context *stack;
748#endif
749};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200750enum {
751 MAYBE_ASSIGNMENT = 0,
752 DEFINITELY_ASSIGNMENT = 1,
753 NOT_ASSIGNMENT = 2,
754 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
755 WORD_IS_KEYWORD = 3,
756};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000757
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000758/* On program start, environ points to initial environment.
759 * putenv adds new pointers into it, unsetenv removes them.
760 * Neither of these (de)allocates the strings.
761 * setenv allocates new strings in malloc space and does putenv,
762 * and thus setenv is unusable (leaky) for shell's purposes */
763#define setenv(...) setenv_is_leaky_dont_use()
764struct variable {
765 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000766 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000767 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200768 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000769 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000770 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000771};
772
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000773enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000774 BC_BREAK = 1,
775 BC_CONTINUE = 2,
776};
777
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000778#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000779struct function {
780 struct function *next;
781 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000782 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000783 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200784# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200786# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000787};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000788#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000789
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000790
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100791/* set -/+o OPT support. (TODO: make it optional)
792 * bash supports the following opts:
793 * allexport off
794 * braceexpand on
795 * emacs on
796 * errexit off
797 * errtrace off
798 * functrace off
799 * hashall on
800 * histexpand off
801 * history on
802 * ignoreeof off
803 * interactive-comments on
804 * keyword off
805 * monitor on
806 * noclobber off
807 * noexec off
808 * noglob off
809 * nolog off
810 * notify off
811 * nounset off
812 * onecmd off
813 * physical off
814 * pipefail off
815 * posix off
816 * privileged off
817 * verbose off
818 * vi off
819 * xtrace off
820 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800821static const char o_opt_strings[] ALIGN1 =
822 "pipefail\0"
823 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200824 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800825#if ENABLE_HUSH_MODE_X
826 "xtrace\0"
827#endif
828 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100829enum {
830 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800831 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200832 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800833#if ENABLE_HUSH_MODE_X
834 OPT_O_XTRACE,
835#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100836 NUM_OPT_O
837};
838
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000840/* Sorted roughly by size (smaller offsets == smaller code) */
841struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000842 /* interactive_fd != 0 means we are an interactive shell.
843 * If we are, then saved_tty_pgrp can also be != 0, meaning
844 * that controlling tty is available. With saved_tty_pgrp == 0,
845 * job control still works, but terminal signals
846 * (^C, ^Z, ^Y, ^\) won't work at all, and background
847 * process groups can only be created with "cmd &".
848 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
849 * to give tty to the foreground process group,
850 * and will take it back when the group is stopped (^Z)
851 * or killed (^C).
852 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000853#if ENABLE_HUSH_INTERACTIVE
854 /* 'interactive_fd' is a fd# open to ctty, if we have one
855 * _AND_ if we decided to act interactively */
856 int interactive_fd;
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +0200857 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000858# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000859#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000860# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000861#endif
862#if ENABLE_FEATURE_EDITING
863 line_input_t *line_input_state;
864#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000865 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200866 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000867 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200868#if ENABLE_HUSH_RANDOM_SUPPORT
869 random_t random_gen;
870#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000871#if ENABLE_HUSH_JOB
872 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100873 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000874 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000875 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400876# define G_saved_tty_pgrp (G.saved_tty_pgrp)
877#else
878# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000879#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200880 /* How deeply are we in context where "set -e" is ignored */
881 int errexit_depth;
882 /* "set -e" rules (do we follow them correctly?):
883 * Exit if pipe, list, or compound command exits with a non-zero status.
884 * Shell does not exit if failed command is part of condition in
885 * if/while, part of && or || list except the last command, any command
886 * in a pipe but the last, or if the command's return value is being
887 * inverted with !. If a compound command other than a subshell returns a
888 * non-zero status because a command failed while -e was being ignored, the
889 * shell does not exit. A trap on ERR, if set, is executed before the shell
890 * exits [ERR is a bashism].
891 *
892 * If a compound command or function executes in a context where -e is
893 * ignored, none of the commands executed within are affected by the -e
894 * setting. If a compound command or function sets -e while executing in a
895 * context where -e is ignored, that setting does not have any effect until
896 * the compound command or the command containing the function call completes.
897 */
898
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100899 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100900#if ENABLE_HUSH_MODE_X
901# define G_x_mode (G.o_opt[OPT_O_XTRACE])
902#else
903# define G_x_mode 0
904#endif
Denys Vlasenkod8740b22019-05-19 19:11:21 +0200905 char opt_s;
Denys Vlasenkof3634582019-06-03 12:21:04 +0200906 char opt_c;
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200907#if ENABLE_HUSH_INTERACTIVE
908 smallint promptmode; /* 0: PS1, 1: PS2 */
909#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000910 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000911#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000912 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000913#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000914#if ENABLE_HUSH_FUNCTIONS
915 /* 0: outside of a function (or sourced file)
916 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000917 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000918 */
919 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200920# define G_flag_return_in_progress (G.flag_return_in_progress)
921#else
922# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000923#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000924 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100925 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000926 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200927 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200928 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100929#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000930 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000931 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100932# define G_global_args_malloced (G.global_args_malloced)
933#else
934# define G_global_args_malloced 0
935#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100936#if ENABLE_HUSH_BASH_COMPAT
937 int dead_job_exitcode; /* for "wait -n" */
938#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000939 /* how many non-NULL argv's we have. NB: $# + 1 */
940 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000941 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000942#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000943 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000944#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000945#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000946 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000947 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000948#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200949#if ENABLE_HUSH_GETOPTS
950 unsigned getopt_count;
951#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000952 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200953 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000954 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200955 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200956 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200957 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200958 unsigned var_nest_level;
959#if ENABLE_HUSH_FUNCTIONS
960# if ENABLE_HUSH_LOCAL
961 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200962# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200963 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000964#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000965 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200966#if ENABLE_HUSH_FAST
967 unsigned count_SIGCHLD;
968 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200969 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200970#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100971#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200972 unsigned parse_lineno;
973 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100974#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200975 HFILE *HFILE_list;
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
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000991 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100992# define G_traps G.traps
993#else
994# define G_traps ((char**)NULL)
995#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200996 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100997#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000998 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100999#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001000#if ENABLE_HUSH_MODE_X
1001 unsigned x_mode_depth;
1002 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1003 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1004 * for all subsequent output.
1005 */
1006 int x_mode_fd;
1007 o_string x_mode_buf;
1008#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001009#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001011#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001012 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001013 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001014#if BASH_EPOCH_VARS
1015 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1016#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001017#if ENABLE_FEATURE_EDITING
1018 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1019#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001020};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001021#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001022/* Not #defining name to G.name - this quickly gets unwieldy
1023 * (too many defines). Also, I actually prefer to see when a variable
1024 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001025#define INIT_G() do { \
1026 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001027 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1028 sigfillset(&G.sa.sa_mask); \
1029 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001030} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001031
1032
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001033/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001034static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001035#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001036static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001037#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_eval(char **argv) FAST_FUNC;
1039static int builtin_exec(char **argv) FAST_FUNC;
1040static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001041#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001043#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001044#if ENABLE_HUSH_READONLY
1045static int builtin_readonly(char **argv) FAST_FUNC;
1046#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001047#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001048static int builtin_fg_bg(char **argv) FAST_FUNC;
1049static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001050#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001051#if ENABLE_HUSH_GETOPTS
1052static int builtin_getopts(char **argv) FAST_FUNC;
1053#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001054#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001055static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001056#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001057#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001058static int builtin_history(char **argv) FAST_FUNC;
1059#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001060#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001061static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001062#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001063#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001064static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001065#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001066#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001067static int builtin_printf(char **argv) FAST_FUNC;
1068#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001069static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001070#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001071static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001072#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001073#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001074static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001075#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001076static int builtin_shift(char **argv) FAST_FUNC;
1077static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001078#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001079static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001080#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001081#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001082static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001083#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001084#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001085static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001086#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001087#if ENABLE_HUSH_TIMES
1088static int builtin_times(char **argv) FAST_FUNC;
1089#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001090static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001091#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001092static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001093#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001094#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001095static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001096#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001097#if ENABLE_HUSH_KILL
1098static int builtin_kill(char **argv) FAST_FUNC;
1099#endif
1100#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001101static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001102#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001104static int builtin_break(char **argv) FAST_FUNC;
1105static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001107#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001108static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001109#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001110
1111/* Table of built-in functions. They can be forked or not, depending on
1112 * context: within pipes, they fork. As simple commands, they do not.
1113 * When used in non-forking context, they can change global variables
1114 * in the parent shell process. If forked, of course they cannot.
1115 * For example, 'unset foo | whatever' will parse and run, but foo will
1116 * still be set at the end. */
1117struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001118 const char *b_cmd;
1119 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001120#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001121 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001122# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001124# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001125#endif
1126};
1127
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001129 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001130 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001131#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001132 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001133#endif
1134#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001135 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001139 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001140#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001141 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1142 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001143 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001144#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001145 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001146#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001147#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001148 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001149#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001150#if ENABLE_HUSH_GETOPTS
1151 BLTIN("getopts" , builtin_getopts , NULL),
1152#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001153#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001154 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001155#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001156#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001157 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001158#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001159#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001160 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001161#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001162#if ENABLE_HUSH_KILL
1163 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1164#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001165#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001166 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001167#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001168#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001169 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001170#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001171#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001172 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001173#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001174#if ENABLE_HUSH_READONLY
1175 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1176#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001177#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001178 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001179#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001180#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001181 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001182#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001183 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001184#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001185 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001186#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001187#if ENABLE_HUSH_TIMES
1188 BLTIN("times" , builtin_times , NULL),
1189#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001190#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001191 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001192#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001193 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001194#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001195 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001196#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001197#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001198 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001199#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001200#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001201 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001202#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001203#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001204 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001205#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001206#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001207 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001208#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001209};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001210/* These builtins won't be used if we are on NOMMU and need to re-exec
1211 * (it's cheaper to run an external program in this case):
1212 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001213static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001214#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001215 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001216#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001217#if BASH_TEST2
1218 BLTIN("[[" , builtin_test , NULL),
1219#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001220#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001221 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001222#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001223#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001224 BLTIN("printf" , builtin_printf , NULL),
1225#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001226 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001227#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001228 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001229#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001230};
1231
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001232
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001233/* Debug printouts.
1234 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001235#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001236/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001237# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001238# define debug_enter() (G.debug_indent++)
1239# define debug_leave() (G.debug_indent--)
1240#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001241# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001242# define debug_enter() ((void)0)
1243# define debug_leave() ((void)0)
1244#endif
1245
1246#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001247# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248#endif
1249
1250#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001251# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001252#endif
1253
Denys Vlasenko3675c372018-07-23 16:31:21 +02001254#ifndef debug_printf_heredoc
1255# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1256#endif
1257
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001259#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001260#endif
1261
1262#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001263# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#endif
1265
1266#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001267# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001268# define DEBUG_JOBS 1
1269#else
1270# define DEBUG_JOBS 0
1271#endif
1272
1273#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001274# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001275# define DEBUG_EXPAND 1
1276#else
1277# define DEBUG_EXPAND 0
1278#endif
1279
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001280#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001281# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001282#endif
1283
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001285# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001286# define DEBUG_GLOB 1
1287#else
1288# define DEBUG_GLOB 0
1289#endif
1290
Denys Vlasenko2db74612017-07-07 22:07:28 +02001291#ifndef debug_printf_redir
1292# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1293#endif
1294
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001295#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001296# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001297#endif
1298
1299#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001300# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001301#endif
1302
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001303#ifndef debug_printf_prompt
1304# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1305#endif
1306
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001307#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001308# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001309# define DEBUG_CLEAN 1
1310#else
1311# define DEBUG_CLEAN 0
1312#endif
1313
1314#if DEBUG_EXPAND
1315static void debug_print_strings(const char *prefix, char **vv)
1316{
1317 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001318 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001319 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001320 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001321}
1322#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001323# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001324#endif
1325
1326
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001327/* Leak hunting. Use hush_leaktool.sh for post-processing.
1328 */
1329#if LEAK_HUNTING
1330static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001331{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001332 void *ptr = xmalloc((size + 0xff) & ~0xff);
1333 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1334 return ptr;
1335}
1336static void *xxrealloc(int lineno, void *ptr, size_t size)
1337{
1338 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1339 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1340 return ptr;
1341}
1342static char *xxstrdup(int lineno, const char *str)
1343{
1344 char *ptr = xstrdup(str);
1345 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1346 return ptr;
1347}
1348static void xxfree(void *ptr)
1349{
1350 fdprintf(2, "free %p\n", ptr);
1351 free(ptr);
1352}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001353# define xmalloc(s) xxmalloc(__LINE__, s)
1354# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1355# define xstrdup(s) xxstrdup(__LINE__, s)
1356# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001357#endif
1358
1359
1360/* Syntax and runtime errors. They always abort scripts.
1361 * In interactive use they usually discard unparsed and/or unexecuted commands
1362 * and return to the prompt.
1363 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1364 */
1365#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001366# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001367# define syntax_error(lineno, msg) syntax_error(msg)
1368# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1369# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1370# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1371# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372#endif
1373
Denys Vlasenko39701202017-08-02 19:44:05 +02001374static void die_if_script(void)
1375{
1376 if (!G_interactive_fd) {
1377 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1378 xfunc_error_retval = G.last_exitcode;
1379 xfunc_die();
1380 }
1381}
1382
1383static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001384{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001385 va_list p;
1386
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001387#if HUSH_DEBUG >= 2
1388 bb_error_msg("hush.c:%u", lineno);
1389#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001390 va_start(p, fmt);
1391 bb_verror_msg(fmt, p, NULL);
1392 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001393 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001394}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001395
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001396static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001397{
1398 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001399 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001401 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001402 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001403}
1404
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001405static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001406{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001407 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001408 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001409}
1410
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001411static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001412{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001413 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001414//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1415// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001416}
1417
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001418static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001419{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001420 char msg[2] = { ch, '\0' };
1421 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001422}
1423
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001424static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001425{
1426 char msg[2];
1427 msg[0] = ch;
1428 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001429#if HUSH_DEBUG >= 2
1430 bb_error_msg("hush.c:%u", lineno);
1431#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001432 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001433 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001434}
1435
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001436#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001437# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001438# undef syntax_error
1439# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001440# undef syntax_error_unterm_ch
1441# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001442# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001443#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001444# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001445# define syntax_error(msg) syntax_error(__LINE__, msg)
1446# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1447# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1448# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1449# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001450#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001451
Denis Vlasenko552433b2009-04-04 19:29:21 +00001452
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001453/* Utility functions
1454 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001455/* Replace each \x with x in place, return ptr past NUL. */
1456static char *unbackslash(char *src)
1457{
Denys Vlasenko71885402009-09-24 01:44:13 +02001458 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001459 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001460 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001461 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001462 if (*src != '\0') {
1463 /* \x -> x */
1464 *dst++ = *src++;
1465 continue;
1466 }
1467 /* else: "\<nul>". Do not delete this backslash.
1468 * Testcase: eval 'echo ok\'
1469 */
1470 *dst++ = '\\';
1471 /* fallthrough */
1472 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001473 if ((*dst++ = *src++) == '\0')
1474 break;
1475 }
1476 return dst;
1477}
1478
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001479static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001480{
1481 int i;
1482 unsigned count1;
1483 unsigned count2;
1484 char **v;
1485
1486 v = strings;
1487 count1 = 0;
1488 if (v) {
1489 while (*v) {
1490 count1++;
1491 v++;
1492 }
1493 }
1494 count2 = 0;
1495 v = add;
1496 while (*v) {
1497 count2++;
1498 v++;
1499 }
1500 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1501 v[count1 + count2] = NULL;
1502 i = count2;
1503 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001504 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001505 return v;
1506}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001507#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001508static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1509{
1510 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1511 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1512 return ptr;
1513}
1514#define add_strings_to_strings(strings, add, need_to_dup) \
1515 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1516#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001517
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001518/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001519static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001520{
1521 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001522 v[0] = add;
1523 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001524 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001525}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001526#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001527static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1528{
1529 char **ptr = add_string_to_strings(strings, add);
1530 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1531 return ptr;
1532}
1533#define add_string_to_strings(strings, add) \
1534 xx_add_string_to_strings(__LINE__, strings, add)
1535#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001536
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001537static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001538{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001539 char **v;
1540
1541 if (!strings)
1542 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001543 v = strings;
1544 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001545 free(*v);
1546 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001547 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001548 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001549}
1550
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001551static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001552{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001553 int newfd;
1554 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001555 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1556 if (newfd >= 0) {
1557 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1558 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1559 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001560 if (errno == EBUSY)
1561 goto repeat;
1562 if (errno == EINTR)
1563 goto repeat;
1564 }
1565 return newfd;
1566}
1567
Denys Vlasenko657e9002017-07-30 23:34:04 +02001568static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001569{
1570 int newfd;
1571 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001572 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001573 if (newfd < 0) {
1574 if (errno == EBUSY)
1575 goto repeat;
1576 if (errno == EINTR)
1577 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001578 /* fd was not open? */
1579 if (errno == EBADF)
1580 return fd;
1581 xfunc_die();
1582 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001583 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1584 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001585 close(fd);
1586 return newfd;
1587}
1588
1589
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001590/* Manipulating HFILEs */
1591static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001592{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001593 HFILE *fp;
1594 int fd;
1595
1596 fd = STDIN_FILENO;
1597 if (name) {
1598 fd = open(name, O_RDONLY | O_CLOEXEC);
1599 if (fd < 0)
1600 return NULL;
1601 if (O_CLOEXEC == 0) /* ancient libc */
1602 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001603 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001604
1605 fp = xmalloc(sizeof(*fp));
1606 fp->is_stdin = (name == NULL);
1607 fp->fd = fd;
1608 fp->cur = fp->end = fp->buf;
1609 fp->next_hfile = G.HFILE_list;
1610 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001611 return fp;
1612}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001613static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001614{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001615 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001616 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001617 HFILE *cur = *pp;
1618 if (cur == fp) {
1619 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001620 break;
1621 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001622 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001623 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001624 if (fp->fd >= 0)
1625 close(fp->fd);
1626 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001627}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001628static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001629{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001630 int n;
1631
1632 if (fp->fd < 0) {
1633 /* Already saw EOF */
1634 return EOF;
1635 }
1636 /* Try to buffer more input */
1637 fp->cur = fp->buf;
1638 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1639 if (n < 0) {
1640 bb_perror_msg("read error");
1641 n = 0;
1642 }
1643 fp->end = fp->buf + n;
1644 if (n == 0) {
1645 /* EOF/error */
1646 close(fp->fd);
1647 fp->fd = -1;
1648 return EOF;
1649 }
1650 return (unsigned char)(*fp->cur++);
1651}
1652/* Inlined for common case of non-empty buffer.
1653 */
1654static ALWAYS_INLINE int hfgetc(HFILE *fp)
1655{
1656 if (fp->cur < fp->end)
1657 return (unsigned char)(*fp->cur++);
1658 /* Buffer empty */
1659 return refill_HFILE_and_getc(fp);
1660}
1661static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1662{
1663 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001664 while (fl) {
1665 if (fd == fl->fd) {
1666 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001667 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001668 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 +02001669 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001670 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001671 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001672 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001673#if ENABLE_HUSH_MODE_X
1674 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1675 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1676 return 1; /* "found and moved" */
1677 }
1678#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001679 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001680}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001681#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001682static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001683{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001684 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001685 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001686 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001687 * It is disastrous if we share memory with a vforked parent.
1688 * I'm not sure we never come here after vfork.
1689 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001690 *
1691 * ">" instead of ">=": we don't close fd#0,
1692 * interactive shell uses hfopen(NULL) as stdin input
1693 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1694 * If we'd close it here, then e.g. interactive "set | sort"
1695 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001696 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001697 if (fl->fd > 0)
1698 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001699 close(fl->fd);
1700 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001701 }
1702}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001703#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001704static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001705{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001706 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001707 while (fl) {
1708 if (fl->fd == fd)
1709 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001710 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001711 }
1712 return 0;
1713}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001714
1715
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001716/* Helpers for setting new $n and restoring them back
1717 */
1718typedef struct save_arg_t {
1719 char *sv_argv0;
1720 char **sv_g_argv;
1721 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001722 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001723} save_arg_t;
1724
1725static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1726{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001727 sv->sv_argv0 = argv[0];
1728 sv->sv_g_argv = G.global_argv;
1729 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001730 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001731
1732 argv[0] = G.global_argv[0]; /* retain $0 */
1733 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001734 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001735
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001736 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001737}
1738
1739static void restore_G_args(save_arg_t *sv, char **argv)
1740{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001741#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001742 if (G.global_args_malloced) {
1743 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001744 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001745 while (*++pp) /* note: does not free $0 */
1746 free(*pp);
1747 free(G.global_argv);
1748 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001749#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001750 argv[0] = sv->sv_argv0;
1751 G.global_argv = sv->sv_g_argv;
1752 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001753 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001754}
1755
1756
Denis Vlasenkod5762932009-03-31 11:22:57 +00001757/* Basic theory of signal handling in shell
1758 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001759 * This does not describe what hush does, rather, it is current understanding
1760 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001761 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1762 *
1763 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1764 * is finished or backgrounded. It is the same in interactive and
1765 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001766 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001767 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001768 * backgrounds (i.e. stops) or kills all members of currently running
1769 * pipe.
1770 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001771 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001772 * or by SIGINT in interactive shell.
1773 *
1774 * Trap handlers will execute even within trap handlers. (right?)
1775 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001776 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1777 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001778 *
1779 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001780 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001781 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001782 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001783 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001784 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001785 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001786 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001787 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001788 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001789 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001790 *
1791 * SIGQUIT: ignore
1792 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001793 * SIGHUP (interactive):
1794 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001795 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001796 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1797 * that all pipe members are stopped. Try this in bash:
1798 * while :; do :; done - ^Z does not background it
1799 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001800 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001801 * of the command line, show prompt. NB: ^C does not send SIGINT
1802 * to interactive shell while shell is waiting for a pipe,
1803 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001804 * Example 1: this waits 5 sec, but does not execute ls:
1805 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1806 * Example 2: this does not wait and does not execute ls:
1807 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1808 * Example 3: this does not wait 5 sec, but executes ls:
1809 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001810 * Example 4: this does not wait and does not execute ls:
1811 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001812 *
1813 * (What happens to signals which are IGN on shell start?)
1814 * (What happens with signal mask on shell start?)
1815 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001816 * Old implementation
1817 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001818 * We use in-kernel pending signal mask to determine which signals were sent.
1819 * We block all signals which we don't want to take action immediately,
1820 * i.e. we block all signals which need to have special handling as described
1821 * above, and all signals which have traps set.
1822 * After each pipe execution, we extract any pending signals via sigtimedwait()
1823 * and act on them.
1824 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001825 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001826 * sigset_t blocked_set: current blocked signal set
1827 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001828 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001829 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001830 * "trap 'cmd' SIGxxx":
1831 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001832 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001833 * unblock signals with special interactive handling
1834 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001835 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001836 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001837 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001838 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001839 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001840 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001841 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001842 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001843 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001844 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001845 * Standard says "When a subshell is entered, traps that are not being ignored
1846 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001847 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001848 *
1849 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001850 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001851 * masked signals are not visible!
1852 *
1853 * New implementation
1854 * ==================
1855 * We record each signal we are interested in by installing signal handler
1856 * for them - a bit like emulating kernel pending signal mask in userspace.
1857 * We are interested in: signals which need to have special handling
1858 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001859 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001860 * After each pipe execution, we extract any pending signals
1861 * and act on them.
1862 *
1863 * unsigned special_sig_mask: a mask of shell-special signals.
1864 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1865 * char *traps[sig] if trap for sig is set (even if it's '').
1866 * sigset_t pending_set: set of sigs we received.
1867 *
1868 * "trap - SIGxxx":
1869 * if sig is in special_sig_mask, set handler back to:
1870 * record_pending_signo, or to IGN if it's a tty stop signal
1871 * if sig is in fatal_sig_mask, set handler back to sigexit.
1872 * else: set handler back to SIG_DFL
1873 * "trap 'cmd' SIGxxx":
1874 * set handler to record_pending_signo.
1875 * "trap '' SIGxxx":
1876 * set handler to SIG_IGN.
1877 * after [v]fork, if we plan to be a shell:
1878 * set signals with special interactive handling to SIG_DFL
1879 * (because child shell is not interactive),
1880 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1881 * after [v]fork, if we plan to exec:
1882 * POSIX says fork clears pending signal mask in child - no need to clear it.
1883 *
1884 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1885 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1886 *
1887 * Note (compat):
1888 * Standard says "When a subshell is entered, traps that are not being ignored
1889 * are set to the default actions". bash interprets it so that traps which
1890 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001891 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001892enum {
1893 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001894 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001895 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001896 | (1 << SIGHUP)
1897 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001898 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001899#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001900 | (1 << SIGTTIN)
1901 | (1 << SIGTTOU)
1902 | (1 << SIGTSTP)
1903#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001904 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001905};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001906
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001907static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001908{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001909 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001910#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001911 if (sig == SIGCHLD) {
1912 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001913//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 +02001914 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001915#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001916}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001917
Denys Vlasenko0806e402011-05-12 23:06:20 +02001918static sighandler_t install_sighandler(int sig, sighandler_t handler)
1919{
1920 struct sigaction old_sa;
1921
1922 /* We could use signal() to install handlers... almost:
1923 * except that we need to mask ALL signals while handlers run.
1924 * I saw signal nesting in strace, race window isn't small.
1925 * SA_RESTART is also needed, but in Linux, signal()
1926 * sets SA_RESTART too.
1927 */
1928 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1929 /* sigfillset(&G.sa.sa_mask); - already done */
1930 /* G.sa.sa_flags = SA_RESTART; - already done */
1931 G.sa.sa_handler = handler;
1932 sigaction(sig, &G.sa, &old_sa);
1933 return old_sa.sa_handler;
1934}
1935
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001936static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001937
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001938static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001939static void restore_ttypgrp_and__exit(void)
1940{
1941 /* xfunc has failed! die die die */
1942 /* no EXIT traps, this is an escape hatch! */
1943 G.exiting = 1;
1944 hush_exit(xfunc_error_retval);
1945}
1946
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001947#if ENABLE_HUSH_JOB
1948
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001949/* Needed only on some libc:
1950 * It was observed that on exit(), fgetc'ed buffered data
1951 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1952 * With the net effect that even after fork(), not vfork(),
1953 * exit() in NOEXECed applet in "sh SCRIPT":
1954 * noexec_applet_here
1955 * echo END_OF_SCRIPT
1956 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1957 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001958 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001959 * and in `cmd` handling.
1960 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1961 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001962static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001963static void fflush_and__exit(void)
1964{
1965 fflush_all();
1966 _exit(xfunc_error_retval);
1967}
1968
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001969/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001970# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001971/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001972# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001973
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001974/* Restores tty foreground process group, and exits.
1975 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001976 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001977 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001978 * We also call it if xfunc is exiting.
1979 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001980static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001981static void sigexit(int sig)
1982{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001983 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001984 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001985 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1986 /* Disable all signals: job control, SIGPIPE, etc.
1987 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1988 */
1989 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001990 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001991 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001992
1993 /* Not a signal, just exit */
1994 if (sig <= 0)
1995 _exit(- sig);
1996
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001997 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001998}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001999#else
2000
Denys Vlasenko8391c482010-05-22 17:50:43 +02002001# define disable_restore_tty_pgrp_on_exit() ((void)0)
2002# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002003
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002004#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002005
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002006static sighandler_t pick_sighandler(unsigned sig)
2007{
2008 sighandler_t handler = SIG_DFL;
2009 if (sig < sizeof(unsigned)*8) {
2010 unsigned sigmask = (1 << sig);
2011
2012#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002013 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002014 if (G_fatal_sig_mask & sigmask)
2015 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002016 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002017#endif
2018 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002019 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002020 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002021 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002022 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002023 * in an endless loop when we try to do some
2024 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002025 */
2026 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2027 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002028 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002029 }
2030 return handler;
2031}
2032
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002033/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002034static void hush_exit(int exitcode)
2035{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002036#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko76a4e832019-05-19 18:24:52 +02002037 if (G.line_input_state)
2038 save_history(G.line_input_state);
Denys Vlasenkobede2152011-09-04 16:12:33 +02002039#endif
2040
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002041 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002042 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002043 char *argv[3];
2044 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002045 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002046 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002047 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002048 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002049 * "trap" will still show it, if executed
2050 * in the handler */
2051 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002052 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002053
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002054#if ENABLE_FEATURE_CLEAN_UP
2055 {
2056 struct variable *cur_var;
2057 if (G.cwd != bb_msg_unknown)
2058 free((char*)G.cwd);
2059 cur_var = G.top_var;
2060 while (cur_var) {
2061 struct variable *tmp = cur_var;
2062 if (!cur_var->max_len)
2063 free(cur_var->varstr);
2064 cur_var = cur_var->next;
2065 free(tmp);
2066 }
2067 }
2068#endif
2069
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002070 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002071#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002072 sigexit(- (exitcode & 0xff));
2073#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002074 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002075#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002076}
2077
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002078
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002079//TODO: return a mask of ALL handled sigs?
2080static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002081{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002082 int last_sig = 0;
2083
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002084 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002085 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002086
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002087 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002088 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002089 sig = 0;
2090 do {
2091 sig++;
2092 if (sigismember(&G.pending_set, sig)) {
2093 sigdelset(&G.pending_set, sig);
2094 goto got_sig;
2095 }
2096 } while (sig < NSIG);
2097 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002098 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002099 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002100 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002101 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002102 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002103 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002104 char *argv[3];
2105 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002106 argv[1] = xstrdup(G_traps[sig]);
2107 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002108 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002109 save_rcode = G.last_exitcode;
2110 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002111 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002112//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002113 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002114 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002115 } /* else: "" trap, ignoring signal */
2116 continue;
2117 }
2118 /* not a trap: special action */
2119 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002120 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002121 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002122 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002123 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002124 break;
2125#if ENABLE_HUSH_JOB
2126 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002127//TODO: why are we doing this? ash and dash don't do this,
2128//they have no handler for SIGHUP at all,
2129//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002130 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002131 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002132 /* bash is observed to signal whole process groups,
2133 * not individual processes */
2134 for (job = G.job_list; job; job = job->next) {
2135 if (job->pgrp <= 0)
2136 continue;
2137 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2138 if (kill(- job->pgrp, SIGHUP) == 0)
2139 kill(- job->pgrp, SIGCONT);
2140 }
2141 sigexit(SIGHUP);
2142 }
2143#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002144#if ENABLE_HUSH_FAST
2145 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002146 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002147 G.count_SIGCHLD++;
2148//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2149 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002150 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002151 * This simplifies wait builtin a bit.
2152 */
2153 break;
2154#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002155 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002156 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002157 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002158 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002159 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002160 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002161 * in interactive shell, because TERM is ignored.
2162 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002163 break;
2164 }
2165 }
2166 return last_sig;
2167}
2168
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002169
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002170static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002171{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002172 if (force || G.cwd == NULL) {
2173 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2174 * we must not try to free(bb_msg_unknown) */
2175 if (G.cwd == bb_msg_unknown)
2176 G.cwd = NULL;
2177 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2178 if (!G.cwd)
2179 G.cwd = bb_msg_unknown;
2180 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002181 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002182}
2183
Denis Vlasenko83506862007-11-23 13:11:42 +00002184
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002185/*
2186 * Shell and environment variable support
2187 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002188static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002189{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002190 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002191 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002192
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002193 pp = &G.top_var;
2194 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002195 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002196 return pp;
2197 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198 }
2199 return NULL;
2200}
2201
Denys Vlasenko03dad222010-01-12 23:29:57 +01002202static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002203{
Denys Vlasenko29082232010-07-16 13:52:32 +02002204 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002205 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002206
2207 if (G.expanded_assignments) {
2208 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002209 while (*cpp) {
2210 char *cp = *cpp;
2211 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2212 return cp + len + 1;
2213 cpp++;
2214 }
2215 }
2216
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002217 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002218 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002219 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002220
Denys Vlasenkodea47882009-10-09 15:40:49 +02002221 if (strcmp(name, "PPID") == 0)
2222 return utoa(G.root_ppid);
2223 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002224#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002225 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002226 return utoa(next_random(&G.random_gen));
2227#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002228#if ENABLE_HUSH_LINENO_VAR
2229 if (strcmp(name, "LINENO") == 0)
2230 return utoa(G.execute_lineno);
2231#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002232#if BASH_EPOCH_VARS
2233 {
2234 const char *fmt = NULL;
2235 if (strcmp(name, "EPOCHSECONDS") == 0)
2236 fmt = "%lu";
2237 else if (strcmp(name, "EPOCHREALTIME") == 0)
2238 fmt = "%lu.%06u";
2239 if (fmt) {
2240 struct timeval tv;
2241 gettimeofday(&tv, NULL);
2242 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2243 (unsigned)tv.tv_usec);
2244 return G.epoch_buf;
2245 }
2246 }
2247#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248 return NULL;
2249}
2250
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002251#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002252static void handle_changed_special_names(const char *name, unsigned name_len)
2253{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002254 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002255 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002256 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002257 return;
2258 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002259 }
2260}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002261#else
2262/* Do not even bother evaluating arguments */
2263# define handle_changed_special_names(...) ((void)0)
2264#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002265
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002267 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002268 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002269#define SETFLAG_EXPORT (1 << 0)
2270#define SETFLAG_UNEXPORT (1 << 1)
2271#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002272#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002273static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002274{
Denys Vlasenko61407802018-04-04 21:14:28 +02002275 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002276 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002277 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002278 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002279 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002280 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002281 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002282
Denis Vlasenko950bd722009-04-21 11:23:56 +00002283 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002284 if (HUSH_DEBUG && !eq_sign)
2285 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002286
Denis Vlasenko950bd722009-04-21 11:23:56 +00002287 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002288 cur_pp = &G.top_var;
2289 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002290 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002291 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002292 continue;
2293 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002294
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002295 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002296 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002297 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002298 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002299//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2300//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002301 return -1;
2302 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002303 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002304 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2305 *eq_sign = '\0';
2306 unsetenv(str);
2307 *eq_sign = '=';
2308 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002309 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002310 /* bash 3.2.33(1) and exported vars:
2311 * # export z=z
2312 * # f() { local z=a; env | grep ^z; }
2313 * # f
2314 * z=a
2315 * # env | grep ^z
2316 * z=z
2317 */
2318 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002319 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002320 /* New variable is local ("local VAR=VAL" or
2321 * "VAR=VAL cmd")
2322 * and existing one is global, or local
2323 * on a lower level that new one.
2324 * Remove it from global variable list:
2325 */
2326 *cur_pp = cur->next;
2327 if (G.shadowed_vars_pp) {
2328 /* Save in "shadowed" list */
2329 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2330 cur->flg_export ? "exported " : "",
2331 cur->varstr, cur->var_nest_level, str, local_lvl
2332 );
2333 cur->next = *G.shadowed_vars_pp;
2334 *G.shadowed_vars_pp = cur;
2335 } else {
2336 /* Came from pseudo_exec_argv(), no need to save: delete it */
2337 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2338 cur->flg_export ? "exported " : "",
2339 cur->varstr, cur->var_nest_level, str, local_lvl
2340 );
2341 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2342 free_me = cur->varstr; /* then free it later */
2343 free(cur);
2344 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002345 break;
2346 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002347
Denis Vlasenko950bd722009-04-21 11:23:56 +00002348 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002349 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002350 free_and_exp:
2351 free(str);
2352 goto exp;
2353 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002354
2355 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002356 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002357 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002358 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002359 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002360 strcpy(cur->varstr, str);
2361 goto free_and_exp;
2362 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002363 /* Can't reuse */
2364 cur->max_len = 0;
2365 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002366 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002367 /* max_len == 0 signifies "malloced" var, which we can
2368 * (and have to) free. But we can't free(cur->varstr) here:
2369 * if cur->flg_export is 1, it is in the environment.
2370 * We should either unsetenv+free, or wait until putenv,
2371 * then putenv(new)+free(old).
2372 */
2373 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002374 goto set_str_and_exp;
2375 }
2376
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002377 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002378 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002379 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002380 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002381 cur->next = *cur_pp;
2382 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002383
2384 set_str_and_exp:
2385 cur->varstr = str;
2386 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002387#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002388 if (flags & SETFLAG_MAKE_RO) {
2389 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002390 }
2391#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002392 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002393 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002394 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002395 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002396 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002397 cur->flg_export = 0;
2398 /* unsetenv was already done */
2399 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002400 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002401 retval = putenv(cur->varstr);
2402 /* fall through to "free(free_me)" -
2403 * only now we can free old exported malloced string
2404 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002405 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002406 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002407 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002408
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002409 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002410
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002411 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002412}
2413
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002414static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2415{
2416 char *var = xasprintf("%s=%s", name, val);
2417 set_local_var(var, /*flag:*/ 0);
2418}
2419
Denys Vlasenko6db47842009-09-05 20:15:17 +02002420/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002421static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002422{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002423 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002424}
2425
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002426#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002427static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002428{
2429 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002430 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002431
Denys Vlasenko61407802018-04-04 21:14:28 +02002432 cur_pp = &G.top_var;
2433 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002434 if (strncmp(cur->varstr, name, name_len) == 0
2435 && cur->varstr[name_len] == '='
2436 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002437 if (cur->flg_read_only) {
2438 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002439 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002440 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002441
Denys Vlasenko61407802018-04-04 21:14:28 +02002442 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002443 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2444 bb_unsetenv(cur->varstr);
2445 if (!cur->max_len)
2446 free(cur->varstr);
2447 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002448
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002449 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002450 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002451 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002452 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002453
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002454 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002455 handle_changed_special_names(name, name_len);
2456
Mike Frysingerd690f682009-03-30 06:50:54 +00002457 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002458}
2459
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002460static int unset_local_var(const char *name)
2461{
2462 return unset_local_var_len(name, strlen(name));
2463}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002464#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002465
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002466
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002467/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002468 * Helpers for "var1=val1 var2=val2 cmd" feature
2469 */
2470static void add_vars(struct variable *var)
2471{
2472 struct variable *next;
2473
2474 while (var) {
2475 next = var->next;
2476 var->next = G.top_var;
2477 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002478 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002479 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002480 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002481 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002482 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002483 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002484 var = next;
2485 }
2486}
2487
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002488/* We put strings[i] into variable table and possibly putenv them.
2489 * If variable is read only, we can free the strings[i]
2490 * which attempts to overwrite it.
2491 * The strings[] vector itself is freed.
2492 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002493static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002494{
2495 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002496
2497 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002498 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002499
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002500 s = strings;
2501 while (*s) {
2502 struct variable *var_p;
2503 struct variable **var_pp;
2504 char *eq;
2505
2506 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002507 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002508 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002509 var_pp = get_ptr_to_local_var(*s, eq - *s);
2510 if (var_pp) {
2511 var_p = *var_pp;
2512 if (var_p->flg_read_only) {
2513 char **p;
2514 bb_error_msg("%s: readonly variable", *s);
2515 /*
2516 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2517 * If VAR is readonly, leaving it in the list
2518 * after asssignment error (msg above)
2519 * causes doubled error message later, on unset.
2520 */
2521 debug_printf_env("removing/freeing '%s' element\n", *s);
2522 free(*s);
2523 p = s;
2524 do { *p = p[1]; p++; } while (*p);
2525 goto next;
2526 }
2527 /* below, set_local_var() with nest level will
2528 * "shadow" (remove) this variable from
2529 * global linked list.
2530 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002531 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002532 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2533 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002534 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002535 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002536 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002537 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002538}
2539
2540
2541/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002542 * Unicode helper
2543 */
2544static void reinit_unicode_for_hush(void)
2545{
2546 /* Unicode support should be activated even if LANG is set
2547 * _during_ shell execution, not only if it was set when
2548 * shell was started. Therefore, re-check LANG every time:
2549 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002550 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2551 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002552 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002553 const char *s = get_local_var_value("LC_ALL");
2554 if (!s) s = get_local_var_value("LC_CTYPE");
2555 if (!s) s = get_local_var_value("LANG");
2556 reinit_unicode(s);
2557 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002558}
2559
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002560/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002561 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002562 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002563
2564#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002565/* To test correct lineedit/interactive behavior, type from command line:
2566 * echo $P\
2567 * \
2568 * AT\
2569 * H\
2570 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002571 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002572 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002573static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002574{
2575 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002576
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002577 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002578
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002579# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2580 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2581 if (!prompt_str)
2582 prompt_str = "";
2583# else
2584 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002585 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002586 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2587 free(G.PS1);
2588 /* bash uses $PWD value, even if it is set by user.
2589 * It uses current dir only if PWD is unset.
2590 * We always use current dir. */
2591 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002592 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002593# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002594 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002595 return prompt_str;
2596}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002597static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002598{
2599 int r;
2600 const char *prompt_str;
2601
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002602 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002603# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002604 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002605 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002606 if (G.flag_SIGINT) {
2607 /* There was ^C'ed, make it look prettier: */
2608 bb_putchar('\n');
2609 G.flag_SIGINT = 0;
2610 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002611 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002612 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002613 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002614 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002615 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002616 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002617 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002618 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002619 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002620 if (r != 0 && !G.flag_SIGINT)
2621 break;
2622 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002623 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2624 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002625 G.last_exitcode = 128 + SIGINT;
2626 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002627 if (r < 0) {
2628 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002629 i->p = NULL;
2630 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002631 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002633 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002634 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002635# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002636 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002637 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002638 if (i->last_char == '\0' || i->last_char == '\n') {
2639 /* Why check_and_run_traps here? Try this interactively:
2640 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2641 * $ <[enter], repeatedly...>
2642 * Without check_and_run_traps, handler never runs.
2643 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002644 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002645 fputs(prompt_str, stdout);
2646 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002647 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002648//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002649 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002650 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2651 * no ^C masking happens during fgetc, no special code for ^C:
2652 * it generates SIGINT as usual.
2653 */
2654 check_and_run_traps();
2655 if (G.flag_SIGINT)
2656 G.last_exitcode = 128 + SIGINT;
2657 if (r != '\0')
2658 break;
2659 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002660 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002661# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002662}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663/* This is the magic location that prints prompts
2664 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002665static int fgetc_interactive(struct in_str *i)
2666{
2667 int ch;
2668 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002669 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002670 /* Returns first char (or EOF), the rest is in i->p[] */
2671 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002672 G.promptmode = 1; /* PS2 */
2673 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002674 } else {
2675 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002676 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002677 }
2678 return ch;
2679}
2680#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002681static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002682{
2683 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002684 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002685 return ch;
2686}
2687#endif /* INTERACTIVE */
2688
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002689static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002690{
2691 int ch;
2692
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002693 if (!i->file) {
2694 /* string-based in_str */
2695 ch = (unsigned char)*i->p;
2696 if (ch != '\0') {
2697 i->p++;
2698 i->last_char = ch;
2699 return ch;
2700 }
2701 return EOF;
2702 }
2703
2704 /* FILE-based in_str */
2705
Denys Vlasenko4074d492016-09-30 01:49:53 +02002706#if ENABLE_FEATURE_EDITING
2707 /* This can be stdin, check line editing char[] buffer */
2708 if (i->p && *i->p != '\0') {
2709 ch = (unsigned char)*i->p++;
2710 goto out;
2711 }
2712#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002713 /* peek_buf[] is an int array, not char. Can contain EOF. */
2714 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002715 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002716 int ch2 = i->peek_buf[1];
2717 i->peek_buf[0] = ch2;
2718 if (ch2 == 0) /* very likely, avoid redundant write */
2719 goto out;
2720 i->peek_buf[1] = 0;
2721 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002722 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002723
Denys Vlasenko4074d492016-09-30 01:49:53 +02002724 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002725 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002726 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002727 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002728#if ENABLE_HUSH_LINENO_VAR
2729 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002730 G.parse_lineno++;
2731 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002732 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002733#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002734 return ch;
2735}
2736
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002737static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002738{
2739 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002740
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002741 if (!i->file) {
2742 /* string-based in_str */
2743 /* Doesn't report EOF on NUL. None of the callers care. */
2744 return (unsigned char)*i->p;
2745 }
2746
2747 /* FILE-based in_str */
2748
Denys Vlasenko4074d492016-09-30 01:49:53 +02002749#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002750 /* This can be stdin, check line editing char[] buffer */
2751 if (i->p && *i->p != '\0')
2752 return (unsigned char)*i->p;
2753#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002754 /* peek_buf[] is an int array, not char. Can contain EOF. */
2755 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002756 if (ch != 0)
2757 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002758
Denys Vlasenko4074d492016-09-30 01:49:53 +02002759 /* Need to get a new char */
2760 ch = fgetc_interactive(i);
2761 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2762
2763 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2764#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2765 if (i->p) {
2766 i->p -= 1;
2767 return ch;
2768 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002769#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002770 i->peek_buf[0] = ch;
2771 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002772 return ch;
2773}
2774
Denys Vlasenko4074d492016-09-30 01:49:53 +02002775/* Only ever called if i_peek() was called, and did not return EOF.
2776 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2777 * not end-of-line. Therefore we never need to read a new editing line here.
2778 */
2779static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002780{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002781 int ch;
2782
2783 /* There are two cases when i->p[] buffer exists.
2784 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002785 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002786 * In both cases, we know that i->p[0] exists and not NUL, and
2787 * the peek2 result is in i->p[1].
2788 */
2789 if (i->p)
2790 return (unsigned char)i->p[1];
2791
2792 /* Now we know it is a file-based in_str. */
2793
2794 /* peek_buf[] is an int array, not char. Can contain EOF. */
2795 /* Is there 2nd char? */
2796 ch = i->peek_buf[1];
2797 if (ch == 0) {
2798 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002799 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002800 i->peek_buf[1] = ch;
2801 }
2802
2803 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2804 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002805}
2806
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002807static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2808{
2809 for (;;) {
2810 int ch, ch2;
2811
2812 ch = i_getch(input);
2813 if (ch != '\\')
2814 return ch;
2815 ch2 = i_peek(input);
2816 if (ch2 != '\n')
2817 return ch;
2818 /* backslash+newline, skip it */
2819 i_getch(input);
2820 }
2821}
2822
2823/* Note: this function _eats_ \<newline> pairs, safe to use plain
2824 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2825 */
2826static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2827{
2828 for (;;) {
2829 int ch, ch2;
2830
2831 ch = i_peek(input);
2832 if (ch != '\\')
2833 return ch;
2834 ch2 = i_peek2(input);
2835 if (ch2 != '\n')
2836 return ch;
2837 /* backslash+newline, skip it */
2838 i_getch(input);
2839 i_getch(input);
2840 }
2841}
2842
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002843static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002844{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002845 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002846 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002847 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002848}
2849
2850static void setup_string_in_str(struct in_str *i, const char *s)
2851{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002852 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002853 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002854 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002855}
2856
2857
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002858/*
2859 * o_string support
2860 */
2861#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002862
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002863static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002864{
2865 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002866 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002867 if (o->data)
2868 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002869}
2870
Denys Vlasenko18567402018-07-20 17:51:31 +02002871static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002872{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002873 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002874 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002875}
2876
Denys Vlasenko18567402018-07-20 17:51:31 +02002877static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002878{
2879 free(o->data);
2880}
2881
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002882static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002883{
2884 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002885 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002886 o->data = xrealloc(o->data, 1 + o->maxlen);
2887 }
2888}
2889
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002890static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002891{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002892 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002893 if (o->length < o->maxlen) {
2894 /* likely. avoid o_grow_by() call */
2895 add:
2896 o->data[o->length] = ch;
2897 o->length++;
2898 o->data[o->length] = '\0';
2899 return;
2900 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002901 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002902 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002903}
2904
Denys Vlasenko657086a2016-09-29 18:07:42 +02002905#if 0
2906/* Valid only if we know o_string is not empty */
2907static void o_delchr(o_string *o)
2908{
2909 o->length--;
2910 o->data[o->length] = '\0';
2911}
2912#endif
2913
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002914static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002915{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002916 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002917 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002918 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002919}
2920
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002921static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002922{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002923 o_addblock(o, str, strlen(str));
2924}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002925
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002926static void o_addstr_with_NUL(o_string *o, const char *str)
2927{
2928 o_addblock(o, str, strlen(str) + 1);
2929}
2930
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002931#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002932static void nommu_addchr(o_string *o, int ch)
2933{
2934 if (o)
2935 o_addchr(o, ch);
2936}
2937#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002938# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002939#endif
2940
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002941#if ENABLE_HUSH_MODE_X
2942static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002943{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002944 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002945}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002946static void x_mode_addstr(const char *str)
2947{
2948 o_addstr(&G.x_mode_buf, str);
2949}
2950static void x_mode_addblock(const char *str, int len)
2951{
2952 o_addblock(&G.x_mode_buf, str, len);
2953}
2954static void x_mode_prefix(void)
2955{
2956 int n = G.x_mode_depth;
2957 do x_mode_addchr('+'); while (--n >= 0);
2958}
2959static void x_mode_flush(void)
2960{
2961 int len = G.x_mode_buf.length;
2962 if (len <= 0)
2963 return;
2964 if (G.x_mode_fd > 0) {
2965 G.x_mode_buf.data[len] = '\n';
2966 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2967 }
2968 G.x_mode_buf.length = 0;
2969}
2970#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002971
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002972/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002973 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002974 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2975 * Apparently, on unquoted $v bash still does globbing
2976 * ("v='*.txt'; echo $v" prints all .txt files),
2977 * but NOT brace expansion! Thus, there should be TWO independent
2978 * quoting mechanisms on $v expansion side: one protects
2979 * $v from brace expansion, and other additionally protects "$v" against globbing.
2980 * We have only second one.
2981 */
2982
Denys Vlasenko9e800222010-10-03 14:28:04 +02002983#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002984# define MAYBE_BRACES "{}"
2985#else
2986# define MAYBE_BRACES ""
2987#endif
2988
Eric Andersen25f27032001-04-26 23:22:31 +00002989/* My analysis of quoting semantics tells me that state information
2990 * is associated with a destination, not a source.
2991 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002992static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002993{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002994 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002995 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002996 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002997 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002998 o_grow_by(o, sz);
2999 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003000 o->data[o->length] = '\\';
3001 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003002 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003003 o->data[o->length] = ch;
3004 o->length++;
3005 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003006}
3007
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003008static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003009{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003010 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003011 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3012 && strchr("*?[\\" MAYBE_BRACES, ch)
3013 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003014 sz++;
3015 o->data[o->length] = '\\';
3016 o->length++;
3017 }
3018 o_grow_by(o, sz);
3019 o->data[o->length] = ch;
3020 o->length++;
3021 o->data[o->length] = '\0';
3022}
3023
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003024static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003025{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003026 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003027 char ch;
3028 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003029 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003030 if (ordinary_cnt > len) /* paranoia */
3031 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003032 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003033 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003034 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003035 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003036 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003037
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003038 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003039 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003040 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003041 sz++;
3042 o->data[o->length] = '\\';
3043 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003044 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003045 o_grow_by(o, sz);
3046 o->data[o->length] = ch;
3047 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003048 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003049 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003050}
3051
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003052static void o_addQblock(o_string *o, const char *str, int len)
3053{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003054 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003055 o_addblock(o, str, len);
3056 return;
3057 }
3058 o_addqblock(o, str, len);
3059}
3060
Denys Vlasenko38292b62010-09-05 14:49:40 +02003061static void o_addQstr(o_string *o, const char *str)
3062{
3063 o_addQblock(o, str, strlen(str));
3064}
3065
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003066/* A special kind of o_string for $VAR and `cmd` expansion.
3067 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003068 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003069 * list[i] contains an INDEX (int!) into this string data.
3070 * It means that if list[] needs to grow, data needs to be moved higher up
3071 * but list[i]'s need not be modified.
3072 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003073 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003074 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3075 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003076#if DEBUG_EXPAND || DEBUG_GLOB
3077static void debug_print_list(const char *prefix, o_string *o, int n)
3078{
3079 char **list = (char**)o->data;
3080 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3081 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003082
3083 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003084 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 +02003085 prefix, list, n, string_start, o->length, o->maxlen,
3086 !!(o->o_expflags & EXP_FLAG_GLOB),
3087 o->has_quoted_part,
3088 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003089 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003090 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003091 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3092 o->data + (int)(uintptr_t)list[i] + string_start,
3093 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003094 i++;
3095 }
3096 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003097 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003098 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003099 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003100 }
3101}
3102#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003103# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003104#endif
3105
3106/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3107 * in list[n] so that it points past last stored byte so far.
3108 * It returns n+1. */
3109static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003110{
3111 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003112 int string_start;
3113 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003114
3115 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003116 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3117 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003118 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003119 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003120 /* list[n] points to string_start, make space for 16 more pointers */
3121 o->maxlen += 0x10 * sizeof(list[0]);
3122 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003123 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003124 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003125 /*
3126 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3127 * check. (grep for -prev-ifs-check-).
3128 * Ensure that argv[-1][last] is not garbage
3129 * but zero bytes, to save index check there.
3130 */
3131 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003132 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003133 } else {
3134 debug_printf_list("list[%d]=%d string_start=%d\n",
3135 n, string_len, string_start);
3136 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003137 } else {
3138 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003139 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3140 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003141 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3142 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003143 o->has_empty_slot = 0;
3144 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003145 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003146 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003147 return n + 1;
3148}
3149
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003150/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003151static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003152{
3153 char **list = (char**)o->data;
3154 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3155
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003156 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003157}
3158
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003159/*
3160 * Globbing routines.
3161 *
3162 * Most words in commands need to be globbed, even ones which are
3163 * (single or double) quoted. This stems from the possiblity of
3164 * constructs like "abc"* and 'abc'* - these should be globbed.
3165 * Having a different code path for fully-quoted strings ("abc",
3166 * 'abc') would only help performance-wise, but we still need
3167 * code for partially-quoted strings.
3168 *
3169 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003170 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003171 * to a string, then globbed, and if globbing does not match anything,
3172 * it is used verbatim". Here are two examples where it fails:
3173 *
3174 * echo 'b\*'?
3175 *
3176 * The globbing can't be avoided (because of '?' at the end).
3177 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3178 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003179 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003180 * Now, look at this:
3181 *
3182 * v='\\\*'; echo b$v?
3183 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003184 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003185 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003186 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003187 *
3188 * ash implements this by having an encoded representation of the word
3189 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3190 * Glob pattern is derived from it. If glob fails, the decision what result
3191 * should be is made using that encoded representation. Not glob pattern.
3192 */
3193
Denys Vlasenko9e800222010-10-03 14:28:04 +02003194#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003195/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3196 * first, it processes even {a} (no commas), second,
3197 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003198 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003199 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003200
3201/* Helper */
3202static int glob_needed(const char *s)
3203{
3204 while (*s) {
3205 if (*s == '\\') {
3206 if (!s[1])
3207 return 0;
3208 s += 2;
3209 continue;
3210 }
3211 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3212 return 1;
3213 s++;
3214 }
3215 return 0;
3216}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003217/* Return pointer to next closing brace or to comma */
3218static const char *next_brace_sub(const char *cp)
3219{
3220 unsigned depth = 0;
3221 cp++;
3222 while (*cp != '\0') {
3223 if (*cp == '\\') {
3224 if (*++cp == '\0')
3225 break;
3226 cp++;
3227 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003228 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003229 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003230 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003231 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003232 depth++;
3233 }
3234
3235 return *cp != '\0' ? cp : NULL;
3236}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003237/* Recursive brace globber. Note: may garble pattern[]. */
3238static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003239{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003240 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003241 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003242 const char *next;
3243 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003244 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003245 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003246
3247 debug_printf_glob("glob_brace('%s')\n", pattern);
3248
3249 begin = pattern;
3250 while (1) {
3251 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003252 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003253 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003254 /* Find the first sub-pattern and at the same time
3255 * find the rest after the closing brace */
3256 next = next_brace_sub(begin);
3257 if (next == NULL) {
3258 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003259 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003260 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003261 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003262 /* "{abc}" with no commas - illegal
3263 * brace expr, disregard and skip it */
3264 begin = next + 1;
3265 continue;
3266 }
3267 break;
3268 }
3269 if (*begin == '\\' && begin[1] != '\0')
3270 begin++;
3271 begin++;
3272 }
3273 debug_printf_glob("begin:%s\n", begin);
3274 debug_printf_glob("next:%s\n", next);
3275
3276 /* Now find the end of the whole brace expression */
3277 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003278 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003279 rest = next_brace_sub(rest);
3280 if (rest == NULL) {
3281 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003282 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003283 }
3284 debug_printf_glob("rest:%s\n", rest);
3285 }
3286 rest_len = strlen(++rest) + 1;
3287
3288 /* We are sure the brace expression is well-formed */
3289
3290 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003291 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003292
3293 /* We have a brace expression. BEGIN points to the opening {,
3294 * NEXT points past the terminator of the first element, and REST
3295 * points past the final }. We will accumulate result names from
3296 * recursive runs for each brace alternative in the buffer using
3297 * GLOB_APPEND. */
3298
3299 p = begin + 1;
3300 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003301 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003302 memcpy(
3303 mempcpy(
3304 mempcpy(new_pattern_buf,
3305 /* We know the prefix for all sub-patterns */
3306 pattern, begin - pattern),
3307 p, next - p),
3308 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003309
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003310 /* Note: glob_brace() may garble new_pattern_buf[].
3311 * That's why we re-copy prefix every time (1st memcpy above).
3312 */
3313 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003314 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003315 /* We saw the last entry */
3316 break;
3317 }
3318 p = next + 1;
3319 next = next_brace_sub(next);
3320 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003321 free(new_pattern_buf);
3322 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003323
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003324 simple_glob:
3325 {
3326 int gr;
3327 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003328
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003329 memset(&globdata, 0, sizeof(globdata));
3330 gr = glob(pattern, 0, NULL, &globdata);
3331 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3332 if (gr != 0) {
3333 if (gr == GLOB_NOMATCH) {
3334 globfree(&globdata);
3335 /* NB: garbles parameter */
3336 unbackslash(pattern);
3337 o_addstr_with_NUL(o, pattern);
3338 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3339 return o_save_ptr_helper(o, n);
3340 }
3341 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003342 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003343 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3344 * but we didn't specify it. Paranoia again. */
3345 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3346 }
3347 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3348 char **argv = globdata.gl_pathv;
3349 while (1) {
3350 o_addstr_with_NUL(o, *argv);
3351 n = o_save_ptr_helper(o, n);
3352 argv++;
3353 if (!*argv)
3354 break;
3355 }
3356 }
3357 globfree(&globdata);
3358 }
3359 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003360}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003361/* Performs globbing on last list[],
3362 * saving each result as a new list[].
3363 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003364static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003365{
3366 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003367
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003368 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003369 if (!o->data)
3370 return o_save_ptr_helper(o, n);
3371 pattern = o->data + o_get_last_ptr(o, n);
3372 debug_printf_glob("glob pattern '%s'\n", pattern);
3373 if (!glob_needed(pattern)) {
3374 /* unbackslash last string in o in place, fix length */
3375 o->length = unbackslash(pattern) - o->data;
3376 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3377 return o_save_ptr_helper(o, n);
3378 }
3379
3380 copy = xstrdup(pattern);
3381 /* "forget" pattern in o */
3382 o->length = pattern - o->data;
3383 n = glob_brace(copy, o, n);
3384 free(copy);
3385 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003386 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003387 return n;
3388}
3389
Denys Vlasenko238081f2010-10-03 14:26:26 +02003390#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003391
3392/* Helper */
3393static int glob_needed(const char *s)
3394{
3395 while (*s) {
3396 if (*s == '\\') {
3397 if (!s[1])
3398 return 0;
3399 s += 2;
3400 continue;
3401 }
3402 if (*s == '*' || *s == '[' || *s == '?')
3403 return 1;
3404 s++;
3405 }
3406 return 0;
3407}
3408/* Performs globbing on last list[],
3409 * saving each result as a new list[].
3410 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003411static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003412{
3413 glob_t globdata;
3414 int gr;
3415 char *pattern;
3416
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003417 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003418 if (!o->data)
3419 return o_save_ptr_helper(o, n);
3420 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003421 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003422 if (!glob_needed(pattern)) {
3423 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003424 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003425 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003426 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003427 return o_save_ptr_helper(o, n);
3428 }
3429
3430 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003431 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3432 * If we glob "*.\*" and don't find anything, we need
3433 * to fall back to using literal "*.*", but GLOB_NOCHECK
3434 * will return "*.\*"!
3435 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003436 gr = glob(pattern, 0, NULL, &globdata);
3437 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003438 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003439 if (gr == GLOB_NOMATCH) {
3440 globfree(&globdata);
3441 goto literal;
3442 }
3443 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003444 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003445 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3446 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003447 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003448 }
3449 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3450 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003451 /* "forget" pattern in o */
3452 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003453 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003454 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003455 n = o_save_ptr_helper(o, n);
3456 argv++;
3457 if (!*argv)
3458 break;
3459 }
3460 }
3461 globfree(&globdata);
3462 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003463 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003464 return n;
3465}
3466
Denys Vlasenko238081f2010-10-03 14:26:26 +02003467#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003468
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003469/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003470 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003471static int o_save_ptr(o_string *o, int n)
3472{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003473 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003474 /* If o->has_empty_slot, list[n] was already globbed
3475 * (if it was requested back then when it was filled)
3476 * so don't do that again! */
3477 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003478 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003479 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003480 return o_save_ptr_helper(o, n);
3481}
3482
3483/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003484static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003485{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003486 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003487 int string_start;
3488
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003489 if (DEBUG_EXPAND)
3490 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003491 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003492 list = (char**)o->data;
3493 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3494 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003495 while (n) {
3496 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003497 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003498 }
3499 return list;
3500}
3501
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003502static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003503
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003504/* Returns pi->next - next pipe in the list */
3505static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003506{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003507 struct pipe *next;
3508 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003509
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003510 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003511 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003512 struct command *command;
3513 struct redir_struct *r, *rnext;
3514
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003515 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003516 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003517 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003518 if (DEBUG_CLEAN) {
3519 int a;
3520 char **p;
3521 for (a = 0, p = command->argv; *p; a++, p++) {
3522 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3523 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003524 }
3525 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003526 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003527 }
3528 /* not "else if": on syntax error, we may have both! */
3529 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003530 debug_printf_clean(" begin group (cmd_type:%d)\n",
3531 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003532 free_pipe_list(command->group);
3533 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003534 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003535 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003536 /* else is crucial here.
3537 * If group != NULL, child_func is meaningless */
3538#if ENABLE_HUSH_FUNCTIONS
3539 else if (command->child_func) {
3540 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3541 command->child_func->parent_cmd = NULL;
3542 }
3543#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003544#if !BB_MMU
3545 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003546 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003547#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003548 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003549 debug_printf_clean(" redirect %d%s",
3550 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003551 /* guard against the case >$FOO, where foo is unset or blank */
3552 if (r->rd_filename) {
3553 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3554 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003555 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003556 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003557 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003558 rnext = r->next;
3559 free(r);
3560 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003561 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003562 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003563 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003564 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003565#if ENABLE_HUSH_JOB
3566 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003567 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003569
3570 next = pi->next;
3571 free(pi);
3572 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003573}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003574
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003575static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003577 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003578#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003579 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003580#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003581 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003582 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003583 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003584}
3585
3586
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003587/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003588
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003589#ifndef debug_print_tree
3590static void debug_print_tree(struct pipe *pi, int lvl)
3591{
3592 static const char *const PIPE[] = {
3593 [PIPE_SEQ] = "SEQ",
3594 [PIPE_AND] = "AND",
3595 [PIPE_OR ] = "OR" ,
3596 [PIPE_BG ] = "BG" ,
3597 };
3598 static const char *RES[] = {
3599 [RES_NONE ] = "NONE" ,
3600# if ENABLE_HUSH_IF
3601 [RES_IF ] = "IF" ,
3602 [RES_THEN ] = "THEN" ,
3603 [RES_ELIF ] = "ELIF" ,
3604 [RES_ELSE ] = "ELSE" ,
3605 [RES_FI ] = "FI" ,
3606# endif
3607# if ENABLE_HUSH_LOOPS
3608 [RES_FOR ] = "FOR" ,
3609 [RES_WHILE] = "WHILE",
3610 [RES_UNTIL] = "UNTIL",
3611 [RES_DO ] = "DO" ,
3612 [RES_DONE ] = "DONE" ,
3613# endif
3614# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3615 [RES_IN ] = "IN" ,
3616# endif
3617# if ENABLE_HUSH_CASE
3618 [RES_CASE ] = "CASE" ,
3619 [RES_CASE_IN ] = "CASE_IN" ,
3620 [RES_MATCH] = "MATCH",
3621 [RES_CASE_BODY] = "CASE_BODY",
3622 [RES_ESAC ] = "ESAC" ,
3623# endif
3624 [RES_XXXX ] = "XXXX" ,
3625 [RES_SNTX ] = "SNTX" ,
3626 };
3627 static const char *const CMDTYPE[] = {
3628 "{}",
3629 "()",
3630 "[noglob]",
3631# if ENABLE_HUSH_FUNCTIONS
3632 "func()",
3633# endif
3634 };
3635
3636 int pin, prn;
3637
3638 pin = 0;
3639 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003640 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3641 lvl*2, "",
3642 pin,
3643 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3644 RES[pi->res_word],
3645 pi->followup, PIPE[pi->followup]
3646 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003647 prn = 0;
3648 while (prn < pi->num_cmds) {
3649 struct command *command = &pi->cmds[prn];
3650 char **argv = command->argv;
3651
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003652 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003653 lvl*2, "", prn,
3654 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003655#if ENABLE_HUSH_LINENO_VAR
3656 fdprintf(2, " LINENO:%u", command->lineno);
3657#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003658 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003659 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003660 CMDTYPE[command->cmd_type],
3661 argv
3662# if !BB_MMU
3663 , " group_as_string:", command->group_as_string
3664# else
3665 , "", ""
3666# endif
3667 );
3668 debug_print_tree(command->group, lvl+1);
3669 prn++;
3670 continue;
3671 }
3672 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003673 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003674 argv++;
3675 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003676 if (command->redirects)
3677 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003678 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003679 prn++;
3680 }
3681 pi = pi->next;
3682 pin++;
3683 }
3684}
3685#endif /* debug_print_tree */
3686
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003687static struct pipe *new_pipe(void)
3688{
Eric Andersen25f27032001-04-26 23:22:31 +00003689 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003690 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003691 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003692 return pi;
3693}
3694
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003695/* Command (member of a pipe) is complete, or we start a new pipe
3696 * if ctx->command is NULL.
3697 * No errors possible here.
3698 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003699static int done_command(struct parse_context *ctx)
3700{
3701 /* The command is really already in the pipe structure, so
3702 * advance the pipe counter and make a new, null command. */
3703 struct pipe *pi = ctx->pipe;
3704 struct command *command = ctx->command;
3705
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003706#if 0 /* Instead we emit error message at run time */
3707 if (ctx->pending_redirect) {
3708 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003709 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003710 ctx->pending_redirect = NULL;
3711 }
3712#endif
3713
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003714 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003715 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003716 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003717 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003718 }
3719 pi->num_cmds++;
3720 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003721 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003722 } else {
3723 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3724 }
3725
3726 /* Only real trickiness here is that the uncommitted
3727 * command structure is not counted in pi->num_cmds. */
3728 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003729 ctx->command = command = &pi->cmds[pi->num_cmds];
3730 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003731 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003732#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003733 command->lineno = G.parse_lineno;
3734 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003735#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003736 return pi->num_cmds; /* used only for 0/nonzero check */
3737}
3738
3739static void done_pipe(struct parse_context *ctx, pipe_style type)
3740{
3741 int not_null;
3742
3743 debug_printf_parse("done_pipe entered, followup %d\n", type);
3744 /* Close previous command */
3745 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003746#if HAS_KEYWORDS
3747 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3748 ctx->ctx_inverted = 0;
3749 ctx->pipe->res_word = ctx->ctx_res_w;
3750#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003751 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3752 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003753 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3754 * in a backgrounded subshell.
3755 */
3756 struct pipe *pi;
3757 struct command *command;
3758
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003759 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003760 pi = ctx->list_head;
3761 while (pi != ctx->pipe) {
3762 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3763 goto no_conv;
3764 pi = pi->next;
3765 }
3766
3767 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3768 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3769 pi = xzalloc(sizeof(*pi));
3770 pi->followup = PIPE_BG;
3771 pi->num_cmds = 1;
3772 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3773 command = &pi->cmds[0];
3774 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3775 command->cmd_type = CMD_NORMAL;
3776 command->group = ctx->list_head;
3777#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003778 command->group_as_string = xstrndup(
3779 ctx->as_string.data,
3780 ctx->as_string.length - 1 /* do not copy last char, "&" */
3781 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003782#endif
3783 /* Replace all pipes in ctx with one newly created */
3784 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003785 } else {
3786 no_conv:
3787 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003788 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003789
3790 /* Without this check, even just <enter> on command line generates
3791 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003792 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003793 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003794#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003795 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003796#endif
3797#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003798 || ctx->ctx_res_w == RES_DONE
3799 || ctx->ctx_res_w == RES_FOR
3800 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003801#endif
3802#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003803 || ctx->ctx_res_w == RES_ESAC
3804#endif
3805 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003806 struct pipe *new_p;
3807 debug_printf_parse("done_pipe: adding new pipe: "
3808 "not_null:%d ctx->ctx_res_w:%d\n",
3809 not_null, ctx->ctx_res_w);
3810 new_p = new_pipe();
3811 ctx->pipe->next = new_p;
3812 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003813 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003814 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003815 * This is used to control execution.
3816 * RES_FOR and RES_IN are NOT sticky (needed to support
3817 * cases where variable or value happens to match a keyword):
3818 */
3819#if ENABLE_HUSH_LOOPS
3820 if (ctx->ctx_res_w == RES_FOR
3821 || ctx->ctx_res_w == RES_IN)
3822 ctx->ctx_res_w = RES_NONE;
3823#endif
3824#if ENABLE_HUSH_CASE
3825 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003826 ctx->ctx_res_w = RES_CASE_BODY;
3827 if (ctx->ctx_res_w == RES_CASE)
3828 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003829#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003830 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003831 /* Create the memory for command, roughly:
3832 * ctx->pipe->cmds = new struct command;
3833 * ctx->command = &ctx->pipe->cmds[0];
3834 */
3835 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003836 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003837 }
3838 debug_printf_parse("done_pipe return\n");
3839}
3840
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003841static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003842{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003843 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003844 if (MAYBE_ASSIGNMENT != 0)
3845 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003846 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003847 /* Create the memory for command, roughly:
3848 * ctx->pipe->cmds = new struct command;
3849 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003850 */
3851 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003852}
3853
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003854/* If a reserved word is found and processed, parse context is modified
3855 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003856 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003857#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003858struct reserved_combo {
3859 char literal[6];
3860 unsigned char res;
3861 unsigned char assignment_flag;
3862 int flag;
3863};
3864enum {
3865 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003866# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003867 FLAG_IF = (1 << RES_IF ),
3868 FLAG_THEN = (1 << RES_THEN ),
3869 FLAG_ELIF = (1 << RES_ELIF ),
3870 FLAG_ELSE = (1 << RES_ELSE ),
3871 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003872# endif
3873# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003874 FLAG_FOR = (1 << RES_FOR ),
3875 FLAG_WHILE = (1 << RES_WHILE),
3876 FLAG_UNTIL = (1 << RES_UNTIL),
3877 FLAG_DO = (1 << RES_DO ),
3878 FLAG_DONE = (1 << RES_DONE ),
3879 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003880# endif
3881# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003882 FLAG_MATCH = (1 << RES_MATCH),
3883 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003884# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003885 FLAG_START = (1 << RES_XXXX ),
3886};
3887
3888static const struct reserved_combo* match_reserved_word(o_string *word)
3889{
Eric Andersen25f27032001-04-26 23:22:31 +00003890 /* Mostly a list of accepted follow-up reserved words.
3891 * FLAG_END means we are done with the sequence, and are ready
3892 * to turn the compound list into a command.
3893 * FLAG_START means the word must start a new compound list.
3894 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003895 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003896# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003897 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3898 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3899 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3900 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3901 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3902 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003903# endif
3904# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003905 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3906 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3907 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3908 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3909 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3910 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003911# endif
3912# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003913 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3914 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003915# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003916 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003917 const struct reserved_combo *r;
3918
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003919 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003920 if (strcmp(word->data, r->literal) == 0)
3921 return r;
3922 }
3923 return NULL;
3924}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003925/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003926 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003927static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003928{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003929# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003930 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003931 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003932 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003933# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003934 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003935
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003936 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003937 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003938 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003939 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003940 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003941
3942 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003943# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003944 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3945 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003946 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003947 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003948# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003949 if (r->flag == 0) { /* '!' */
3950 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003951 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003952 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003953 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003954 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003955 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003956 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003957 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003958 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003959
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003960 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003961 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003962 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003963 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003964 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003965 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003966 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003967 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003968 } else {
3969 /* "{...} fi" is ok. "{...} if" is not
3970 * Example:
3971 * if { echo foo; } then { echo bar; } fi */
3972 if (ctx->command->group)
3973 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003974 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003975
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003976 ctx->ctx_res_w = r->res;
3977 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003978 ctx->is_assignment = r->assignment_flag;
3979 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003980
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003981 if (ctx->old_flag & FLAG_END) {
3982 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003983
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003984 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003985 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003986 old = ctx->stack;
3987 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003988 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003989# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003990 /* At this point, the compound command's string is in
3991 * ctx->as_string... except for the leading keyword!
3992 * Consider this example: "echo a | if true; then echo a; fi"
3993 * ctx->as_string will contain "true; then echo a; fi",
3994 * with "if " remaining in old->as_string!
3995 */
3996 {
3997 char *str;
3998 int len = old->as_string.length;
3999 /* Concatenate halves */
4000 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004001 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004002 /* Find where leading keyword starts in first half */
4003 str = old->as_string.data + len;
4004 if (str > old->as_string.data)
4005 str--; /* skip whitespace after keyword */
4006 while (str > old->as_string.data && isalpha(str[-1]))
4007 str--;
4008 /* Ugh, we're done with this horrid hack */
4009 old->command->group_as_string = xstrdup(str);
4010 debug_printf_parse("pop, remembering as:'%s'\n",
4011 old->command->group_as_string);
4012 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004013# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004014 *ctx = *old; /* physical copy */
4015 free(old);
4016 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004017 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004018}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004019#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004020
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004021/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004022 * Normal return is 0. Syntax errors return 1.
4023 * Note: on return, word is reset, but not o_free'd!
4024 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004025static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004026{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004027 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004028
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4030 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004031 debug_printf_parse("done_word return 0: true null, ignored\n");
4032 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004033 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004034
Eric Andersen25f27032001-04-26 23:22:31 +00004035 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004036 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4037 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004038 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004039 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004040 * If the redirection operator is "<<" or "<<-", the word
4041 * that follows the redirection operator shall be
4042 * subjected to quote removal; it is unspecified whether
4043 * any of the other expansions occur. For the other
4044 * redirection operators, the word that follows the
4045 * redirection operator shall be subjected to tilde
4046 * expansion, parameter expansion, command substitution,
4047 * arithmetic expansion, and quote removal.
4048 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004049 * on the word by a non-interactive shell; an interactive
4050 * shell may perform it, but shall do so only when
4051 * the expansion would result in one word."
4052 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004053//bash does not do parameter/command substitution or arithmetic expansion
4054//for _heredoc_ redirection word: these constructs look for exact eof marker
4055// as written:
4056// <<EOF$t
4057// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004058// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4059
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004060 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004061 /* Cater for >\file case:
4062 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4063 * Same with heredocs:
4064 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4065 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004066 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4067 unbackslash(ctx->pending_redirect->rd_filename);
4068 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004069 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004070 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4071 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004072 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004073 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004074 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004075 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004076#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004077# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004078 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004079 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004080 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004081 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004082 /* ctx->ctx_res_w = RES_MATCH; */
4083 ctx->ctx_dsemicolon = 0;
4084 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004085# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004086 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004087# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004088 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4089 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004090# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004091# if ENABLE_HUSH_CASE
4092 && ctx->ctx_res_w != RES_CASE
4093# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004094 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004095 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004096 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004097 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004098 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004099# if ENABLE_HUSH_LINENO_VAR
4100/* Case:
4101 * "while ...; do
4102 * cmd ..."
4103 * If we don't close the pipe _now_, immediately after "do", lineno logic
4104 * sees "cmd" as starting at "do" - i.e., at the previous line.
4105 */
4106 if (0
4107 IF_HUSH_IF(|| reserved->res == RES_THEN)
4108 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4109 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4110 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4111 ) {
4112 done_pipe(ctx, PIPE_SEQ);
4113 }
4114# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004115 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004116 debug_printf_parse("done_word return %d\n",
4117 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004118 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004119 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004120# if defined(CMD_SINGLEWORD_NOGLOB)
4121 if (0
4122# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004123 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004124# endif
4125 /* In bash, local/export/readonly are special, args
4126 * are assignments and therefore expansion of them
4127 * should be "one-word" expansion:
4128 * $ export i=`echo 'a b'` # one arg: "i=a b"
4129 * compare with:
4130 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4131 * ls: cannot access i=a: No such file or directory
4132 * ls: cannot access b: No such file or directory
4133 * Note: bash 3.2.33(1) does this only if export word
4134 * itself is not quoted:
4135 * $ export i=`echo 'aaa bbb'`; echo "$i"
4136 * aaa bbb
4137 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4138 * aaa
4139 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004140 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4141 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4142 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004143 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004144 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4145 }
4146 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004147# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004148 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004149#endif /* HAS_KEYWORDS */
4150
Denis Vlasenkobb929512009-04-16 10:59:40 +00004151 if (command->group) {
4152 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004153 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004154 debug_printf_parse("done_word return 1: syntax error, "
4155 "groups and arglists don't mix\n");
4156 return 1;
4157 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004158
4159 /* If this word wasn't an assignment, next ones definitely
4160 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004161 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4162 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004163 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004164 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004165 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004166 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004167 command->assignment_cnt++;
4168 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4169 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004170 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4171 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004172 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004173 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4174 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004175 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004176 }
Eric Andersen25f27032001-04-26 23:22:31 +00004177
Denis Vlasenko06810332007-05-21 23:30:54 +00004178#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004179 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004180 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004181 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004182 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004183 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004184 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004185 return 1;
4186 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004187 /* Force FOR to have just one word (variable name) */
4188 /* NB: basically, this makes hush see "for v in ..."
4189 * syntax as if it is "for v; in ...". FOR and IN become
4190 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004191 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004192 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004193#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004194#if ENABLE_HUSH_CASE
4195 /* Force CASE to have just one word */
4196 if (ctx->ctx_res_w == RES_CASE) {
4197 done_pipe(ctx, PIPE_SEQ);
4198 }
4199#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004200
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004201 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004202
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004203 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004204 return 0;
4205}
4206
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004207
4208/* Peek ahead in the input to find out if we have a "&n" construct,
4209 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004210 * Return:
4211 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4212 * REDIRFD_SYNTAX_ERR if syntax error,
4213 * REDIRFD_TO_FILE if no & was seen,
4214 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004215 */
4216#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004217#define parse_redir_right_fd(as_string, input) \
4218 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004219#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004220static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004221{
4222 int ch, d, ok;
4223
4224 ch = i_peek(input);
4225 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004226 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004227
4228 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004229 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004230 ch = i_peek(input);
4231 if (ch == '-') {
4232 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004233 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004234 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004235 }
4236 d = 0;
4237 ok = 0;
4238 while (ch != EOF && isdigit(ch)) {
4239 d = d*10 + (ch-'0');
4240 ok = 1;
4241 ch = i_getch(input);
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 }
4245 if (ok) return d;
4246
4247//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4248
4249 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004250 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004251}
4252
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004253/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004254 */
4255static int parse_redirect(struct parse_context *ctx,
4256 int fd,
4257 redir_type style,
4258 struct in_str *input)
4259{
4260 struct command *command = ctx->command;
4261 struct redir_struct *redir;
4262 struct redir_struct **redirp;
4263 int dup_num;
4264
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004265 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004267 /* Check for a '>&1' type redirect */
4268 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4269 if (dup_num == REDIRFD_SYNTAX_ERR)
4270 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004271 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004272 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004273 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004274 if (dup_num) { /* <<-... */
4275 ch = i_getch(input);
4276 nommu_addchr(&ctx->as_string, ch);
4277 ch = i_peek(input);
4278 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004279 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004280
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004281 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004282 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004283 if (ch == '|') {
4284 /* >|FILE redirect ("clobbering" >).
4285 * Since we do not support "set -o noclobber" yet,
4286 * >| and > are the same for now. Just eat |.
4287 */
4288 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004289 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004290 }
4291 }
4292
4293 /* Create a new redir_struct and append it to the linked list */
4294 redirp = &command->redirects;
4295 while ((redir = *redirp) != NULL) {
4296 redirp = &(redir->next);
4297 }
4298 *redirp = redir = xzalloc(sizeof(*redir));
4299 /* redir->next = NULL; */
4300 /* redir->rd_filename = NULL; */
4301 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004302 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004304 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4305 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004306
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004307 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004308 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004309 /* Erik had a check here that the file descriptor in question
4310 * is legit; I postpone that to "run time"
4311 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004312 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4313 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004314 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004315#if 0 /* Instead we emit error message at run time */
4316 if (ctx->pending_redirect) {
4317 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004318 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004319 }
4320#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004321 /* Set ctx->pending_redirect, so we know what to do at the
4322 * end of the next parsed word. */
4323 ctx->pending_redirect = redir;
4324 }
4325 return 0;
4326}
4327
Eric Andersen25f27032001-04-26 23:22:31 +00004328/* If a redirect is immediately preceded by a number, that number is
4329 * supposed to tell which file descriptor to redirect. This routine
4330 * looks for such preceding numbers. In an ideal world this routine
4331 * needs to handle all the following classes of redirects...
4332 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4333 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4334 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4335 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004336 *
4337 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4338 * "2.7 Redirection
4339 * ... If n is quoted, the number shall not be recognized as part of
4340 * the redirection expression. For example:
4341 * echo \2>a
4342 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004343 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004344 *
4345 * A -1 return means no valid number was found,
4346 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004347 */
4348static int redirect_opt_num(o_string *o)
4349{
4350 int num;
4351
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004352 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004353 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004354 num = bb_strtou(o->data, NULL, 10);
4355 if (errno || num < 0)
4356 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004357 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004358 return num;
4359}
4360
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004361#if BB_MMU
4362#define fetch_till_str(as_string, input, word, skip_tabs) \
4363 fetch_till_str(input, word, skip_tabs)
4364#endif
4365static char *fetch_till_str(o_string *as_string,
4366 struct in_str *input,
4367 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004368 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004369{
4370 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004371 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004372 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004373 int ch;
4374
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004375 /* Starting with "" is necessary for this case:
4376 * cat <<EOF
4377 *
4378 * xxx
4379 * EOF
4380 */
4381 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4382
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004383 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004384
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004385 while (1) {
4386 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004387 if (ch != EOF)
4388 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004389 if (ch == '\n' || ch == EOF) {
4390 check_heredoc_end:
4391 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004392 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004393 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4394 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004395 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004396 return heredoc.data;
4397 }
4398 if (ch == '\n') {
4399 /* This is a new line.
4400 * Remember position and backslash-escaping status.
4401 */
4402 o_addchr(&heredoc, ch);
4403 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004404 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004405 past_EOL = heredoc.length;
4406 /* Get 1st char of next line, possibly skipping leading tabs */
4407 do {
4408 ch = i_getch(input);
4409 if (ch != EOF)
4410 nommu_addchr(as_string, ch);
4411 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4412 /* If this immediately ended the line,
4413 * go back to end-of-line checks.
4414 */
4415 if (ch == '\n')
4416 goto check_heredoc_end;
4417 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004418 } else {
4419 /* Backslash-line continuation in an unquoted
4420 * heredoc. This does not need special handling
4421 * for heredoc body (unquoted heredocs are
4422 * expanded on "execution" and that would take
4423 * care of this case too), but not the case
4424 * of line continuation *in terminator*:
4425 * cat <<EOF
4426 * Ok1
4427 * EO\
4428 * F
4429 */
4430 heredoc.data[--heredoc.length] = '\0';
4431 prev = 0; /* not '\' */
4432 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004433 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004434 }
4435 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004436 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004437 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004438 }
4439 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004440 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004441 if (prev == '\\' && ch == '\\')
4442 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004443 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004444 else
4445 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004446 }
4447}
4448
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004449/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4450 * and load them all. There should be exactly heredoc_cnt of them.
4451 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004452#if BB_MMU
4453#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4454 fetch_heredocs(pi, heredoc_cnt, input)
4455#endif
4456static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004457{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004458 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004459 int i;
4460 struct command *cmd = pi->cmds;
4461
Denys Vlasenko3675c372018-07-23 16:31:21 +02004462 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004463 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004464 cmd->argv ? cmd->argv[0] : "NONE"
4465 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004466 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004467 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004468
Denys Vlasenko3675c372018-07-23 16:31:21 +02004469 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004470 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004471 while (redir) {
4472 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004473 char *p;
4474
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004475 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004476 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004477 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004478 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004479 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004480 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004481 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004482 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004483 free(redir->rd_filename);
4484 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004485 heredoc_cnt--;
4486 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004487 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004488 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004489 if (cmd->group) {
4490 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4491 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4492 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4493 if (heredoc_cnt < 0)
4494 return heredoc_cnt; /* error */
4495 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004496 cmd++;
4497 }
4498 pi = pi->next;
4499 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004500 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004501}
4502
4503
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004504static int run_list(struct pipe *pi);
4505#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004506#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4507 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004508#endif
4509static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004510 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004511 struct in_str *input,
4512 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004513
Denys Vlasenko474cb202018-07-24 13:03:03 +02004514/* Returns number of heredocs not yet consumed,
4515 * or -1 on error.
4516 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004517static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004518 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004519{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004520 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004521 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004522 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004523#if BB_MMU
4524# define as_string NULL
4525#else
4526 char *as_string = NULL;
4527#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004528 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004529 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004530 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004531 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004532
4533 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004534#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004535 if (ch == '(' && !ctx->word.has_quoted_part) {
4536 if (ctx->word.length)
4537 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004538 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004539 if (!command->argv)
4540 goto skip; /* (... */
4541 if (command->argv[1]) { /* word word ... (... */
4542 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004543 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004544 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004545 /* it is "word(..." or "word (..." */
4546 do
4547 ch = i_getch(input);
4548 while (ch == ' ' || ch == '\t');
4549 if (ch != ')') {
4550 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004551 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004552 }
4553 nommu_addchr(&ctx->as_string, ch);
4554 do
4555 ch = i_getch(input);
4556 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004557 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004558 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004559 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004560 }
4561 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004562 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004563 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004564 }
4565#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004566
4567#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004568 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004569 || ctx->word.length /* word{... */
4570 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004571 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004572 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004573 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004574 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004575 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004576 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004577#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004578
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004579 IF_HUSH_FUNCTIONS(skip:)
4580
Denis Vlasenko240c2552009-04-03 03:45:05 +00004581 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004582 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004583 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004584 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4585 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004586 } else {
4587 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004588 ch = i_peek(input);
4589 if (ch != ' ' && ch != '\t' && ch != '\n'
4590 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4591 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004592 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004593 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004594 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004595 if (ch != '(') {
4596 ch = i_getch(input);
4597 nommu_addchr(&ctx->as_string, ch);
4598 }
Eric Andersen25f27032001-04-26 23:22:31 +00004599 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004600
Denys Vlasenko474cb202018-07-24 13:03:03 +02004601 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4602 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4603 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004604#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004605 if (as_string)
4606 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004607#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004608
4609 /* empty ()/{} or parse error? */
4610 if (!pipe_list || pipe_list == ERR_PTR) {
4611 /* parse_stream already emitted error msg */
4612 if (!BB_MMU)
4613 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004614 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004615 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004616 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004617 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004618#if !BB_MMU
4619 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4620 command->group_as_string = as_string;
4621 debug_printf_parse("end of group, remembering as:'%s'\n",
4622 command->group_as_string);
4623#endif
4624
4625#if ENABLE_HUSH_FUNCTIONS
4626 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4627 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4628 struct command *cmd2;
4629
4630 cmd2 = xzalloc(sizeof(*cmd2));
4631 cmd2->cmd_type = CMD_SUBSHELL;
4632 cmd2->group = pipe_list;
4633# if !BB_MMU
4634//UNTESTED!
4635 cmd2->group_as_string = command->group_as_string;
4636 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4637# endif
4638
4639 pipe_list = new_pipe();
4640 pipe_list->cmds = cmd2;
4641 pipe_list->num_cmds = 1;
4642 }
4643#endif
4644
4645 command->group = pipe_list;
4646
Denys Vlasenko474cb202018-07-24 13:03:03 +02004647 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4648 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004649 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004650#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004651}
4652
Denys Vlasenko0b883582016-12-23 16:49:07 +01004653#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004654/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004655/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004656static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004657{
4658 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004659 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004660 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004661 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004662 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004663 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004664 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004665 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004666 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004667 }
4668}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004669static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4670{
4671 while (1) {
4672 int ch = i_getch(input);
4673 if (ch == EOF) {
4674 syntax_error_unterm_ch('\'');
4675 return 0;
4676 }
4677 if (ch == '\'')
4678 return 1;
4679 o_addqchr(dest, ch);
4680 }
4681}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004682/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004683static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004684static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004685{
4686 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004687 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004688 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004689 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004690 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004691 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004692 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004693 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004694 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004695 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004696 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004697 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004698 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004699 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004700 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4701 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004702 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004703 continue;
4704 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004705 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004706 }
4707}
4708/* Process `cmd` - copy contents until "`" is seen. Complicated by
4709 * \` quoting.
4710 * "Within the backquoted style of command substitution, backslash
4711 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4712 * The search for the matching backquote shall be satisfied by the first
4713 * backquote found without a preceding backslash; during this search,
4714 * if a non-escaped backquote is encountered within a shell comment,
4715 * a here-document, an embedded command substitution of the $(command)
4716 * form, or a quoted string, undefined results occur. A single-quoted
4717 * or double-quoted string that begins, but does not end, within the
4718 * "`...`" sequence produces undefined results."
4719 * Example Output
4720 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4721 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004722static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004723{
4724 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004725 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004726 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004727 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004728 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004729 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4730 ch = i_getch(input);
4731 if (ch != '`'
4732 && ch != '$'
4733 && ch != '\\'
4734 && (!in_dquote || ch != '"')
4735 ) {
4736 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004737 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004738 }
4739 if (ch == EOF) {
4740 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004741 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004742 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004743 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004744 }
4745}
4746/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4747 * quoting and nested ()s.
4748 * "With the $(command) style of command substitution, all characters
4749 * following the open parenthesis to the matching closing parenthesis
4750 * constitute the command. Any valid shell script can be used for command,
4751 * except a script consisting solely of redirections which produces
4752 * unspecified results."
4753 * Example Output
4754 * echo $(echo '(TEST)' BEST) (TEST) BEST
4755 * echo $(echo 'TEST)' BEST) TEST) BEST
4756 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004757 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004758 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004759 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004760 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4761 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004762 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004763#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004764static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004765{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004766 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004767 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004768# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004769 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004770# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004771 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4772
Denys Vlasenko817a2022018-06-26 15:35:17 +02004773#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004774 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004775#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004776 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4777
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004778 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004779 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004780 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004781 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004782 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004783 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004784 if (ch == end_ch
4785# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004786 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004787# endif
4788 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004789 if (!dbl)
4790 break;
4791 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004792 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004793 i_getch(input); /* eat second ')' */
4794 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004795 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004796 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004797 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004798 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004799 if (ch == '(' || ch == '{') {
4800 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004801 if (!add_till_closing_bracket(dest, input, ch))
4802 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004803 o_addchr(dest, ch);
4804 continue;
4805 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004806 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004807 if (!add_till_single_quote(dest, input))
4808 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004809 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004810 continue;
4811 }
4812 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004813 if (!add_till_double_quote(dest, input))
4814 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004815 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004816 continue;
4817 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004818 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004819 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4820 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004821 o_addchr(dest, ch);
4822 continue;
4823 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004824 if (ch == '\\') {
4825 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004826 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004827 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004828 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004829 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004830 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004831#if 0
4832 if (ch == '\n') {
4833 /* "backslash+newline", ignore both */
4834 o_delchr(dest); /* undo insertion of '\' */
4835 continue;
4836 }
4837#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004838 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004839 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004840 continue;
4841 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004842 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004843 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004844 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004845}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004846#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004847
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004848/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004849#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004850#define parse_dollar(as_string, dest, input, quote_mask) \
4851 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004852#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004853#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004854static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004855 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004856 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004857{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004858 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004859
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004860 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004861 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004862 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004863 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004864 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004865 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004867 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004868 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004869 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004870 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004871 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004872 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004873 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004874 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004875 }
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);
Eric Andersen25f27032001-04-26 23:22:31 +00004878 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004880 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004881 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004882 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004883 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004885 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004886 o_addchr(dest, ch | quote_mask);
4887 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004888 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004889 case '$': /* pid */
4890 case '!': /* last bg pid */
4891 case '?': /* last exit code */
4892 case '#': /* number of args */
4893 case '*': /* args */
4894 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02004895 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004896 goto make_one_char_var;
4897 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004898 char len_single_ch;
4899
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004900 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4901
Denys Vlasenko74369502010-05-21 19:52:01 +02004902 ch = i_getch(input); /* eat '{' */
4903 nommu_addchr(as_string, ch);
4904
Denys Vlasenko46e64982016-09-29 19:50:55 +02004905 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004906 /* It should be ${?}, or ${#var},
4907 * or even ${?+subst} - operator acting on a special variable,
4908 * or the beginning of variable name.
4909 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004910 if (ch == EOF
4911 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4912 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004913 bad_dollar_syntax:
4914 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004915 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4916 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004917 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004918 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004919 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004920 ch |= quote_mask;
4921
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004922 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004923 * However, this regresses some of our testsuite cases
4924 * which check invalid constructs like ${%}.
4925 * Oh well... let's check that the var name part is fine... */
4926
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004927 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004928 unsigned pos;
4929
Denys Vlasenko74369502010-05-21 19:52:01 +02004930 o_addchr(dest, ch);
4931 debug_printf_parse(": '%c'\n", ch);
4932
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004933 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004934 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004935 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004936 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004937
Denys Vlasenko74369502010-05-21 19:52:01 +02004938 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004939 unsigned end_ch;
4940 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004941 /* handle parameter expansions
4942 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4943 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004944 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4945 if (len_single_ch != '#'
4946 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4947 || i_peek(input) != '}'
4948 ) {
4949 goto bad_dollar_syntax;
4950 }
4951 /* else: it's "length of C" ${#C} op,
4952 * where C is a single char
4953 * special var name, e.g. ${#!}.
4954 */
4955 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004956 /* Eat everything until closing '}' (or ':') */
4957 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004958 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004959 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004960 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004961 ) {
4962 /* It's ${var:N[:M]} thing */
4963 end_ch = '}' * 0x100 + ':';
4964 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004965 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004966 && ch == '/'
4967 ) {
4968 /* It's ${var/[/]pattern[/repl]} thing */
4969 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4970 i_getch(input);
4971 nommu_addchr(as_string, '/');
4972 ch = '\\';
4973 }
4974 end_ch = '}' * 0x100 + '/';
4975 }
4976 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02004977 /* The pattern can't be empty.
4978 * IOW: if the first char after "${v//" is a slash,
4979 * it does not terminate the pattern - it's the first char of the pattern:
4980 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4981 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4982 */
4983 if (i_peek(input) == '/') {
4984 o_addchr(dest, i_getch(input));
4985 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004986 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004987 if (!BB_MMU)
4988 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004989#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004990 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004991 if (last_ch == 0) /* error? */
4992 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004993#else
4994#error Simple code to only allow ${var} is not implemented
4995#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004996 if (as_string) {
4997 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004998 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004999 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005000
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005001 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5002 && (end_ch & 0xff00)
5003 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005004 /* close the first block: */
5005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005006 /* while parsing N from ${var:N[:M]}
5007 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005008 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005009 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005010 end_ch = '}';
5011 goto again;
5012 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005013 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005014 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005015 /* it's ${var:N} - emulate :999999999 */
5016 o_addstr(dest, "999999999");
5017 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005018 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005019 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005020 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005021 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005022 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005023 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5024 break;
5025 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005026#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005027 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005028 unsigned pos;
5029
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005030 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005031 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005032# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005033 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005034 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005035 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005036 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5037 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005038 if (!BB_MMU)
5039 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005040 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5041 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005042 if (as_string) {
5043 o_addstr(as_string, dest->data + pos);
5044 o_addchr(as_string, ')');
5045 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005046 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005047 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005048 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005049 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005050# endif
5051# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005052 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5053 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005054 if (!BB_MMU)
5055 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005056 if (!add_till_closing_bracket(dest, input, ')'))
5057 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005058 if (as_string) {
5059 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005060 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005061 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005062 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005063# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005064 break;
5065 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005066#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005067 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005068 goto make_var;
5069#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005070 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005071 /* $_ Shell or shell script name; or last argument of last command
5072 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5073 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005074 ch = i_getch(input);
5075 nommu_addchr(as_string, ch);
5076 ch = i_peek_and_eat_bkslash_nl(input);
5077 if (isalnum(ch)) { /* it's $_name or $_123 */
5078 ch = '_';
5079 goto make_var1;
5080 }
5081 /* else: it's $_ */
5082#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005083 default:
5084 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005085 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005086 debug_printf_parse("parse_dollar return 1 (ok)\n");
5087 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005088#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005089}
5090
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005091#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005092#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005093 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005094#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005095#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005096static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005097 o_string *dest,
5098 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005099 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005100{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005101 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005102 int next;
5103
5104 again:
5105 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005106 if (ch != EOF)
5107 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005108 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005109 debug_printf_parse("encode_string return 1 (ok)\n");
5110 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005111 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005112 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005113 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005114 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005115 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005116 }
5117 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005118 if (ch != '\n') {
5119 next = i_peek(input);
5120 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005121 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005122 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005123 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005124 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005125 /* Testcase: in interactive shell a file with
5126 * echo "unterminated string\<eof>
5127 * is sourced.
5128 */
5129 syntax_error_unterm_ch('"');
5130 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005131 }
5132 /* bash:
5133 * "The backslash retains its special meaning [in "..."]
5134 * only when followed by one of the following characters:
5135 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005136 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005137 * NB: in (unquoted) heredoc, above does not apply to ",
5138 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005139 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005140 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005141 ch = i_getch(input); /* eat next */
5142 if (ch == '\n')
5143 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005144 } /* else: ch remains == '\\', and we double it below: */
5145 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005146 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005147 goto again;
5148 }
5149 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005150 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5151 debug_printf_parse("encode_string return 0: "
5152 "parse_dollar returned 0 (error)\n");
5153 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005154 }
5155 goto again;
5156 }
5157#if ENABLE_HUSH_TICK
5158 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005159 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005160 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5161 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005162 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5163 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005164 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5165 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005166 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005167 }
5168#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005169 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005170 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005171#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005172}
5173
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005174/*
5175 * Scan input until EOF or end_trigger char.
5176 * Return a list of pipes to execute, or NULL on EOF
5177 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005178 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005179 * reset parsing machinery and start parsing anew,
5180 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005181 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005182static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005183 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005184 struct in_str *input,
5185 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005186{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005187 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005188 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005189
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005190 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005191 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005192 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005193 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005194 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005195 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005196
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005197 initialize_context(&ctx);
5198
5199 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5200 * Preventing this:
5201 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005202 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005203
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005204 /* We used to separate words on $IFS here. This was wrong.
5205 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005206 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005207 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005208
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005209 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005210 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005211 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005212 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005213 int ch;
5214 int next;
5215 int redir_fd;
5216 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005217
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005218 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005219 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005220 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005221 if (ch == EOF) {
5222 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005223
5224 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005225 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005226 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005227 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005228 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005229 syntax_error_unterm_ch('(');
5230 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005231 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005232 if (end_trigger == '}') {
5233 syntax_error_unterm_ch('{');
5234 goto parse_error;
5235 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005236
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005237 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005238 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005239 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005240 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005241 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005242 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005243 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005244 /* (this makes bare "&" cmd a no-op.
5245 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005246 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005247 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005248 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005249 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005250 pi = NULL;
5251 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005252#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005253 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005254 if (pstring)
5255 *pstring = ctx.as_string.data;
5256 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005257 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005258#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005259 // heredoc_cnt must be 0 here anyway
5260 //if (heredoc_cnt_ptr)
5261 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005262 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005263 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005264 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005265 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005266 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005267
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005268 /* Handle "'" and "\" first, as they won't play nice with
5269 * i_peek_and_eat_bkslash_nl() anyway:
5270 * echo z\\
5271 * and
5272 * echo '\
5273 * '
5274 * would break.
5275 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005276 if (ch == '\\') {
5277 ch = i_getch(input);
5278 if (ch == '\n')
5279 continue; /* drop \<newline>, get next char */
5280 nommu_addchr(&ctx.as_string, '\\');
5281 o_addchr(&ctx.word, '\\');
5282 if (ch == EOF) {
5283 /* Testcase: eval 'echo Ok\' */
5284 /* bash-4.3.43 was removing backslash,
5285 * but 4.4.19 retains it, most other shells too
5286 */
5287 continue; /* get next char */
5288 }
5289 /* Example: echo Hello \2>file
5290 * we need to know that word 2 is quoted
5291 */
5292 ctx.word.has_quoted_part = 1;
5293 nommu_addchr(&ctx.as_string, ch);
5294 o_addchr(&ctx.word, ch);
5295 continue; /* get next char */
5296 }
5297 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005298 if (ch == '\'') {
5299 ctx.word.has_quoted_part = 1;
5300 next = i_getch(input);
5301 if (next == '\'' && !ctx.pending_redirect)
5302 goto insert_empty_quoted_str_marker;
5303
5304 ch = next;
5305 while (1) {
5306 if (ch == EOF) {
5307 syntax_error_unterm_ch('\'');
5308 goto parse_error;
5309 }
5310 nommu_addchr(&ctx.as_string, ch);
5311 if (ch == '\'')
5312 break;
5313 if (ch == SPECIAL_VAR_SYMBOL) {
5314 /* Convert raw ^C to corresponding special variable reference */
5315 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5316 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5317 }
5318 o_addqchr(&ctx.word, ch);
5319 ch = i_getch(input);
5320 }
5321 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005322 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005323
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005324 next = '\0';
5325 if (ch != '\n')
5326 next = i_peek_and_eat_bkslash_nl(input);
5327
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005328 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005329 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005330 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005331 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005332 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005333 || ctx.word.length /* word{... - non-special */
5334 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005335 || (next != ';' /* }; - special */
5336 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005337 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005338 && next != '&' /* }& and }&& ... - special */
5339 && next != '|' /* }|| ... - special */
5340 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005341 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005342 ) {
5343 /* They are not special, skip "{}" */
5344 is_special += 2;
5345 }
5346 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005347 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005348
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005349 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005350 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005351 o_addQchr(&ctx.word, ch);
5352 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5353 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005354 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005355 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005356 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005357 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5358 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005359 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005360 continue;
5361 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005362
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005363 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005364#if ENABLE_HUSH_LINENO_VAR
5365/* Case:
5366 * "while ...; do<whitespace><newline>
5367 * cmd ..."
5368 * would think that "cmd" starts in <whitespace> -
5369 * i.e., at the previous line.
5370 * We need to skip all whitespace before newlines.
5371 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005372 while (ch != '\n') {
5373 next = i_peek(input);
5374 if (next != ' ' && next != '\t' && next != '\n')
5375 break; /* next char is not ws */
5376 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005377 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005378 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005379#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005380 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005381 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005382 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005383 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005384 /* Is this a case when newline is simply ignored?
5385 * Some examples:
5386 * "cmd | <newline> cmd ..."
5387 * "case ... in <newline> word) ..."
5388 */
5389 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005390 && ctx.word.length == 0
5391 && !ctx.word.has_quoted_part
5392 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005393 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005394 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005395 * Without check #1, interactive shell
5396 * ignores even bare <newline>,
5397 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005398 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005399 * ps2> _ <=== wrong, should be ps1
5400 * Without check #2, "cmd & <newline>"
5401 * is similarly mistreated.
5402 * (BTW, this makes "cmd & cmd"
5403 * and "cmd && cmd" non-orthogonal.
5404 * Really, ask yourself, why
5405 * "cmd && <newline>" doesn't start
5406 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005407 * The only reason is that it might be
5408 * a "cmd1 && <nl> cmd2 &" construct,
5409 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005410 */
5411 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005412 if (pi->num_cmds != 0 /* check #1 */
5413 && pi->followup != PIPE_BG /* check #2 */
5414 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005415 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005416 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005417 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005418 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005419 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005420 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005421 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005422 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5423 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005424 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005425 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005426 ctx.is_assignment = MAYBE_ASSIGNMENT;
5427 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005428 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005429 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005430 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005431 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005432 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005433
5434 /* "cmd}" or "cmd }..." without semicolon or &:
5435 * } is an ordinary char in this case, even inside { cmd; }
5436 * Pathological example: { ""}; } should exec "}" cmd
5437 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005438 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005439 if (ctx.word.length != 0 /* word} */
5440 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005441 ) {
5442 goto ordinary_char;
5443 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005444 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5445 /* Generally, there should be semicolon: "cmd; }"
5446 * However, bash allows to omit it if "cmd" is
5447 * a group. Examples:
5448 * { { echo 1; } }
5449 * {(echo 1)}
5450 * { echo 0 >&2 | { echo 1; } }
5451 * { while false; do :; done }
5452 * { case a in b) ;; esac }
5453 */
5454 if (ctx.command->group)
5455 goto term_group;
5456 goto ordinary_char;
5457 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005458 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005459 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005460 goto skip_end_trigger;
5461 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005462 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005463 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005464 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005465 && (ch != ';' || heredoc_cnt == 0)
5466#if ENABLE_HUSH_CASE
5467 && (ch != ')'
5468 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005469 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005470 )
5471#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005472 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005473 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005474 goto parse_error;
5475 }
5476 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005477 ctx.is_assignment = MAYBE_ASSIGNMENT;
5478 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005479 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005480 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005481 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005482 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005483 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005484#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005485 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005486 if (pstring)
5487 *pstring = ctx.as_string.data;
5488 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005489 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005490#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005491 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5492 /* Example: bare "{ }", "()" */
5493 G.last_exitcode = 2; /* bash compat */
5494 syntax_error_unexpected_ch(ch);
5495 goto parse_error2;
5496 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005497 if (heredoc_cnt_ptr)
5498 *heredoc_cnt_ptr = heredoc_cnt;
5499 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005500 debug_printf_parse("parse_stream return %p: "
5501 "end_trigger char found\n",
5502 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005503 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005504 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005505 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005506 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005507
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005508 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005509 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005510
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005511 /* Catch <, > before deciding whether this word is
5512 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5513 switch (ch) {
5514 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005515 redir_fd = redirect_opt_num(&ctx.word);
5516 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005517 goto parse_error;
5518 }
5519 redir_style = REDIRECT_OVERWRITE;
5520 if (next == '>') {
5521 redir_style = REDIRECT_APPEND;
5522 ch = i_getch(input);
5523 nommu_addchr(&ctx.as_string, ch);
5524 }
5525#if 0
5526 else if (next == '(') {
5527 syntax_error(">(process) not supported");
5528 goto parse_error;
5529 }
5530#endif
5531 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5532 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005533 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005534 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005535 redir_fd = redirect_opt_num(&ctx.word);
5536 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005537 goto parse_error;
5538 }
5539 redir_style = REDIRECT_INPUT;
5540 if (next == '<') {
5541 redir_style = REDIRECT_HEREDOC;
5542 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005543 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005544 ch = i_getch(input);
5545 nommu_addchr(&ctx.as_string, ch);
5546 } else if (next == '>') {
5547 redir_style = REDIRECT_IO;
5548 ch = i_getch(input);
5549 nommu_addchr(&ctx.as_string, ch);
5550 }
5551#if 0
5552 else if (next == '(') {
5553 syntax_error("<(process) not supported");
5554 goto parse_error;
5555 }
5556#endif
5557 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5558 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005559 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005560 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005561 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005562 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005563 /* note: we do not add it to &ctx.as_string */
5564/* TODO: in bash:
5565 * comment inside $() goes to the next \n, even inside quoted string (!):
5566 * cmd "$(cmd2 #comment)" - syntax error
5567 * cmd "`cmd2 #comment`" - ok
5568 * We accept both (comment ends where command subst ends, in both cases).
5569 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005570 while (1) {
5571 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005572 if (ch == '\n') {
5573 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005574 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005575 }
5576 ch = i_getch(input);
5577 if (ch == EOF)
5578 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005579 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005580 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005581 }
5582 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005583 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005584 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005585
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005586 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005587 /* check that we are not in word in "a=1 2>word b=1": */
5588 && !ctx.pending_redirect
5589 ) {
5590 /* ch is a special char and thus this word
5591 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005592 ctx.is_assignment = NOT_ASSIGNMENT;
5593 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005594 }
5595
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005596 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5597
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005598 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005599 case SPECIAL_VAR_SYMBOL:
5600 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005601 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5602 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005603 /* fall through */
5604 case '#':
5605 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005606 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005607 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005608 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005609 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005610 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005611 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005612 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005613 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005614 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005615 case '"':
5616 ctx.word.has_quoted_part = 1;
5617 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005618 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005619 insert_empty_quoted_str_marker:
5620 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005621 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5622 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005623 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005624 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005625 if (ctx.is_assignment == NOT_ASSIGNMENT)
5626 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005627 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005628 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005629 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005630 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005631#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005632 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005633 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005634
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005635 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5636 o_addchr(&ctx.word, '`');
5637 USE_FOR_NOMMU(pos = ctx.word.length;)
5638 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005639 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005640# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005641 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005642 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005643# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005644 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5645 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005646 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005647 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005648#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005649 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005650#if ENABLE_HUSH_CASE
5651 case_semi:
5652#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005653 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005654 goto parse_error;
5655 }
5656 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005657#if ENABLE_HUSH_CASE
5658 /* Eat multiple semicolons, detect
5659 * whether it means something special */
5660 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005661 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005662 if (ch != ';')
5663 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005664 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005665 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005666 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005667 ctx.ctx_dsemicolon = 1;
5668 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005669 break;
5670 }
5671 }
5672#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005673 new_cmd:
5674 /* We just finished a cmd. New one may start
5675 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005676 ctx.is_assignment = MAYBE_ASSIGNMENT;
5677 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005678 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005679 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005680 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005681 goto parse_error;
5682 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005683 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005684 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005685 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005686 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005687 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005688 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005689 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005690 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005691 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005692 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005693 goto parse_error;
5694 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005695#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005696 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005697 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005698#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005699 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005700 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005701 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005702 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005703 } else {
5704 /* we could pick up a file descriptor choice here
5705 * with redirect_opt_num(), but bash doesn't do it.
5706 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005707 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005708 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005709 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005710 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005711#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005712 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005713 if (ctx.ctx_res_w == RES_MATCH
5714 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005715 && ctx.word.length == 0 /* not word(... */
5716 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005717 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005718 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005719 }
5720#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005721 /* fall through */
5722 case '{': {
5723 int n = parse_group(&ctx, input, ch);
5724 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005725 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005726 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005727 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5728 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005729 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005730 }
Eric Andersen25f27032001-04-26 23:22:31 +00005731 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005732#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005733 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005734 goto case_semi;
5735#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005736
Eric Andersen25f27032001-04-26 23:22:31 +00005737 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005738 /* proper use of this character is caught by end_trigger:
5739 * if we see {, we call parse_group(..., end_trigger='}')
5740 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005741 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005742 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005743 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005744 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005745 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005746 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005747 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005748 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005749
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005750 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005751 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005752 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005753 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005754 struct parse_context *pctx;
5755 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005756
5757 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005758 * Sample for finding leaks on syntax error recovery path.
5759 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005760 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005761 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005762 * while if (true | { true;}); then echo ok; fi; do break; done
5763 * 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 +00005764 */
5765 pctx = &ctx;
5766 do {
5767 /* Update pipe/command counts,
5768 * otherwise freeing may miss some */
5769 done_pipe(pctx, PIPE_SEQ);
5770 debug_printf_clean("freeing list %p from ctx %p\n",
5771 pctx->list_head, pctx);
5772 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005773 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005774 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005775#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005776 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005777#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005778 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005779 if (pctx != &ctx) {
5780 free(pctx);
5781 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005782 IF_HAS_KEYWORDS(pctx = p2;)
5783 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005784
Denys Vlasenko474cb202018-07-24 13:03:03 +02005785 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005786#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005787 if (pstring)
5788 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005789#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005790 debug_leave();
5791 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005792 }
Eric Andersen25f27032001-04-26 23:22:31 +00005793}
5794
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005795
5796/*** Execution routines ***/
5797
5798/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005799#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005800#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005801 expand_string_to_string(str)
5802#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005803static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005804#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005805static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005806#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005807static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808
5809/* expand_strvec_to_strvec() takes a list of strings, expands
5810 * all variable references within and returns a pointer to
5811 * a list of expanded strings, possibly with larger number
5812 * of strings. (Think VAR="a b"; echo $VAR).
5813 * This new list is allocated as a single malloc block.
5814 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005815 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005816 * Caller can deallocate entire list by single free(list). */
5817
Denys Vlasenko238081f2010-10-03 14:26:26 +02005818/* A horde of its helpers come first: */
5819
5820static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5821{
5822 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005823 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005824
Denys Vlasenko9e800222010-10-03 14:28:04 +02005825#if ENABLE_HUSH_BRACE_EXPANSION
5826 if (c == '{' || c == '}') {
5827 /* { -> \{, } -> \} */
5828 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005829 /* And now we want to add { or } and continue:
5830 * o_addchr(o, c);
5831 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005832 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005833 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005834 }
5835#endif
5836 o_addchr(o, c);
5837 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005838 /* \z -> \\\z; \<eol> -> \\<eol> */
5839 o_addchr(o, '\\');
5840 if (len) {
5841 len--;
5842 o_addchr(o, '\\');
5843 o_addchr(o, *str++);
5844 }
5845 }
5846 }
5847}
5848
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005849/* Store given string, finalizing the word and starting new one whenever
5850 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005851 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005852 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005853 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5854 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005855static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005856{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005857 int last_is_ifs = 0;
5858
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005859 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005860 int word_len;
5861
5862 if (!*str) /* EOL - do not finalize word */
5863 break;
5864 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005865 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005866 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005867 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005868 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005869 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005870 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005871 * Example: "v='\*'; echo b$v" prints "b\*"
5872 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005873 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005874 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005875 /*/ Why can't we do it easier? */
5876 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5877 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5878 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005879 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005880 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005881 if (!*str) /* EOL - do not finalize word */
5882 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005883 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005884
5885 /* We know str here points to at least one IFS char */
5886 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005887 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005888 if (!*str) /* EOL - do not finalize word */
5889 break;
5890
Denys Vlasenko96786362018-04-11 16:02:58 +02005891 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5892 && strchr(G.ifs, *str) /* the second check would fail */
5893 ) {
5894 /* This is a non-whitespace $IFS char */
5895 /* Skip it and IFS whitespace chars, start new word */
5896 str++;
5897 str += strspn(str, G.ifs_whitespace);
5898 goto new_word;
5899 }
5900
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005901 /* Start new word... but not always! */
5902 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005903 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005904 /*
5905 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005906 * here nothing precedes the space in $v expansion,
5907 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005908 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005909 * It's okay if this accesses the byte before first argv[]:
5910 * past call to o_save_ptr() cleared it to zero byte
5911 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005912 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005913 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005914 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005915 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005916 o_addchr(output, '\0');
5917 debug_print_list("expand_on_ifs", output, n);
5918 n = o_save_ptr(output, n);
5919 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005920 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005921
Denys Vlasenko168579a2018-07-19 13:45:54 +02005922 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005923 debug_print_list("expand_on_ifs[1]", output, n);
5924 return n;
5925}
5926
5927/* Helper to expand $((...)) and heredoc body. These act as if
5928 * they are in double quotes, with the exception that they are not :).
5929 * Just the rules are similar: "expand only $var and `cmd`"
5930 *
5931 * Returns malloced string.
5932 * As an optimization, we return NULL if expansion is not needed.
5933 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005934static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005935{
5936 char *exp_str;
5937 struct in_str input;
5938 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005939 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005940
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005941 cp = str;
5942 for (;;) {
5943 if (!*cp) return NULL; /* string has no special chars */
5944 if (*cp == '$') break;
5945 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005946#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005947 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005948#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005949 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005950 }
5951
5952 /* We need to expand. Example:
5953 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5954 */
5955 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005956 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005957//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005958 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005959 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005960 EXP_FLAG_ESC_GLOB_CHARS,
5961 /*unbackslash:*/ 1
5962 );
5963 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005964 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005965 return exp_str;
5966}
5967
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005968static const char *first_special_char_in_vararg(const char *cp)
5969{
5970 for (;;) {
5971 if (!*cp) return NULL; /* string has no special chars */
5972 if (*cp == '$') return cp;
5973 if (*cp == '\\') return cp;
5974 if (*cp == '\'') return cp;
5975 if (*cp == '"') return cp;
5976#if ENABLE_HUSH_TICK
5977 if (*cp == '`') return cp;
5978#endif
5979 /* dquoted "${x:+ARG}" should not glob, therefore
5980 * '*' et al require some non-literal processing: */
5981 if (*cp == '*') return cp;
5982 if (*cp == '?') return cp;
5983 if (*cp == '[') return cp;
5984 cp++;
5985 }
5986}
5987
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005988/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5989 * These can contain single- and double-quoted strings,
5990 * and treated as if the ARG string is initially unquoted. IOW:
5991 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5992 * a dquoted string: "${var#"zz"}"), the difference only comes later
5993 * (word splitting and globbing of the ${var...} result).
5994 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005995#if !BASH_PATTERN_SUBST
5996#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5997 encode_then_expand_vararg(str, handle_squotes)
5998#endif
5999static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6000{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006001#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006002 const int do_unbackslash = 0;
6003#endif
6004 char *exp_str;
6005 struct in_str input;
6006 o_string dest = NULL_O_STRING;
6007
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006008 if (!first_special_char_in_vararg(str)) {
6009 /* string has no special chars */
6010 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006011 }
6012
Denys Vlasenkob762c782018-07-17 14:21:38 +02006013 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006014 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006015 exp_str = NULL;
6016
6017 for (;;) {
6018 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006019
6020 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006021 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6022 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006023
6024 if (!dest.o_expflags) {
6025 if (ch == EOF)
6026 break;
6027 if (handle_squotes && ch == '\'') {
6028 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006029 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006030 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006031 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006032 }
6033 if (ch == EOF) {
6034 syntax_error_unterm_ch('"');
6035 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006036 }
6037 if (ch == '"') {
6038 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6039 continue;
6040 }
6041 if (ch == '\\') {
6042 ch = i_getch(&input);
6043 if (ch == EOF) {
6044//example? error message? syntax_error_unterm_ch('"');
6045 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6046 goto ret;
6047 }
6048 o_addqchr(&dest, ch);
6049 continue;
6050 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006051 if (ch == '$') {
6052 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6053 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6054 goto ret;
6055 }
6056 continue;
6057 }
6058#if ENABLE_HUSH_TICK
6059 if (ch == '`') {
6060 //unsigned pos = dest->length;
6061 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6062 o_addchr(&dest, 0x80 | '`');
6063 if (!add_till_backquote(&dest, &input,
6064 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6065 )
6066 ) {
6067 goto ret; /* error */
6068 }
6069 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6070 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6071 continue;
6072 }
6073#endif
6074 o_addQchr(&dest, ch);
6075 } /* for (;;) */
6076
6077 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6078 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006079 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6080 do_unbackslash
6081 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006082 ret:
6083 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006084 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006085 return exp_str;
6086}
6087
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006088/* Expanding ARG in ${var+ARG}, ${var-ARG}
6089 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006090static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006091 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006092{
6093 struct in_str input;
6094 o_string dest = NULL_O_STRING;
6095
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006096 if (!first_special_char_in_vararg(str)
6097 && '\0' == str[strcspn(str, G.ifs)]
6098 ) {
6099 /* string has no special chars
6100 * && string has no $IFS chars
6101 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006102 if (dquoted) {
6103 /* Prints 1 (quoted expansion is a "" word, not nothing):
6104 * set -- "${notexist-}"; echo $#
6105 */
6106 output->has_quoted_part = 1;
6107 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006108 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006109 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006110
Denys Vlasenko294eb462018-07-20 16:18:59 +02006111 setup_string_in_str(&input, str);
6112
6113 for (;;) {
6114 int ch;
6115
6116 ch = i_getch(&input);
6117 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6118 __func__, ch, ch, dest.o_expflags);
6119
6120 if (!dest.o_expflags) {
6121 if (ch == EOF)
6122 break;
6123 if (!dquoted && strchr(G.ifs, ch)) {
6124 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6125 * do not assume we are at the start of the word (PREFIX above).
6126 */
6127 if (dest.data) {
6128 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006129 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006130 o_addchr(output, '\0');
6131 n = o_save_ptr(output, n); /* create next word */
6132 } else
6133 if (output->length != o_get_last_ptr(output, n)
6134 || output->has_quoted_part
6135 ) {
6136 /* For these cases:
6137 * f() { for i; do echo "|$i|"; done; }; x=x
6138 * f a${x:+ }b # 1st condition
6139 * |a|
6140 * |b|
6141 * f ""${x:+ }b # 2nd condition
6142 * ||
6143 * |b|
6144 */
6145 o_addchr(output, '\0');
6146 n = o_save_ptr(output, n); /* create next word */
6147 }
6148 continue;
6149 }
6150 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006151 if (!add_till_single_quote_dquoted(&dest, &input))
6152 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006153 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6154 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006155 continue;
6156 }
6157 }
6158 if (ch == EOF) {
6159 syntax_error_unterm_ch('"');
6160 goto ret; /* error */
6161 }
6162 if (ch == '"') {
6163 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006164 if (dest.o_expflags) {
6165 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6166 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6167 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006168 continue;
6169 }
6170 if (ch == '\\') {
6171 ch = i_getch(&input);
6172 if (ch == EOF) {
6173//example? error message? syntax_error_unterm_ch('"');
6174 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6175 goto ret;
6176 }
6177 o_addqchr(&dest, ch);
6178 continue;
6179 }
6180 if (ch == '$') {
6181 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6182 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6183 goto ret;
6184 }
6185 continue;
6186 }
6187#if ENABLE_HUSH_TICK
6188 if (ch == '`') {
6189 //unsigned pos = dest->length;
6190 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6191 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6192 if (!add_till_backquote(&dest, &input,
6193 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6194 )
6195 ) {
6196 goto ret; /* error */
6197 }
6198 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6199 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6200 continue;
6201 }
6202#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006203 if (dquoted) {
6204 /* Always glob-protect if in dquotes:
6205 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6206 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6207 */
6208 o_addqchr(&dest, ch);
6209 } else {
6210 /* Glob-protect only if char is quoted:
6211 * x=x; echo ${x:+/bin/c*} - prints many filenames
6212 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6213 */
6214 o_addQchr(&dest, ch);
6215 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006216 } /* for (;;) */
6217
6218 if (dest.data) {
6219 n = expand_vars_to_list(output, n, dest.data);
6220 }
6221 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006222 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006223 return n;
6224}
6225
Denys Vlasenko0b883582016-12-23 16:49:07 +01006226#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006227static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006228{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006229 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006230 arith_t res;
6231 char *exp_str;
6232
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006233 math_state.lookupvar = get_local_var_value;
6234 math_state.setvar = set_local_var_from_halves;
6235 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006236 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006237 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006238 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006239 if (errmsg_p)
6240 *errmsg_p = math_state.errmsg;
6241 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006242 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006243 return res;
6244}
6245#endif
6246
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006247#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006248/* ${var/[/]pattern[/repl]} helpers */
6249static char *strstr_pattern(char *val, const char *pattern, int *size)
6250{
6251 while (1) {
6252 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6253 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6254 if (end) {
6255 *size = end - val;
6256 return val;
6257 }
6258 if (*val == '\0')
6259 return NULL;
6260 /* Optimization: if "*pat" did not match the start of "string",
6261 * we know that "tring", "ring" etc will not match too:
6262 */
6263 if (pattern[0] == '*')
6264 return NULL;
6265 val++;
6266 }
6267}
6268static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6269{
6270 char *result = NULL;
6271 unsigned res_len = 0;
6272 unsigned repl_len = strlen(repl);
6273
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006274 /* Null pattern never matches, including if "var" is empty */
6275 if (!pattern[0])
6276 return result; /* NULL, no replaces happened */
6277
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006278 while (1) {
6279 int size;
6280 char *s = strstr_pattern(val, pattern, &size);
6281 if (!s)
6282 break;
6283
6284 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006285 strcpy(mempcpy(result + res_len, val, s - val), repl);
6286 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006287 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6288
6289 val = s + size;
6290 if (exp_op == '/')
6291 break;
6292 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006293 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294 result = xrealloc(result, res_len + strlen(val) + 1);
6295 strcpy(result + res_len, val);
6296 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6297 }
6298 debug_printf_varexp("result:'%s'\n", result);
6299 return result;
6300}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006301#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302
Denys Vlasenko168579a2018-07-19 13:45:54 +02006303static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006304 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006305{
6306 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6307 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6308 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6309 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006310 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006311 } else { /* quoted "$VAR" */
6312 output->has_quoted_part = 1;
6313 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6314 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6315 if (val && val[0])
6316 o_addQstr(output, val);
6317 }
6318 return n;
6319}
6320
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006321/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006322 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006323static NOINLINE int expand_one_var(o_string *output, int n,
6324 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006325{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006326 const char *val;
6327 char *to_be_freed;
6328 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006329 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006330 char exp_op;
6331 char exp_save = exp_save; /* for compiler */
6332 char *exp_saveptr; /* points to expansion operator */
6333 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006334 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006335
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006336 val = NULL;
6337 to_be_freed = NULL;
6338 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006339 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006340 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006341 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006342 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006343 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006344 exp_op = 0;
6345
Denys Vlasenkob762c782018-07-17 14:21:38 +02006346 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006347 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6348 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6349 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006350 ) {
6351 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352 var++;
6353 exp_op = 'L';
6354 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006355 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006356 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006357 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006358 ) {
6359 /* ${?:0}, ${#[:]%0} etc */
6360 exp_saveptr = var + 1;
6361 } else {
6362 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6363 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6364 }
6365 exp_op = exp_save = *exp_saveptr;
6366 if (exp_op) {
6367 exp_word = exp_saveptr + 1;
6368 if (exp_op == ':') {
6369 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006370//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006371 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006372 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006373 ) {
6374 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6375 exp_op = ':';
6376 exp_word--;
6377 }
6378 }
6379 *exp_saveptr = '\0';
6380 } /* else: it's not an expansion op, but bare ${var} */
6381 }
6382
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006383 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006384 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006385 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006386 int nn = xatoi_positive(var);
6387 if (nn < G.global_argc)
6388 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006389 /* else val remains NULL: $N with too big N */
6390 } else {
6391 switch (var[0]) {
6392 case '$': /* pid */
6393 val = utoa(G.root_pid);
6394 break;
6395 case '!': /* bg pid */
6396 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6397 break;
6398 case '?': /* exitcode */
6399 val = utoa(G.last_exitcode);
6400 break;
6401 case '#': /* argc */
6402 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6403 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006404 case '-': { /* active options */
6405 /* Check set_mode() to see what option chars we support */
6406 char *cp;
6407 val = cp = G.optstring_buf;
6408 if (G.o_opt[OPT_O_ERREXIT])
6409 *cp++ = 'e';
6410 if (G_interactive_fd)
6411 *cp++ = 'i';
6412 if (G_x_mode)
6413 *cp++ = 'x';
6414 /* If G.o_opt[OPT_O_NOEXEC] is true,
6415 * commands read but are not executed,
6416 * so $- can not execute too, 'n' is never seen in $-.
6417 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006418 if (G.opt_c)
6419 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006420 if (G.opt_s)
6421 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006422 *cp = '\0';
6423 break;
6424 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006425 default:
6426 val = get_local_var_value(var);
6427 }
6428 }
6429
6430 /* Handle any expansions */
6431 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006432 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006433 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006434 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006435 debug_printf_expand("%s\n", val);
6436 } else if (exp_op) {
6437 if (exp_op == '%' || exp_op == '#') {
6438 /* Standard-mandated substring removal ops:
6439 * ${parameter%word} - remove smallest suffix pattern
6440 * ${parameter%%word} - remove largest suffix pattern
6441 * ${parameter#word} - remove smallest prefix pattern
6442 * ${parameter##word} - remove largest prefix pattern
6443 *
6444 * Word is expanded to produce a glob pattern.
6445 * Then var's value is matched to it and matching part removed.
6446 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006447//FIXME: ${x#...${...}...}
6448//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6449//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006450 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006451 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006452 char *exp_exp_word;
6453 char *loc;
6454 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006455 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006456 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006457 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006458 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006459 if (exp_exp_word)
6460 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006461 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6462 /*
6463 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006464 * G.global_argv and results of utoa and get_local_var_value
6465 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006466 * scan_and_match momentarily stores NULs there.
6467 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006468 t = (char*)val;
6469 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006470 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 +02006471 free(exp_exp_word);
6472 if (loc) { /* match was found */
6473 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006474 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006476 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006477 }
6478 }
6479 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006480#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006481 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006482 /* It's ${var/[/]pattern[/repl]} thing.
6483 * Note that in encoded form it has TWO parts:
6484 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006485 * and if // is used, it is encoded as \:
6486 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006487 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006489 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006490 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006491 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006492 * >az >bz
6493 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6494 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6495 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6496 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006497 * (note that a*z _pattern_ is never globbed!)
6498 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006499 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006500 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006501 if (!pattern)
6502 pattern = xstrdup(exp_word);
6503 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6504 *p++ = SPECIAL_VAR_SYMBOL;
6505 exp_word = p;
6506 p = strchr(p, SPECIAL_VAR_SYMBOL);
6507 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006508 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006509 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6510 /* HACK ALERT. We depend here on the fact that
6511 * G.global_argv and results of utoa and get_local_var_value
6512 * are actually in writable memory:
6513 * replace_pattern momentarily stores NULs there. */
6514 t = (char*)val;
6515 to_be_freed = replace_pattern(t,
6516 pattern,
6517 (repl ? repl : exp_word),
6518 exp_op);
6519 if (to_be_freed) /* at least one replace happened */
6520 val = to_be_freed;
6521 free(pattern);
6522 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006523 } else {
6524 /* Empty variable always gives nothing */
6525 // "v=''; echo ${v/*/w}" prints "", not "w"
6526 /* Just skip "replace" part */
6527 *p++ = SPECIAL_VAR_SYMBOL;
6528 p = strchr(p, SPECIAL_VAR_SYMBOL);
6529 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006530 }
6531 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006532#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006534#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006535 /* It's ${var:N[:M]} bashism.
6536 * Note that in encoded form it has TWO parts:
6537 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6538 */
6539 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006540 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006541
Denys Vlasenko063847d2010-09-15 13:33:02 +02006542 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6543 if (errmsg)
6544 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006545 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6546 *p++ = SPECIAL_VAR_SYMBOL;
6547 exp_word = p;
6548 p = strchr(p, SPECIAL_VAR_SYMBOL);
6549 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006550 len = expand_and_evaluate_arith(exp_word, &errmsg);
6551 if (errmsg)
6552 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006554 if (beg < 0) {
6555 /* negative beg counts from the end */
6556 beg = (arith_t)strlen(val) + beg;
6557 if (beg < 0) /* ${v: -999999} is "" */
6558 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006559 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006560 debug_printf_varexp("from val:'%s'\n", val);
6561 if (len < 0) {
6562 /* in bash, len=-n means strlen()-n */
6563 len = (arith_t)strlen(val) - beg + len;
6564 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006565 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006566 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006567 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006568 arith_err:
6569 val = NULL;
6570 } else {
6571 /* Paranoia. What if user entered 9999999999999
6572 * which fits in arith_t but not int? */
6573 if (len >= INT_MAX)
6574 len = INT_MAX;
6575 val = to_be_freed = xstrndup(val + beg, len);
6576 }
6577 debug_printf_varexp("val:'%s'\n", val);
6578#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006579 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006580 val = NULL;
6581#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006582 } else { /* one of "-=+?" */
6583 /* Standard-mandated substitution ops:
6584 * ${var?word} - indicate error if unset
6585 * If var is unset, word (or a message indicating it is unset
6586 * if word is null) is written to standard error
6587 * and the shell exits with a non-zero exit status.
6588 * Otherwise, the value of var is substituted.
6589 * ${var-word} - use default value
6590 * If var is unset, word is substituted.
6591 * ${var=word} - assign and use default value
6592 * If var is unset, word is assigned to var.
6593 * In all cases, final value of var is substituted.
6594 * ${var+word} - use alternative value
6595 * If var is unset, null is substituted.
6596 * Otherwise, word is substituted.
6597 *
6598 * Word is subjected to tilde expansion, parameter expansion,
6599 * command substitution, and arithmetic expansion.
6600 * If word is not needed, it is not expanded.
6601 *
6602 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6603 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006604 *
6605 * Word-splitting and single quote behavior:
6606 *
6607 * $ f() { for i; do echo "|$i|"; done; };
6608 *
6609 * $ x=; f ${x:?'x y' z}
6610 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6611 * $ x=; f "${x:?'x y' z}"
6612 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6613 *
6614 * $ x=; f ${x:='x y' z}
6615 * |x|
6616 * |y|
6617 * |z|
6618 * $ x=; f "${x:='x y' z}"
6619 * |'x y' z|
6620 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006621 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006622 * |x y|
6623 * |z|
6624 * $ x=x; f "${x:+'x y' z}"
6625 * |'x y' z|
6626 *
6627 * $ x=; f ${x:-'x y' z}
6628 * |x y|
6629 * |z|
6630 * $ x=; f "${x:-'x y' z}"
6631 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006632 */
6633 int use_word = (!val || ((exp_save == ':') && !val[0]));
6634 if (exp_op == '+')
6635 use_word = !use_word;
6636 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6637 (exp_save == ':') ? "true" : "false", use_word);
6638 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006639 if (exp_op == '+' || exp_op == '-') {
6640 /* ${var+word} - use alternative value */
6641 /* ${var-word} - use default value */
6642 n = encode_then_append_var_plusminus(output, n, exp_word,
6643 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006644 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006645 val = NULL;
6646 } else {
6647 /* ${var?word} - indicate error if unset */
6648 /* ${var=word} - assign and use default value */
6649 to_be_freed = encode_then_expand_vararg(exp_word,
6650 /*handle_squotes:*/ !(arg0 & 0x80),
6651 /*unbackslash:*/ 0
6652 );
6653 if (to_be_freed)
6654 exp_word = to_be_freed;
6655 if (exp_op == '?') {
6656 /* mimic bash message */
6657 msg_and_die_if_script("%s: %s",
6658 var,
6659 exp_word[0]
6660 ? exp_word
6661 : "parameter null or not set"
6662 /* ash has more specific messages, a-la: */
6663 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6664 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006665//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006666//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006667// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6668// bash: x: x y z
6669// $
6670// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006671 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006672 val = exp_word;
6673 }
6674 if (exp_op == '=') {
6675 /* ${var=[word]} or ${var:=[word]} */
6676 if (isdigit(var[0]) || var[0] == '#') {
6677 /* mimic bash message */
6678 msg_and_die_if_script("$%s: cannot assign in this way", var);
6679 val = NULL;
6680 } else {
6681 char *new_var = xasprintf("%s=%s", var, val);
6682 set_local_var(new_var, /*flag:*/ 0);
6683 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006684 }
6685 }
6686 }
6687 } /* one of "-=+?" */
6688
6689 *exp_saveptr = exp_save;
6690 } /* if (exp_op) */
6691
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006692 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006694
Denys Vlasenko168579a2018-07-19 13:45:54 +02006695 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006696
6697 free(to_be_freed);
6698 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006699}
6700
6701/* Expand all variable references in given string, adding words to list[]
6702 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6703 * to be filled). This routine is extremely tricky: has to deal with
6704 * variables/parameters with whitespace, $* and $@, and constructs like
6705 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006706static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006707{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006708 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006709 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006710 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006711 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006712 char *p;
6713
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006714 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6715 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006716 debug_print_list("expand_vars_to_list[0]", output, n);
6717
6718 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6719 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006720#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006721 char arith_buf[sizeof(arith_t)*3 + 2];
6722#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006723
Denys Vlasenko168579a2018-07-19 13:45:54 +02006724 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006725 o_addchr(output, '\0');
6726 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006727 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006728 }
6729
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006730 o_addblock(output, arg, p - arg);
6731 debug_print_list("expand_vars_to_list[1]", output, n);
6732 arg = ++p;
6733 p = strchr(p, SPECIAL_VAR_SYMBOL);
6734
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006735 /* Fetch special var name (if it is indeed one of them)
6736 * and quote bit, force the bit on if singleword expansion -
6737 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006738 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006739
6740 /* Is this variable quoted and thus expansion can't be null?
6741 * "$@" is special. Even if quoted, it can still
6742 * expand to nothing (not even an empty string),
6743 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006745 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006746
6747 switch (first_ch & 0x7f) {
6748 /* Highest bit in first_ch indicates that var is double-quoted */
6749 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006750 case '@': {
6751 int i;
6752 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006753 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006754 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006755 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006756 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006757 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006758 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006759 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6760 if (G.global_argv[i++][0] && G.global_argv[i]) {
6761 /* this argv[] is not empty and not last:
6762 * put terminating NUL, start new word */
6763 o_addchr(output, '\0');
6764 debug_print_list("expand_vars_to_list[2]", output, n);
6765 n = o_save_ptr(output, n);
6766 debug_print_list("expand_vars_to_list[3]", output, n);
6767 }
6768 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006770 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006771 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006772 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006773 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006774 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006775 while (1) {
6776 o_addQstr(output, G.global_argv[i]);
6777 if (++i >= G.global_argc)
6778 break;
6779 o_addchr(output, '\0');
6780 debug_print_list("expand_vars_to_list[4]", output, n);
6781 n = o_save_ptr(output, n);
6782 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006783 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784 while (1) {
6785 o_addQstr(output, G.global_argv[i]);
6786 if (!G.global_argv[++i])
6787 break;
6788 if (G.ifs[0])
6789 o_addchr(output, G.ifs[0]);
6790 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006791 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792 }
6793 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006794 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006795 case SPECIAL_VAR_SYMBOL: {
6796 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006797 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006798 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006799 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006800 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006801 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006802 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006803 case SPECIAL_VAR_QUOTED_SVS:
6804 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006805 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006806 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006807 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006808 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006810 case '`': {
6811 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006812 o_string subst_result = NULL_O_STRING;
6813
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006814 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006815 arg++;
6816 /* Can't just stuff it into output o_string,
6817 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006818 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006819 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6820 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006821 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006822 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006823 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006824 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006825 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006826 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006827#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006828#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006829 case '+': {
6830 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006831 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006832
6833 arg++; /* skip '+' */
6834 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6835 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006836 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006837 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6838 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006839 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006840 break;
6841 }
6842#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006843 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006844 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006845 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006846 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6848
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006849 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6850 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006851 if (*p != SPECIAL_VAR_SYMBOL)
6852 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006853 arg = ++p;
6854 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6855
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006856 if (*arg) {
6857 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006858 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006859 o_addchr(output, '\0');
6860 n = o_save_ptr(output, n);
6861 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006862 debug_print_list("expand_vars_to_list[a]", output, n);
6863 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006864 * if needed (much earlier), do not use o_addQstr here!
6865 */
6866 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006867 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006868 } else
6869 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006870 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6871 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006872 ) {
6873 n--;
6874 /* allow to reuse list[n] later without re-growth */
6875 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006876 }
6877
6878 return n;
6879}
6880
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006881static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006882{
6883 int n;
6884 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006885 o_string output = NULL_O_STRING;
6886
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006887 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006888
6889 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006890 for (;;) {
6891 /* go to next list[n] */
6892 output.ended_in_ifs = 0;
6893 n = o_save_ptr(&output, n);
6894
6895 if (!*argv)
6896 break;
6897
6898 /* expand argv[i] */
6899 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006900 /* if (!output->has_empty_slot) -- need this?? */
6901 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006902 }
6903 debug_print_list("expand_variables", &output, n);
6904
6905 /* output.data (malloced in one block) gets returned in "list" */
6906 list = o_finalize_list(&output, n);
6907 debug_print_strings("expand_variables[1]", list);
6908 return list;
6909}
6910
6911static char **expand_strvec_to_strvec(char **argv)
6912{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006913 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006914}
6915
Denys Vlasenko11752d42018-04-03 08:20:58 +02006916#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006917static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6918{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006919 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006920}
6921#endif
6922
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006923/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006924 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006925 *
6926 * NB: should NOT do globbing!
6927 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6928 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006929static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006930{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006931#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006932 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006933 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006934#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006935 char *argv[2], **list;
6936
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006937 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006938 /* This is generally an optimization, but it also
6939 * handles "", which otherwise trips over !list[0] check below.
6940 * (is this ever happens that we actually get str="" here?)
6941 */
6942 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6943 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006944 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006945 return xstrdup(str);
6946 }
6947
6948 argv[0] = (char*)str;
6949 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006950 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006951 if (!list[0]) {
6952 /* Example where it happens:
6953 * x=; echo ${x:-"$@"}
6954 */
6955 ((char*)list)[0] = '\0';
6956 } else {
6957 if (HUSH_DEBUG)
6958 if (list[1])
6959 bb_error_msg_and_die("BUG in varexp2");
6960 /* actually, just move string 2*sizeof(char*) bytes back */
6961 overlapping_strcpy((char*)list, list[0]);
6962 if (do_unbackslash)
6963 unbackslash((char*)list);
6964 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006965 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006966 return (char*)list;
6967}
6968
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006969#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006970static char* expand_strvec_to_string(char **argv)
6971{
6972 char **list;
6973
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006974 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006975 /* Convert all NULs to spaces */
6976 if (list[0]) {
6977 int n = 1;
6978 while (list[n]) {
6979 if (HUSH_DEBUG)
6980 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6981 bb_error_msg_and_die("BUG in varexp3");
6982 /* bash uses ' ' regardless of $IFS contents */
6983 list[n][-1] = ' ';
6984 n++;
6985 }
6986 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006987 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006988 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6989 return (char*)list;
6990}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006991#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006992
6993static char **expand_assignments(char **argv, int count)
6994{
6995 int i;
6996 char **p;
6997
6998 G.expanded_assignments = p = NULL;
6999 /* Expand assignments into one string each */
7000 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007001 p = add_string_to_strings(p,
7002 expand_string_to_string(argv[i],
7003 EXP_FLAG_ESC_GLOB_CHARS,
7004 /*unbackslash:*/ 1
7005 )
7006 );
7007 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007008 }
7009 G.expanded_assignments = NULL;
7010 return p;
7011}
7012
7013
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007014static void switch_off_special_sigs(unsigned mask)
7015{
7016 unsigned sig = 0;
7017 while ((mask >>= 1) != 0) {
7018 sig++;
7019 if (!(mask & 1))
7020 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007021#if ENABLE_HUSH_TRAP
7022 if (G_traps) {
7023 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007024 /* trap is '', has to remain SIG_IGN */
7025 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007026 free(G_traps[sig]);
7027 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007028 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007029#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007030 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007031 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007032 }
7033}
7034
Denys Vlasenkob347df92011-08-09 22:49:15 +02007035#if BB_MMU
7036/* never called */
7037void re_execute_shell(char ***to_free, const char *s,
7038 char *g_argv0, char **g_argv,
7039 char **builtin_argv) NORETURN;
7040
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007041static void reset_traps_to_defaults(void)
7042{
7043 /* This function is always called in a child shell
7044 * after fork (not vfork, NOMMU doesn't use this function).
7045 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007046 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007047 unsigned mask;
7048
7049 /* Child shells are not interactive.
7050 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7051 * Testcase: (while :; do :; done) + ^Z should background.
7052 * Same goes for SIGTERM, SIGHUP, SIGINT.
7053 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007054 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007055 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007056 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007057
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007058 /* Switch off special sigs */
7059 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007060# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007061 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007062# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007063 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007064 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7065 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007066
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007067# if ENABLE_HUSH_TRAP
7068 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007069 return;
7070
7071 /* Reset all sigs to default except ones with empty traps */
7072 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007073 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007074 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007075 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007076 continue; /* empty trap: has to remain SIG_IGN */
7077 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007078 free(G_traps[sig]);
7079 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007080 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007081 if (sig == 0)
7082 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007083 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007084 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007085# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007086}
7087
7088#else /* !BB_MMU */
7089
7090static void re_execute_shell(char ***to_free, const char *s,
7091 char *g_argv0, char **g_argv,
7092 char **builtin_argv) NORETURN;
7093static void re_execute_shell(char ***to_free, const char *s,
7094 char *g_argv0, char **g_argv,
7095 char **builtin_argv)
7096{
7097# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7098 /* delims + 2 * (number of bytes in printed hex numbers) */
7099 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7100 char *heredoc_argv[4];
7101 struct variable *cur;
7102# if ENABLE_HUSH_FUNCTIONS
7103 struct function *funcp;
7104# endif
7105 char **argv, **pp;
7106 unsigned cnt;
7107 unsigned long long empty_trap_mask;
7108
7109 if (!g_argv0) { /* heredoc */
7110 argv = heredoc_argv;
7111 argv[0] = (char *) G.argv0_for_re_execing;
7112 argv[1] = (char *) "-<";
7113 argv[2] = (char *) s;
7114 argv[3] = NULL;
7115 pp = &argv[3]; /* used as pointer to empty environment */
7116 goto do_exec;
7117 }
7118
7119 cnt = 0;
7120 pp = builtin_argv;
7121 if (pp) while (*pp++)
7122 cnt++;
7123
7124 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007125 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007126 int sig;
7127 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007128 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007129 empty_trap_mask |= 1LL << sig;
7130 }
7131 }
7132
7133 sprintf(param_buf, NOMMU_HACK_FMT
7134 , (unsigned) G.root_pid
7135 , (unsigned) G.root_ppid
7136 , (unsigned) G.last_bg_pid
7137 , (unsigned) G.last_exitcode
7138 , cnt
7139 , empty_trap_mask
7140 IF_HUSH_LOOPS(, G.depth_of_loop)
7141 );
7142# undef NOMMU_HACK_FMT
7143 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7144 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7145 */
7146 cnt += 6;
7147 for (cur = G.top_var; cur; cur = cur->next) {
7148 if (!cur->flg_export || cur->flg_read_only)
7149 cnt += 2;
7150 }
7151# if ENABLE_HUSH_FUNCTIONS
7152 for (funcp = G.top_func; funcp; funcp = funcp->next)
7153 cnt += 3;
7154# endif
7155 pp = g_argv;
7156 while (*pp++)
7157 cnt++;
7158 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7159 *pp++ = (char *) G.argv0_for_re_execing;
7160 *pp++ = param_buf;
7161 for (cur = G.top_var; cur; cur = cur->next) {
7162 if (strcmp(cur->varstr, hush_version_str) == 0)
7163 continue;
7164 if (cur->flg_read_only) {
7165 *pp++ = (char *) "-R";
7166 *pp++ = cur->varstr;
7167 } else if (!cur->flg_export) {
7168 *pp++ = (char *) "-V";
7169 *pp++ = cur->varstr;
7170 }
7171 }
7172# if ENABLE_HUSH_FUNCTIONS
7173 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7174 *pp++ = (char *) "-F";
7175 *pp++ = funcp->name;
7176 *pp++ = funcp->body_as_string;
7177 }
7178# endif
7179 /* We can pass activated traps here. Say, -Tnn:trap_string
7180 *
7181 * However, POSIX says that subshells reset signals with traps
7182 * to SIG_DFL.
7183 * I tested bash-3.2 and it not only does that with true subshells
7184 * of the form ( list ), but with any forked children shells.
7185 * I set trap "echo W" WINCH; and then tried:
7186 *
7187 * { echo 1; sleep 20; echo 2; } &
7188 * while true; do echo 1; sleep 20; echo 2; break; done &
7189 * true | { echo 1; sleep 20; echo 2; } | cat
7190 *
7191 * In all these cases sending SIGWINCH to the child shell
7192 * did not run the trap. If I add trap "echo V" WINCH;
7193 * _inside_ group (just before echo 1), it works.
7194 *
7195 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007196 */
7197 *pp++ = (char *) "-c";
7198 *pp++ = (char *) s;
7199 if (builtin_argv) {
7200 while (*++builtin_argv)
7201 *pp++ = *builtin_argv;
7202 *pp++ = (char *) "";
7203 }
7204 *pp++ = g_argv0;
7205 while (*g_argv)
7206 *pp++ = *g_argv++;
7207 /* *pp = NULL; - is already there */
7208 pp = environ;
7209
7210 do_exec:
7211 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007212 /* Don't propagate SIG_IGN to the child */
7213 if (SPECIAL_JOBSTOP_SIGS != 0)
7214 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007215 execve(bb_busybox_exec_path, argv, pp);
7216 /* Fallback. Useful for init=/bin/hush usage etc */
7217 if (argv[0][0] == '/')
7218 execve(argv[0], argv, pp);
7219 xfunc_error_retval = 127;
7220 bb_error_msg_and_die("can't re-execute the shell");
7221}
7222#endif /* !BB_MMU */
7223
7224
7225static int run_and_free_list(struct pipe *pi);
7226
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007227/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007228 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7229 * end_trigger controls how often we stop parsing
7230 * NUL: parse all, execute, return
7231 * ';': parse till ';' or newline, execute, repeat till EOF
7232 */
7233static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007234{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007235 /* Why we need empty flag?
7236 * An obscure corner case "false; ``; echo $?":
7237 * empty command in `` should still set $? to 0.
7238 * But we can't just set $? to 0 at the start,
7239 * this breaks "false; echo `echo $?`" case.
7240 */
7241 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007242 while (1) {
7243 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007244
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007245#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007246 if (end_trigger == ';') {
7247 G.promptmode = 0; /* PS1 */
7248 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7249 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007250#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007251 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007252 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7253 /* If we are in "big" script
7254 * (not in `cmd` or something similar)...
7255 */
7256 if (pipe_list == ERR_PTR && end_trigger == ';') {
7257 /* Discard cached input (rest of line) */
7258 int ch = inp->last_char;
7259 while (ch != EOF && ch != '\n') {
7260 //bb_error_msg("Discarded:'%c'", ch);
7261 ch = i_getch(inp);
7262 }
7263 /* Force prompt */
7264 inp->p = NULL;
7265 /* This stream isn't empty */
7266 empty = 0;
7267 continue;
7268 }
7269 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007270 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007271 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007272 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007273 debug_print_tree(pipe_list, 0);
7274 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7275 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007276 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007277 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007278 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007279 }
Eric Andersen25f27032001-04-26 23:22:31 +00007280}
7281
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007282static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007283{
7284 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007285 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007286
Eric Andersen25f27032001-04-26 23:22:31 +00007287 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007288 parse_and_run_stream(&input, '\0');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007289 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007290}
7291
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007292static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007293{
Eric Andersen25f27032001-04-26 23:22:31 +00007294 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007295 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007296
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007297 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007298 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007299 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007300 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007301}
7302
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007303#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007304static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007305{
7306 pid_t pid;
7307 int channel[2];
7308# if !BB_MMU
7309 char **to_free = NULL;
7310# endif
7311
7312 xpipe(channel);
7313 pid = BB_MMU ? xfork() : xvfork();
7314 if (pid == 0) { /* child */
7315 disable_restore_tty_pgrp_on_exit();
7316 /* Process substitution is not considered to be usual
7317 * 'command execution'.
7318 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7319 */
7320 bb_signals(0
7321 + (1 << SIGTSTP)
7322 + (1 << SIGTTIN)
7323 + (1 << SIGTTOU)
7324 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007325 close(channel[0]); /* NB: close _first_, then move fd! */
7326 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007327# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007328 /* Awful hack for `trap` or $(trap).
7329 *
7330 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7331 * contains an example where "trap" is executed in a subshell:
7332 *
7333 * save_traps=$(trap)
7334 * ...
7335 * eval "$save_traps"
7336 *
7337 * Standard does not say that "trap" in subshell shall print
7338 * parent shell's traps. It only says that its output
7339 * must have suitable form, but then, in the above example
7340 * (which is not supposed to be normative), it implies that.
7341 *
7342 * bash (and probably other shell) does implement it
7343 * (traps are reset to defaults, but "trap" still shows them),
7344 * but as a result, "trap" logic is hopelessly messed up:
7345 *
7346 * # trap
7347 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7348 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7349 * # true | trap <--- trap is in subshell - no output (ditto)
7350 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7351 * trap -- 'echo Ho' SIGWINCH
7352 * # echo `(trap)` <--- in subshell in subshell - output
7353 * trap -- 'echo Ho' SIGWINCH
7354 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7355 * trap -- 'echo Ho' SIGWINCH
7356 *
7357 * The rules when to forget and when to not forget traps
7358 * get really complex and nonsensical.
7359 *
7360 * Our solution: ONLY bare $(trap) or `trap` is special.
7361 */
7362 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007363 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007364 && skip_whitespace(s + 4)[0] == '\0'
7365 ) {
7366 static const char *const argv[] = { NULL, NULL };
7367 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007368 fflush_all(); /* important */
7369 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007370 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007371# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007372# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007373 /* Prevent it from trying to handle ctrl-z etc */
7374 IF_HUSH_JOB(G.run_list_level = 1;)
7375 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007376 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007377 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007378 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007379 parse_and_run_string(s);
7380 _exit(G.last_exitcode);
7381# else
7382 /* We re-execute after vfork on NOMMU. This makes this script safe:
7383 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7384 * huge=`cat BIG` # was blocking here forever
7385 * echo OK
7386 */
7387 re_execute_shell(&to_free,
7388 s,
7389 G.global_argv[0],
7390 G.global_argv + 1,
7391 NULL);
7392# endif
7393 }
7394
7395 /* parent */
7396 *pid_p = pid;
7397# if ENABLE_HUSH_FAST
7398 G.count_SIGCHLD++;
7399//bb_error_msg("[%d] fork in generate_stream_from_string:"
7400// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7401// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7402# endif
7403 enable_restore_tty_pgrp_on_exit();
7404# if !BB_MMU
7405 free(to_free);
7406# endif
7407 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007408 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007409}
7410
7411/* Return code is exit status of the process that is run. */
7412static int process_command_subs(o_string *dest, const char *s)
7413{
7414 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007415 pid_t pid;
7416 int status, ch, eol_cnt;
7417
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007418 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007419
7420 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007421 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007422 while ((ch = getc(fp)) != EOF) {
7423 if (ch == '\0')
7424 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007425 if (ch == '\n') {
7426 eol_cnt++;
7427 continue;
7428 }
7429 while (eol_cnt) {
7430 o_addchr(dest, '\n');
7431 eol_cnt--;
7432 }
7433 o_addQchr(dest, ch);
7434 }
7435
7436 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007437 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007438 /* We need to extract exitcode. Test case
7439 * "true; echo `sleep 1; false` $?"
7440 * should print 1 */
7441 safe_waitpid(pid, &status, 0);
7442 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7443 return WEXITSTATUS(status);
7444}
7445#endif /* ENABLE_HUSH_TICK */
7446
7447
7448static void setup_heredoc(struct redir_struct *redir)
7449{
7450 struct fd_pair pair;
7451 pid_t pid;
7452 int len, written;
7453 /* the _body_ of heredoc (misleading field name) */
7454 const char *heredoc = redir->rd_filename;
7455 char *expanded;
7456#if !BB_MMU
7457 char **to_free;
7458#endif
7459
7460 expanded = NULL;
7461 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007462 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007463 if (expanded)
7464 heredoc = expanded;
7465 }
7466 len = strlen(heredoc);
7467
7468 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7469 xpiped_pair(pair);
7470 xmove_fd(pair.rd, redir->rd_fd);
7471
7472 /* Try writing without forking. Newer kernels have
7473 * dynamically growing pipes. Must use non-blocking write! */
7474 ndelay_on(pair.wr);
7475 while (1) {
7476 written = write(pair.wr, heredoc, len);
7477 if (written <= 0)
7478 break;
7479 len -= written;
7480 if (len == 0) {
7481 close(pair.wr);
7482 free(expanded);
7483 return;
7484 }
7485 heredoc += written;
7486 }
7487 ndelay_off(pair.wr);
7488
7489 /* Okay, pipe buffer was not big enough */
7490 /* Note: we must not create a stray child (bastard? :)
7491 * for the unsuspecting parent process. Child creates a grandchild
7492 * and exits before parent execs the process which consumes heredoc
7493 * (that exec happens after we return from this function) */
7494#if !BB_MMU
7495 to_free = NULL;
7496#endif
7497 pid = xvfork();
7498 if (pid == 0) {
7499 /* child */
7500 disable_restore_tty_pgrp_on_exit();
7501 pid = BB_MMU ? xfork() : xvfork();
7502 if (pid != 0)
7503 _exit(0);
7504 /* grandchild */
7505 close(redir->rd_fd); /* read side of the pipe */
7506#if BB_MMU
7507 full_write(pair.wr, heredoc, len); /* may loop or block */
7508 _exit(0);
7509#else
7510 /* Delegate blocking writes to another process */
7511 xmove_fd(pair.wr, STDOUT_FILENO);
7512 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7513#endif
7514 }
7515 /* parent */
7516#if ENABLE_HUSH_FAST
7517 G.count_SIGCHLD++;
7518//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7519#endif
7520 enable_restore_tty_pgrp_on_exit();
7521#if !BB_MMU
7522 free(to_free);
7523#endif
7524 close(pair.wr);
7525 free(expanded);
7526 wait(NULL); /* wait till child has died */
7527}
7528
Denys Vlasenko2db74612017-07-07 22:07:28 +02007529struct squirrel {
7530 int orig_fd;
7531 int moved_to;
7532 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7533 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7534};
7535
Denys Vlasenko621fc502017-07-24 12:42:17 +02007536static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7537{
7538 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7539 sq[i].orig_fd = orig;
7540 sq[i].moved_to = moved;
7541 sq[i+1].orig_fd = -1; /* end marker */
7542 return sq;
7543}
7544
Denys Vlasenko2db74612017-07-07 22:07:28 +02007545static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7546{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007547 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007548 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007549
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007550 i = 0;
7551 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007552 /* If we collide with an already moved fd... */
7553 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007554 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007555 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7556 if (sq[i].moved_to < 0) /* what? */
7557 xfunc_die();
7558 return sq;
7559 }
7560 if (fd == sq[i].orig_fd) {
7561 /* Example: echo Hello >/dev/null 1>&2 */
7562 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7563 return sq;
7564 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007565 }
7566
Denys Vlasenko2db74612017-07-07 22:07:28 +02007567 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007568 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007569 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7570 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007571 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007572 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007573}
7574
Denys Vlasenko657e9002017-07-30 23:34:04 +02007575static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7576{
7577 int i;
7578
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007579 i = 0;
7580 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007581 /* If we collide with an already moved fd... */
7582 if (fd == sq[i].orig_fd) {
7583 /* Examples:
7584 * "echo 3>FILE 3>&- 3>FILE"
7585 * "echo 3>&- 3>FILE"
7586 * No need for last redirect to insert
7587 * another "need to close 3" indicator.
7588 */
7589 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7590 return sq;
7591 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007592 }
7593
7594 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7595 return append_squirrel(sq, i, fd, -1);
7596}
7597
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007598/* fd: redirect wants this fd to be used (e.g. 3>file).
7599 * Move all conflicting internally used fds,
7600 * and remember them so that we can restore them later.
7601 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007602static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007603{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007604 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7605 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007606
7607#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007608 if (fd == G_interactive_fd) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007609 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007610 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7611 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 +02007612 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007613 }
7614#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007615 /* Are we called from setup_redirects(squirrel==NULL)
7616 * in redirect in a [v]forked child?
7617 */
7618 if (sqp == NULL) {
7619 /* No need to move script fds.
7620 * For NOMMU case, it's actively wrong: we'd change ->fd
7621 * fields in memory for the parent, but parent's fds
7622 * aren't be moved, it would use wrong fd!
7623 * Reproducer: "cmd 3>FILE" in script.
7624 * If we would call move_HFILEs_on_redirect(), child would:
7625 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7626 * close(3) = 0
7627 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7628 */
7629 //bb_error_msg("sqp == NULL: [v]forked child");
7630 return 0;
7631 }
7632
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007633 /* If this one of script's fds? */
7634 if (move_HFILEs_on_redirect(fd, avoid_fd))
7635 return 1; /* yes. "we closed fd" (actually moved it) */
7636
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007637 /* Are we called for "exec 3>FILE"? Came through
7638 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7639 * This case used to fail for this script:
7640 * exec 3>FILE
7641 * echo Ok
7642 * ...100000 more lines...
7643 * echo Ok
7644 * as follows:
7645 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7646 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7647 * dup2(4, 3) = 3
7648 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7649 * close(4) = 0
7650 * write(1, "Ok\n", 3) = 3
7651 * ... = 3
7652 * write(1, "Ok\n", 3) = 3
7653 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7654 * ^^^^^^^^ oops, wrong fd!!!
7655 * With this case separate from sqp == NULL and *after* move_HFILEs,
7656 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007657 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007658 if (sqp == ERR_PTR) {
7659 /* Don't preserve redirected fds: exec is _meant_ to change these */
7660 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007661 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007662 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007663
Denys Vlasenko2db74612017-07-07 22:07:28 +02007664 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7665 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7666 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007667}
7668
Denys Vlasenko2db74612017-07-07 22:07:28 +02007669static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007670{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007671 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007672 int i;
7673 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007674 if (sq[i].moved_to >= 0) {
7675 /* We simply die on error */
7676 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7677 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7678 } else {
7679 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7680 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7681 close(sq[i].orig_fd);
7682 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007683 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007684 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007685 }
7686
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007687 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007688}
7689
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007690#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007691static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007692{
7693 if (G_interactive_fd)
7694 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007695 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007696}
7697#endif
7698
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007699static int internally_opened_fd(int fd, struct squirrel *sq)
7700{
7701 int i;
7702
7703#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007704 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007705 return 1;
7706#endif
7707 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007708 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007709 return 1;
7710
7711 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7712 if (fd == sq[i].moved_to)
7713 return 1;
7714 }
7715 return 0;
7716}
7717
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007718/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7719 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007720static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007721{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007722 struct redir_struct *redir;
7723
7724 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007725 int newfd;
7726 int closed;
7727
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007728 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007729 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007730 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007731 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7732 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007733 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007734 redir->rd_filename);
7735 setup_heredoc(redir);
7736 continue;
7737 }
7738
7739 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007740 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007741 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007742 int mode;
7743
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007744 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007745 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007746 * "cmd >" (no filename)
7747 * "cmd > <file" (2nd redirect starts too early)
7748 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007749 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007750 continue;
7751 }
7752 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007753 p = expand_string_to_string(redir->rd_filename,
7754 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007755 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007756 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007757 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007758 /* Error message from open_or_warn can be lost
7759 * if stderr has been redirected, but bash
7760 * and ash both lose it as well
7761 * (though zsh doesn't!)
7762 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007763 return 1;
7764 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007765 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007766 /* open() gave us precisely the fd we wanted.
7767 * This means that this fd was not busy
7768 * (not opened to anywhere).
7769 * Remember to close it on restore:
7770 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007771 *sqp = add_squirrel_closed(*sqp, newfd);
7772 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007773 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007774 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007775 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7776 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007777 }
7778
Denys Vlasenko657e9002017-07-30 23:34:04 +02007779 if (newfd == redir->rd_fd)
7780 continue;
7781
7782 /* if "N>FILE": move newfd to redir->rd_fd */
7783 /* if "N>&M": dup newfd to redir->rd_fd */
7784 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7785
7786 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7787 if (newfd == REDIRFD_CLOSE) {
7788 /* "N>&-" means "close me" */
7789 if (!closed) {
7790 /* ^^^ optimization: saving may already
7791 * have closed it. If not... */
7792 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007793 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007794 /* Sometimes we do another close on restore, getting EBADF.
7795 * Consider "echo 3>FILE 3>&-"
7796 * first redirect remembers "need to close 3",
7797 * and second redirect closes 3! Restore code then closes 3 again.
7798 */
7799 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007800 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007801 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007802 //errno = EBADF;
7803 //bb_perror_msg_and_die("can't duplicate file descriptor");
7804 newfd = -1; /* same effect as code above */
7805 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007806 xdup2(newfd, redir->rd_fd);
7807 if (redir->rd_dup == REDIRFD_TO_FILE)
7808 /* "rd_fd > FILE" */
7809 close(newfd);
7810 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007811 }
7812 }
7813 return 0;
7814}
7815
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007816static char *find_in_path(const char *arg)
7817{
7818 char *ret = NULL;
7819 const char *PATH = get_local_var_value("PATH");
7820
7821 if (!PATH)
7822 return NULL;
7823
7824 while (1) {
7825 const char *end = strchrnul(PATH, ':');
7826 int sz = end - PATH; /* must be int! */
7827
7828 free(ret);
7829 if (sz != 0) {
7830 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7831 } else {
7832 /* We have xxx::yyyy in $PATH,
7833 * it means "use current dir" */
7834 ret = xstrdup(arg);
7835 }
7836 if (access(ret, F_OK) == 0)
7837 break;
7838
7839 if (*end == '\0') {
7840 free(ret);
7841 return NULL;
7842 }
7843 PATH = end + 1;
7844 }
7845
7846 return ret;
7847}
7848
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007849static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007850 const struct built_in_command *x,
7851 const struct built_in_command *end)
7852{
7853 while (x != end) {
7854 if (strcmp(name, x->b_cmd) != 0) {
7855 x++;
7856 continue;
7857 }
7858 debug_printf_exec("found builtin '%s'\n", name);
7859 return x;
7860 }
7861 return NULL;
7862}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007863static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007864{
7865 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7866}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007867static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007868{
7869 const struct built_in_command *x = find_builtin1(name);
7870 if (x)
7871 return x;
7872 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7873}
7874
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007875static void remove_nested_vars(void)
7876{
7877 struct variable *cur;
7878 struct variable **cur_pp;
7879
7880 cur_pp = &G.top_var;
7881 while ((cur = *cur_pp) != NULL) {
7882 if (cur->var_nest_level <= G.var_nest_level) {
7883 cur_pp = &cur->next;
7884 continue;
7885 }
7886 /* Unexport */
7887 if (cur->flg_export) {
7888 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7889 bb_unsetenv(cur->varstr);
7890 }
7891 /* Remove from global list */
7892 *cur_pp = cur->next;
7893 /* Free */
7894 if (!cur->max_len) {
7895 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7896 free(cur->varstr);
7897 }
7898 free(cur);
7899 }
7900}
7901
7902static void enter_var_nest_level(void)
7903{
7904 G.var_nest_level++;
7905 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7906
7907 /* Try: f() { echo -n .; f; }; f
7908 * struct variable::var_nest_level is uint16_t,
7909 * thus limiting recursion to < 2^16.
7910 * In any case, with 8 Mbyte stack SEGV happens
7911 * not too long after 2^16 recursions anyway.
7912 */
7913 if (G.var_nest_level > 0xff00)
7914 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7915}
7916
7917static void leave_var_nest_level(void)
7918{
7919 G.var_nest_level--;
7920 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7921 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7922 bb_error_msg_and_die("BUG: nesting underflow");
7923
7924 remove_nested_vars();
7925}
7926
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007927#if ENABLE_HUSH_FUNCTIONS
7928static struct function **find_function_slot(const char *name)
7929{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007930 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007931 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007932
7933 while ((funcp = *funcpp) != NULL) {
7934 if (strcmp(name, funcp->name) == 0) {
7935 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007936 break;
7937 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007938 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007939 }
7940 return funcpp;
7941}
7942
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007943static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007944{
7945 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007946 return funcp;
7947}
7948
7949/* Note: takes ownership on name ptr */
7950static struct function *new_function(char *name)
7951{
7952 struct function **funcpp = find_function_slot(name);
7953 struct function *funcp = *funcpp;
7954
7955 if (funcp != NULL) {
7956 struct command *cmd = funcp->parent_cmd;
7957 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7958 if (!cmd) {
7959 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7960 free(funcp->name);
7961 /* Note: if !funcp->body, do not free body_as_string!
7962 * This is a special case of "-F name body" function:
7963 * body_as_string was not malloced! */
7964 if (funcp->body) {
7965 free_pipe_list(funcp->body);
7966# if !BB_MMU
7967 free(funcp->body_as_string);
7968# endif
7969 }
7970 } else {
7971 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7972 cmd->argv[0] = funcp->name;
7973 cmd->group = funcp->body;
7974# if !BB_MMU
7975 cmd->group_as_string = funcp->body_as_string;
7976# endif
7977 }
7978 } else {
7979 debug_printf_exec("remembering new function '%s'\n", name);
7980 funcp = *funcpp = xzalloc(sizeof(*funcp));
7981 /*funcp->next = NULL;*/
7982 }
7983
7984 funcp->name = name;
7985 return funcp;
7986}
7987
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007988# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007989static void unset_func(const char *name)
7990{
7991 struct function **funcpp = find_function_slot(name);
7992 struct function *funcp = *funcpp;
7993
7994 if (funcp != NULL) {
7995 debug_printf_exec("freeing function '%s'\n", funcp->name);
7996 *funcpp = funcp->next;
7997 /* funcp is unlinked now, deleting it.
7998 * Note: if !funcp->body, the function was created by
7999 * "-F name body", do not free ->body_as_string
8000 * and ->name as they were not malloced. */
8001 if (funcp->body) {
8002 free_pipe_list(funcp->body);
8003 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008004# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008005 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008006# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008007 }
8008 free(funcp);
8009 }
8010}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008011# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008012
8013# if BB_MMU
8014#define exec_function(to_free, funcp, argv) \
8015 exec_function(funcp, argv)
8016# endif
8017static void exec_function(char ***to_free,
8018 const struct function *funcp,
8019 char **argv) NORETURN;
8020static void exec_function(char ***to_free,
8021 const struct function *funcp,
8022 char **argv)
8023{
8024# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008025 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008026
8027 argv[0] = G.global_argv[0];
8028 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008029 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008030
8031// Example when we are here: "cmd | func"
8032// func will run with saved-redirect fds open.
8033// $ f() { echo /proc/self/fd/*; }
8034// $ true | f
8035// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8036// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8037// Same in script:
8038// $ . ./SCRIPT
8039// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8040// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8041// They are CLOEXEC so external programs won't see them, but
8042// for "more correctness" we might want to close those extra fds here:
8043//? close_saved_fds_and_FILE_fds();
8044
Denys Vlasenko332e4112018-04-04 22:32:59 +02008045 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008046 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008047 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008048 IF_HUSH_LOCAL(G.func_nest_level++;)
8049
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008050 /* On MMU, funcp->body is always non-NULL */
8051 n = run_list(funcp->body);
8052 fflush_all();
8053 _exit(n);
8054# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008055//? close_saved_fds_and_FILE_fds();
8056
8057//TODO: check whether "true | func_with_return" works
8058
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008059 re_execute_shell(to_free,
8060 funcp->body_as_string,
8061 G.global_argv[0],
8062 argv + 1,
8063 NULL);
8064# endif
8065}
8066
8067static int run_function(const struct function *funcp, char **argv)
8068{
8069 int rc;
8070 save_arg_t sv;
8071 smallint sv_flg;
8072
8073 save_and_replace_G_args(&sv, argv);
8074
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008075 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008076 sv_flg = G_flag_return_in_progress;
8077 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008078
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008079 /* Make "local" variables properly shadow previous ones */
8080 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008081 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008082
8083 /* On MMU, funcp->body is always non-NULL */
8084# if !BB_MMU
8085 if (!funcp->body) {
8086 /* Function defined by -F */
8087 parse_and_run_string(funcp->body_as_string);
8088 rc = G.last_exitcode;
8089 } else
8090# endif
8091 {
8092 rc = run_list(funcp->body);
8093 }
8094
Denys Vlasenko332e4112018-04-04 22:32:59 +02008095 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008096 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008097
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008098 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008099
8100 restore_G_args(&sv, argv);
8101
8102 return rc;
8103}
8104#endif /* ENABLE_HUSH_FUNCTIONS */
8105
8106
8107#if BB_MMU
8108#define exec_builtin(to_free, x, argv) \
8109 exec_builtin(x, argv)
8110#else
8111#define exec_builtin(to_free, x, argv) \
8112 exec_builtin(to_free, argv)
8113#endif
8114static void exec_builtin(char ***to_free,
8115 const struct built_in_command *x,
8116 char **argv) NORETURN;
8117static void exec_builtin(char ***to_free,
8118 const struct built_in_command *x,
8119 char **argv)
8120{
8121#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008122 int rcode;
8123 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008124//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008125 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008126 fflush_all();
8127 _exit(rcode);
8128#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008129 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008130 /* On NOMMU, we must never block!
8131 * Example: { sleep 99 | read line; } & echo Ok
8132 */
8133 re_execute_shell(to_free,
8134 argv[0],
8135 G.global_argv[0],
8136 G.global_argv + 1,
8137 argv);
8138#endif
8139}
8140
8141
8142static void execvp_or_die(char **argv) NORETURN;
8143static void execvp_or_die(char **argv)
8144{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008145 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008146 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008147 /* Don't propagate SIG_IGN to the child */
8148 if (SPECIAL_JOBSTOP_SIGS != 0)
8149 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008150 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008151 e = 2;
8152 if (errno == EACCES) e = 126;
8153 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008154 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008155 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008156}
8157
8158#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008159static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008160{
8161 unsigned len;
8162 const char *cp;
8163
8164 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008165
8166 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8167 /* test a char with: bash -c 'set -x; echo "CH"' */
8168 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8169 " " "\001\002\003\004\005\006\007"
8170 "\010\011\012\013\014\015\016\017"
8171 "\020\021\022\023\024\025\026\027"
8172 "\030\031\032\033\034\035\036\037"
8173 )
8174 ] == '\0'
8175 ) {
8176 /* string has no special chars */
8177 x_mode_addstr(str);
8178 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008179 }
8180
8181 cp = str;
8182 for (;;) {
8183 /* print '....' up to EOL or first squote */
8184 len = (int)(strchrnul(cp, '\'') - cp);
8185 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008186 x_mode_addchr('\'');
8187 x_mode_addblock(cp, len);
8188 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008189 cp += len;
8190 }
8191 if (*cp == '\0')
8192 break;
8193 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008194 x_mode_addchr('\\');
8195 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008196 cp++;
8197 }
8198}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008199static void dump_cmd_in_x_mode(char **argv)
8200{
8201 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008202 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008203
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008204 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008205 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008206 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008207 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008208 x_mode_addchr(' ');
8209 if (argv[n][0] == '\0') {
8210 x_mode_addchr('\'');
8211 x_mode_addchr('\'');
8212 } else {
8213 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008214 }
8215 n++;
8216 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008217 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008218 }
8219}
8220#else
8221# define dump_cmd_in_x_mode(argv) ((void)0)
8222#endif
8223
Denys Vlasenko57000292018-01-12 14:41:45 +01008224#if ENABLE_HUSH_COMMAND
8225static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8226{
8227 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008228
Denys Vlasenko57000292018-01-12 14:41:45 +01008229 if (!opt_vV)
8230 return;
8231
8232 to_free = NULL;
8233 if (!explanation) {
8234 char *path = getenv("PATH");
8235 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008236 if (!explanation)
8237 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008238 if (opt_vV != 'V')
8239 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8240 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008241 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008242 free(to_free);
8243 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008244 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008245}
8246#else
8247# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8248#endif
8249
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008250#if BB_MMU
8251#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8252 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8253#define pseudo_exec(nommu_save, command, argv_expanded) \
8254 pseudo_exec(command, argv_expanded)
8255#endif
8256
8257/* Called after [v]fork() in run_pipe, or from builtin_exec.
8258 * Never returns.
8259 * Don't exit() here. If you don't exec, use _exit instead.
8260 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008261 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008262 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008263static void pseudo_exec_argv(nommu_save_t *nommu_save,
8264 char **argv, int assignment_cnt,
8265 char **argv_expanded) NORETURN;
8266static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8267 char **argv, int assignment_cnt,
8268 char **argv_expanded)
8269{
Denys Vlasenko57000292018-01-12 14:41:45 +01008270 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008271 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008272 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008273 IF_HUSH_COMMAND(char opt_vV = 0;)
8274 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008275
8276 new_env = expand_assignments(argv, assignment_cnt);
8277 dump_cmd_in_x_mode(new_env);
8278
8279 if (!argv[assignment_cnt]) {
8280 /* Case when we are here: ... | var=val | ...
8281 * (note that we do not exit early, i.e., do not optimize out
8282 * expand_assignments(): think about ... | var=`sleep 1` | ...
8283 */
8284 free_strings(new_env);
8285 _exit(EXIT_SUCCESS);
8286 }
8287
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008288 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008289#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008290 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008291#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008292 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008293 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008294#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008295 set_vars_and_save_old(new_env);
8296 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008297
8298 if (argv_expanded) {
8299 argv = argv_expanded;
8300 } else {
8301 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8302#if !BB_MMU
8303 nommu_save->argv = argv;
8304#endif
8305 }
8306 dump_cmd_in_x_mode(argv);
8307
8308#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8309 if (strchr(argv[0], '/') != NULL)
8310 goto skip;
8311#endif
8312
Denys Vlasenko75481d32017-07-31 05:27:09 +02008313#if ENABLE_HUSH_FUNCTIONS
8314 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008315 funcp = find_function(argv[0]);
8316 if (funcp)
8317 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008318#endif
8319
Denys Vlasenko57000292018-01-12 14:41:45 +01008320#if ENABLE_HUSH_COMMAND
8321 /* "command BAR": run BAR without looking it up among functions
8322 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8323 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8324 */
8325 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8326 char *p;
8327
8328 argv++;
8329 p = *argv;
8330 if (p[0] != '-' || !p[1])
8331 continue; /* bash allows "command command command [-OPT] BAR" */
8332
8333 for (;;) {
8334 p++;
8335 switch (*p) {
8336 case '\0':
8337 argv++;
8338 p = *argv;
8339 if (p[0] != '-' || !p[1])
8340 goto after_opts;
8341 continue; /* next arg is also -opts, process it too */
8342 case 'v':
8343 case 'V':
8344 opt_vV = *p;
8345 continue;
8346 default:
8347 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8348 }
8349 }
8350 }
8351 after_opts:
8352# if ENABLE_HUSH_FUNCTIONS
8353 if (opt_vV && find_function(argv[0]))
8354 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8355# endif
8356#endif
8357
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008358 /* Check if the command matches any of the builtins.
8359 * Depending on context, this might be redundant. But it's
8360 * easier to waste a few CPU cycles than it is to figure out
8361 * if this is one of those cases.
8362 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008363 /* Why "BB_MMU ? :" difference in logic? -
8364 * On NOMMU, it is more expensive to re-execute shell
8365 * just in order to run echo or test builtin.
8366 * It's better to skip it here and run corresponding
8367 * non-builtin later. */
8368 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8369 if (x) {
8370 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8371 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008372 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008373
8374#if ENABLE_FEATURE_SH_STANDALONE
8375 /* Check if the command matches any busybox applets */
8376 {
8377 int a = find_applet_by_name(argv[0]);
8378 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008379 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008380# if BB_MMU /* see above why on NOMMU it is not allowed */
8381 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008382 /* Do not leak open fds from opened script files etc.
8383 * Testcase: interactive "ls -l /proc/self/fd"
8384 * should not show tty fd open.
8385 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008386 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008387//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008388//This casuses test failures in
8389//redir_children_should_not_see_saved_fd_2.tests
8390//redir_children_should_not_see_saved_fd_3.tests
8391//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008392 /* Without this, "rm -i FILE" can't be ^C'ed: */
8393 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008394 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008395 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008396 }
8397# endif
8398 /* Re-exec ourselves */
8399 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008400 /* Don't propagate SIG_IGN to the child */
8401 if (SPECIAL_JOBSTOP_SIGS != 0)
8402 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008403 execv(bb_busybox_exec_path, argv);
8404 /* If they called chroot or otherwise made the binary no longer
8405 * executable, fall through */
8406 }
8407 }
8408#endif
8409
8410#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8411 skip:
8412#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008413 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008414 execvp_or_die(argv);
8415}
8416
8417/* Called after [v]fork() in run_pipe
8418 */
8419static void pseudo_exec(nommu_save_t *nommu_save,
8420 struct command *command,
8421 char **argv_expanded) NORETURN;
8422static void pseudo_exec(nommu_save_t *nommu_save,
8423 struct command *command,
8424 char **argv_expanded)
8425{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008426#if ENABLE_HUSH_FUNCTIONS
8427 if (command->cmd_type == CMD_FUNCDEF) {
8428 /* Ignore funcdefs in pipes:
8429 * true | f() { cmd }
8430 */
8431 _exit(0);
8432 }
8433#endif
8434
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008435 if (command->argv) {
8436 pseudo_exec_argv(nommu_save, command->argv,
8437 command->assignment_cnt, argv_expanded);
8438 }
8439
8440 if (command->group) {
8441 /* Cases when we are here:
8442 * ( list )
8443 * { list } &
8444 * ... | ( list ) | ...
8445 * ... | { list } | ...
8446 */
8447#if BB_MMU
8448 int rcode;
8449 debug_printf_exec("pseudo_exec: run_list\n");
8450 reset_traps_to_defaults();
8451 rcode = run_list(command->group);
8452 /* OK to leak memory by not calling free_pipe_list,
8453 * since this process is about to exit */
8454 _exit(rcode);
8455#else
8456 re_execute_shell(&nommu_save->argv_from_re_execing,
8457 command->group_as_string,
8458 G.global_argv[0],
8459 G.global_argv + 1,
8460 NULL);
8461#endif
8462 }
8463
8464 /* Case when we are here: ... | >file */
8465 debug_printf_exec("pseudo_exec'ed null command\n");
8466 _exit(EXIT_SUCCESS);
8467}
8468
8469#if ENABLE_HUSH_JOB
8470static const char *get_cmdtext(struct pipe *pi)
8471{
8472 char **argv;
8473 char *p;
8474 int len;
8475
8476 /* This is subtle. ->cmdtext is created only on first backgrounding.
8477 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8478 * On subsequent bg argv is trashed, but we won't use it */
8479 if (pi->cmdtext)
8480 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008481
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008482 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008483 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008484 pi->cmdtext = xzalloc(1);
8485 return pi->cmdtext;
8486 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008487 len = 0;
8488 do {
8489 len += strlen(*argv) + 1;
8490 } while (*++argv);
8491 p = xmalloc(len);
8492 pi->cmdtext = p;
8493 argv = pi->cmds[0].argv;
8494 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008495 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008496 *p++ = ' ';
8497 } while (*++argv);
8498 p[-1] = '\0';
8499 return pi->cmdtext;
8500}
8501
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008502static void remove_job_from_table(struct pipe *pi)
8503{
8504 struct pipe *prev_pipe;
8505
8506 if (pi == G.job_list) {
8507 G.job_list = pi->next;
8508 } else {
8509 prev_pipe = G.job_list;
8510 while (prev_pipe->next != pi)
8511 prev_pipe = prev_pipe->next;
8512 prev_pipe->next = pi->next;
8513 }
8514 G.last_jobid = 0;
8515 if (G.job_list)
8516 G.last_jobid = G.job_list->jobid;
8517}
8518
8519static void delete_finished_job(struct pipe *pi)
8520{
8521 remove_job_from_table(pi);
8522 free_pipe(pi);
8523}
8524
8525static void clean_up_last_dead_job(void)
8526{
8527 if (G.job_list && !G.job_list->alive_cmds)
8528 delete_finished_job(G.job_list);
8529}
8530
Denys Vlasenko16096292017-07-10 10:00:28 +02008531static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008532{
8533 struct pipe *job, **jobp;
8534 int i;
8535
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008536 clean_up_last_dead_job();
8537
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008538 /* Find the end of the list, and find next job ID to use */
8539 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008540 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008541 while ((job = *jobp) != NULL) {
8542 if (job->jobid > i)
8543 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008544 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008545 }
8546 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008547
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008548 /* Create a new job struct at the end */
8549 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008550 job->next = NULL;
8551 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8552 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8553 for (i = 0; i < pi->num_cmds; i++) {
8554 job->cmds[i].pid = pi->cmds[i].pid;
8555 /* all other fields are not used and stay zero */
8556 }
8557 job->cmdtext = xstrdup(get_cmdtext(pi));
8558
8559 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008560 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008561 G.last_jobid = job->jobid;
8562}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008563#endif /* JOB */
8564
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008565static int job_exited_or_stopped(struct pipe *pi)
8566{
8567 int rcode, i;
8568
8569 if (pi->alive_cmds != pi->stopped_cmds)
8570 return -1;
8571
8572 /* All processes in fg pipe have exited or stopped */
8573 rcode = 0;
8574 i = pi->num_cmds;
8575 while (--i >= 0) {
8576 rcode = pi->cmds[i].cmd_exitcode;
8577 /* usually last process gives overall exitstatus,
8578 * but with "set -o pipefail", last *failed* process does */
8579 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8580 break;
8581 }
8582 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8583 return rcode;
8584}
8585
Denys Vlasenko7e675362016-10-28 21:57:31 +02008586static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008587{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008588#if ENABLE_HUSH_JOB
8589 struct pipe *pi;
8590#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008591 int i, dead;
8592
8593 dead = WIFEXITED(status) || WIFSIGNALED(status);
8594
8595#if DEBUG_JOBS
8596 if (WIFSTOPPED(status))
8597 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8598 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8599 if (WIFSIGNALED(status))
8600 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8601 childpid, WTERMSIG(status), WEXITSTATUS(status));
8602 if (WIFEXITED(status))
8603 debug_printf_jobs("pid %d exited, exitcode %d\n",
8604 childpid, WEXITSTATUS(status));
8605#endif
8606 /* Were we asked to wait for a fg pipe? */
8607 if (fg_pipe) {
8608 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008609
Denys Vlasenko7e675362016-10-28 21:57:31 +02008610 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008611 int rcode;
8612
Denys Vlasenko7e675362016-10-28 21:57:31 +02008613 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8614 if (fg_pipe->cmds[i].pid != childpid)
8615 continue;
8616 if (dead) {
8617 int ex;
8618 fg_pipe->cmds[i].pid = 0;
8619 fg_pipe->alive_cmds--;
8620 ex = WEXITSTATUS(status);
8621 /* bash prints killer signal's name for *last*
8622 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8623 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8624 */
8625 if (WIFSIGNALED(status)) {
8626 int sig = WTERMSIG(status);
8627 if (i == fg_pipe->num_cmds-1)
8628 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8629 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8630 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8631 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8632 * Maybe we need to use sig | 128? */
8633 ex = sig + 128;
8634 }
8635 fg_pipe->cmds[i].cmd_exitcode = ex;
8636 } else {
8637 fg_pipe->stopped_cmds++;
8638 }
8639 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8640 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008641 rcode = job_exited_or_stopped(fg_pipe);
8642 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008643/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8644 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8645 * and "killall -STOP cat" */
8646 if (G_interactive_fd) {
8647#if ENABLE_HUSH_JOB
8648 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008649 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008650#endif
8651 return rcode;
8652 }
8653 if (fg_pipe->alive_cmds == 0)
8654 return rcode;
8655 }
8656 /* There are still running processes in the fg_pipe */
8657 return -1;
8658 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008659 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008660 }
8661
8662#if ENABLE_HUSH_JOB
8663 /* We were asked to wait for bg or orphaned children */
8664 /* No need to remember exitcode in this case */
8665 for (pi = G.job_list; pi; pi = pi->next) {
8666 for (i = 0; i < pi->num_cmds; i++) {
8667 if (pi->cmds[i].pid == childpid)
8668 goto found_pi_and_prognum;
8669 }
8670 }
8671 /* Happens when shell is used as init process (init=/bin/sh) */
8672 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8673 return -1; /* this wasn't a process from fg_pipe */
8674
8675 found_pi_and_prognum:
8676 if (dead) {
8677 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008678 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008679 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008680 rcode = 128 + WTERMSIG(status);
8681 pi->cmds[i].cmd_exitcode = rcode;
8682 if (G.last_bg_pid == pi->cmds[i].pid)
8683 G.last_bg_pid_exitcode = rcode;
8684 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008685 pi->alive_cmds--;
8686 if (!pi->alive_cmds) {
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008687#if ENABLE_HUSH_BASH_COMPAT
8688 G.dead_job_exitcode = job_exited_or_stopped(pi);
8689#endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008690 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008691 printf(JOB_STATUS_FORMAT, pi->jobid,
8692 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008693 delete_finished_job(pi);
8694 } else {
8695/*
8696 * bash deletes finished jobs from job table only in interactive mode,
8697 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8698 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8699 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8700 * We only retain one "dead" job, if it's the single job on the list.
8701 * This covers most of real-world scenarios where this is useful.
8702 */
8703 if (pi != G.job_list)
8704 delete_finished_job(pi);
8705 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008706 }
8707 } else {
8708 /* child stopped */
8709 pi->stopped_cmds++;
8710 }
8711#endif
8712 return -1; /* this wasn't a process from fg_pipe */
8713}
8714
8715/* Check to see if any processes have exited -- if they have,
8716 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008717 *
8718 * If non-NULL fg_pipe: wait for its completion or stop.
8719 * Return its exitcode or zero if stopped.
8720 *
8721 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8722 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8723 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8724 * or 0 if no children changed status.
8725 *
8726 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8727 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8728 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008729 */
8730static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8731{
8732 int attributes;
8733 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008734 int rcode = 0;
8735
8736 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8737
8738 attributes = WUNTRACED;
8739 if (fg_pipe == NULL)
8740 attributes |= WNOHANG;
8741
8742 errno = 0;
8743#if ENABLE_HUSH_FAST
8744 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8745//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8746//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8747 /* There was neither fork nor SIGCHLD since last waitpid */
8748 /* Avoid doing waitpid syscall if possible */
8749 if (!G.we_have_children) {
8750 errno = ECHILD;
8751 return -1;
8752 }
8753 if (fg_pipe == NULL) { /* is WNOHANG set? */
8754 /* We have children, but they did not exit
8755 * or stop yet (we saw no SIGCHLD) */
8756 return 0;
8757 }
8758 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8759 }
8760#endif
8761
8762/* Do we do this right?
8763 * bash-3.00# sleep 20 | false
8764 * <ctrl-Z pressed>
8765 * [3]+ Stopped sleep 20 | false
8766 * bash-3.00# echo $?
8767 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8768 * [hush 1.14.0: yes we do it right]
8769 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008770 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008771 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008772#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008773 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008774 i = G.count_SIGCHLD;
8775#endif
8776 childpid = waitpid(-1, &status, attributes);
8777 if (childpid <= 0) {
8778 if (childpid && errno != ECHILD)
8779 bb_perror_msg("waitpid");
8780#if ENABLE_HUSH_FAST
8781 else { /* Until next SIGCHLD, waitpid's are useless */
8782 G.we_have_children = (childpid == 0);
8783 G.handled_SIGCHLD = i;
8784//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8785 }
8786#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008787 /* ECHILD (no children), or 0 (no change in children status) */
8788 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008789 break;
8790 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008791 rcode = process_wait_result(fg_pipe, childpid, status);
8792 if (rcode >= 0) {
8793 /* fg_pipe exited or stopped */
8794 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008795 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008796 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008797 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008798 rcode = WEXITSTATUS(status);
8799 if (WIFSIGNALED(status))
8800 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008801 if (WIFSTOPPED(status))
8802 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8803 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008804 rcode++;
8805 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008806 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008807#if ENABLE_HUSH_BASH_COMPAT
8808 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8809 && G.dead_job_exitcode >= 0 /* some job did finish */
8810 ) {
8811 debug_printf_exec("waitfor_pid:-1\n");
8812 rcode = G.dead_job_exitcode + 1;
8813 break;
8814 }
8815#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008816 /* This wasn't one of our processes, or */
8817 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008818 } /* while (waitpid succeeds)... */
8819
8820 return rcode;
8821}
8822
8823#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008824static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008825{
8826 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008827 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008828 if (G_saved_tty_pgrp) {
8829 /* Job finished, move the shell to the foreground */
8830 p = getpgrp(); /* our process group id */
8831 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8832 tcsetpgrp(G_interactive_fd, p);
8833 }
8834 return rcode;
8835}
8836#endif
8837
8838/* Start all the jobs, but don't wait for anything to finish.
8839 * See checkjobs().
8840 *
8841 * Return code is normally -1, when the caller has to wait for children
8842 * to finish to determine the exit status of the pipe. If the pipe
8843 * is a simple builtin command, however, the action is done by the
8844 * time run_pipe returns, and the exit code is provided as the
8845 * return value.
8846 *
8847 * Returns -1 only if started some children. IOW: we have to
8848 * mask out retvals of builtins etc with 0xff!
8849 *
8850 * The only case when we do not need to [v]fork is when the pipe
8851 * is single, non-backgrounded, non-subshell command. Examples:
8852 * cmd ; ... { list } ; ...
8853 * cmd && ... { list } && ...
8854 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008855 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008856 * or (if SH_STANDALONE) an applet, and we can run the { list }
8857 * with run_list. If it isn't one of these, we fork and exec cmd.
8858 *
8859 * Cases when we must fork:
8860 * non-single: cmd | cmd
8861 * backgrounded: cmd & { list } &
8862 * subshell: ( list ) [&]
8863 */
8864#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008865#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8866 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008867#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008868static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008869 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008870 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008871 char **argv_expanded)
8872{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008873 /* Assignments occur before redirects. Try:
8874 * a=`sleep 1` sleep 2 3>/qwe/rty
8875 */
8876
8877 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8878 dump_cmd_in_x_mode(new_env);
8879 dump_cmd_in_x_mode(argv_expanded);
8880 /* this takes ownership of new_env[i] elements, and frees new_env: */
8881 set_vars_and_save_old(new_env);
8882
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008883 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008884}
8885static NOINLINE int run_pipe(struct pipe *pi)
8886{
8887 static const char *const null_ptr = NULL;
8888
8889 int cmd_no;
8890 int next_infd;
8891 struct command *command;
8892 char **argv_expanded;
8893 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008894 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008895 int rcode;
8896
8897 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8898 debug_enter();
8899
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008900 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8901 * Result should be 3 lines: q w e, qwe, q w e
8902 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008903 if (G.ifs_whitespace != G.ifs)
8904 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008905 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008906 if (G.ifs) {
8907 char *p;
8908 G.ifs_whitespace = (char*)G.ifs;
8909 p = skip_whitespace(G.ifs);
8910 if (*p) {
8911 /* Not all $IFS is whitespace */
8912 char *d;
8913 int len = p - G.ifs;
8914 p = skip_non_whitespace(p);
8915 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8916 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8917 while (*p) {
8918 if (isspace(*p))
8919 *d++ = *p;
8920 p++;
8921 }
8922 *d = '\0';
8923 }
8924 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008925 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008926 G.ifs_whitespace = (char*)G.ifs;
8927 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008928
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008929 IF_HUSH_JOB(pi->pgrp = -1;)
8930 pi->stopped_cmds = 0;
8931 command = &pi->cmds[0];
8932 argv_expanded = NULL;
8933
8934 if (pi->num_cmds != 1
8935 || pi->followup == PIPE_BG
8936 || command->cmd_type == CMD_SUBSHELL
8937 ) {
8938 goto must_fork;
8939 }
8940
8941 pi->alive_cmds = 1;
8942
8943 debug_printf_exec(": group:%p argv:'%s'\n",
8944 command->group, command->argv ? command->argv[0] : "NONE");
8945
8946 if (command->group) {
8947#if ENABLE_HUSH_FUNCTIONS
8948 if (command->cmd_type == CMD_FUNCDEF) {
8949 /* "executing" func () { list } */
8950 struct function *funcp;
8951
8952 funcp = new_function(command->argv[0]);
8953 /* funcp->name is already set to argv[0] */
8954 funcp->body = command->group;
8955# if !BB_MMU
8956 funcp->body_as_string = command->group_as_string;
8957 command->group_as_string = NULL;
8958# endif
8959 command->group = NULL;
8960 command->argv[0] = NULL;
8961 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8962 funcp->parent_cmd = command;
8963 command->child_func = funcp;
8964
8965 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8966 debug_leave();
8967 return EXIT_SUCCESS;
8968 }
8969#endif
8970 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008971 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008972 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008973 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008974 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008975//FIXME: we need to pass squirrel down into run_list()
8976//for SH_STANDALONE case, or else this construct:
8977// { find /proc/self/fd; true; } >FILE; cmd2
8978//has no way of closing saved fd#1 for "find",
8979//and in SH_STANDALONE mode, "find" is not execed,
8980//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008981 rcode = run_list(command->group) & 0xff;
8982 }
8983 restore_redirects(squirrel);
8984 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8985 debug_leave();
8986 debug_printf_exec("run_pipe: return %d\n", rcode);
8987 return rcode;
8988 }
8989
8990 argv = command->argv ? command->argv : (char **) &null_ptr;
8991 {
8992 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008993 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8994 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008995 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008996 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008997
Denys Vlasenko5807e182018-02-08 19:19:04 +01008998#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02008999 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009000#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009001
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009002 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009003 /* Assignments, but no command.
9004 * Ensure redirects take effect (that is, create files).
9005 * Try "a=t >file"
9006 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009007 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009008 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009009 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009010 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009011 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009012
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009013 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009014 i = 0;
9015 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009016 char *p = expand_string_to_string(argv[i],
9017 EXP_FLAG_ESC_GLOB_CHARS,
9018 /*unbackslash:*/ 1
9019 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009020#if ENABLE_HUSH_MODE_X
9021 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009022 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009023 if (i == 0)
9024 x_mode_prefix();
9025 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009026 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009027 if (*eq) eq++;
9028 x_mode_addblock(p, (eq - p));
9029 x_mode_print_optionally_squoted(eq);
9030 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009031 }
9032#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009033 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009034 if (set_local_var(p, /*flag:*/ 0)) {
9035 /* assignment to readonly var / putenv error? */
9036 rcode = 1;
9037 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009038 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009039 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009040 /* Redirect error sets $? to 1. Otherwise,
9041 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009042 * Else, clear $?:
9043 * false; q=`exit 2`; echo $? - should print 2
9044 * false; x=1; echo $? - should print 0
9045 * Because of the 2nd case, we can't just use G.last_exitcode.
9046 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009047 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009048 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009049 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9050 debug_leave();
9051 debug_printf_exec("run_pipe: return %d\n", rcode);
9052 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009053 }
9054
9055 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02009056#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009057 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009058 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009059 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009060#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009061 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009062
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009063 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009064 if (!argv_expanded[0]) {
9065 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009066 /* `false` still has to set exitcode 1 */
9067 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009068 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009069 }
9070
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009071 old_vars = NULL;
9072 sv_shadowed = G.shadowed_vars_pp;
9073
Denys Vlasenko75481d32017-07-31 05:27:09 +02009074 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009075 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9076 IF_HUSH_FUNCTIONS(x = NULL;)
9077 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009078 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009079 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009080 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9081 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009082 /*
9083 * Variable assignments are executed, but then "forgotten":
9084 * a=`sleep 1;echo A` exec 3>&-; echo $a
9085 * sleeps, but prints nothing.
9086 */
9087 enter_var_nest_level();
9088 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009089 rcode = redirect_and_varexp_helper(command,
9090 /*squirrel:*/ ERR_PTR,
9091 argv_expanded
9092 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009093 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009094 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009095
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009096 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009097 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009098
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009099 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009100 * a=b true; env | grep ^a=
9101 */
9102 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009103 /* Collect all variables "shadowed" by helper
9104 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9105 * into old_vars list:
9106 */
9107 G.shadowed_vars_pp = &old_vars;
9108 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009109 if (rcode == 0) {
9110 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009111 /* Do not collect *to old_vars list* vars shadowed
9112 * by e.g. "local VAR" builtin (collect them
9113 * in the previously nested list instead):
9114 * don't want them to be restored immediately
9115 * after "local" completes.
9116 */
9117 G.shadowed_vars_pp = sv_shadowed;
9118
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009119 debug_printf_exec(": builtin '%s' '%s'...\n",
9120 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009121 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009122 rcode = x->b_function(argv_expanded) & 0xff;
9123 fflush_all();
9124 }
9125#if ENABLE_HUSH_FUNCTIONS
9126 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009127 debug_printf_exec(": function '%s' '%s'...\n",
9128 funcp->name, argv_expanded[1]);
9129 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009130 /*
9131 * But do collect *to old_vars list* vars shadowed
9132 * within function execution. To that end, restore
9133 * this pointer _after_ function run:
9134 */
9135 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009136 }
9137#endif
9138 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009139 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009140 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009141 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009142 if (n < 0 || !APPLET_IS_NOFORK(n))
9143 goto must_fork;
9144
9145 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009146 /* Collect all variables "shadowed" by helper into old_vars list */
9147 G.shadowed_vars_pp = &old_vars;
9148 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9149 G.shadowed_vars_pp = sv_shadowed;
9150
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009151 if (rcode == 0) {
9152 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9153 argv_expanded[0], argv_expanded[1]);
9154 /*
9155 * Note: signals (^C) can't interrupt here.
9156 * We remember them and they will be acted upon
9157 * after applet returns.
9158 * This makes applets which can run for a long time
9159 * and/or wait for user input ineligible for NOFORK:
9160 * for example, "yes" or "rm" (rm -i waits for input).
9161 */
9162 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009163 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009164 } else
9165 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009166
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009167 restore_redirects(squirrel);
9168 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009169 leave_var_nest_level();
9170 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009171
9172 /*
9173 * Try "usleep 99999999" + ^C + "echo $?"
9174 * with FEATURE_SH_NOFORK=y.
9175 */
9176 if (!funcp) {
9177 /* It was builtin or nofork.
9178 * if this would be a real fork/execed program,
9179 * it should have died if a fatal sig was received.
9180 * But OTOH, there was no separate process,
9181 * the sig was sent to _shell_, not to non-existing
9182 * child.
9183 * Let's just handle ^C only, this one is obvious:
9184 * we aren't ok with exitcode 0 when ^C was pressed
9185 * during builtin/nofork.
9186 */
9187 if (sigismember(&G.pending_set, SIGINT))
9188 rcode = 128 + SIGINT;
9189 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009190 free(argv_expanded);
9191 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9192 debug_leave();
9193 debug_printf_exec("run_pipe return %d\n", rcode);
9194 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009195 }
9196
9197 must_fork:
9198 /* NB: argv_expanded may already be created, and that
9199 * might include `cmd` runs! Do not rerun it! We *must*
9200 * use argv_expanded if it's non-NULL */
9201
9202 /* Going to fork a child per each pipe member */
9203 pi->alive_cmds = 0;
9204 next_infd = 0;
9205
9206 cmd_no = 0;
9207 while (cmd_no < pi->num_cmds) {
9208 struct fd_pair pipefds;
9209#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009210 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009211 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009212 nommu_save.old_vars = NULL;
9213 nommu_save.argv = NULL;
9214 nommu_save.argv_from_re_execing = NULL;
9215#endif
9216 command = &pi->cmds[cmd_no];
9217 cmd_no++;
9218 if (command->argv) {
9219 debug_printf_exec(": pipe member '%s' '%s'...\n",
9220 command->argv[0], command->argv[1]);
9221 } else {
9222 debug_printf_exec(": pipe member with no argv\n");
9223 }
9224
9225 /* pipes are inserted between pairs of commands */
9226 pipefds.rd = 0;
9227 pipefds.wr = 1;
9228 if (cmd_no < pi->num_cmds)
9229 xpiped_pair(pipefds);
9230
Denys Vlasenko5807e182018-02-08 19:19:04 +01009231#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009232 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009233#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009234
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009235 command->pid = BB_MMU ? fork() : vfork();
9236 if (!command->pid) { /* child */
9237#if ENABLE_HUSH_JOB
9238 disable_restore_tty_pgrp_on_exit();
9239 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9240
9241 /* Every child adds itself to new process group
9242 * with pgid == pid_of_first_child_in_pipe */
9243 if (G.run_list_level == 1 && G_interactive_fd) {
9244 pid_t pgrp;
9245 pgrp = pi->pgrp;
9246 if (pgrp < 0) /* true for 1st process only */
9247 pgrp = getpid();
9248 if (setpgid(0, pgrp) == 0
9249 && pi->followup != PIPE_BG
9250 && G_saved_tty_pgrp /* we have ctty */
9251 ) {
9252 /* We do it in *every* child, not just first,
9253 * to avoid races */
9254 tcsetpgrp(G_interactive_fd, pgrp);
9255 }
9256 }
9257#endif
9258 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9259 /* 1st cmd in backgrounded pipe
9260 * should have its stdin /dev/null'ed */
9261 close(0);
9262 if (open(bb_dev_null, O_RDONLY))
9263 xopen("/", O_RDONLY);
9264 } else {
9265 xmove_fd(next_infd, 0);
9266 }
9267 xmove_fd(pipefds.wr, 1);
9268 if (pipefds.rd > 1)
9269 close(pipefds.rd);
9270 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009271 * and the pipe fd (fd#1) is available for dup'ing:
9272 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9273 * of cmd1 goes into pipe.
9274 */
9275 if (setup_redirects(command, NULL)) {
9276 /* Happens when redir file can't be opened:
9277 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9278 * FOO
9279 * hush: can't open '/qwe/rty': No such file or directory
9280 * BAZ
9281 * (echo BAR is not executed, it hits _exit(1) below)
9282 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009283 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009284 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009285
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009286 /* Stores to nommu_save list of env vars putenv'ed
9287 * (NOMMU, on MMU we don't need that) */
9288 /* cast away volatility... */
9289 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9290 /* pseudo_exec() does not return */
9291 }
9292
9293 /* parent or error */
9294#if ENABLE_HUSH_FAST
9295 G.count_SIGCHLD++;
9296//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9297#endif
9298 enable_restore_tty_pgrp_on_exit();
9299#if !BB_MMU
9300 /* Clean up after vforked child */
9301 free(nommu_save.argv);
9302 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009303 G.var_nest_level = sv_var_nest_level;
9304 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009305 add_vars(nommu_save.old_vars);
9306#endif
9307 free(argv_expanded);
9308 argv_expanded = NULL;
9309 if (command->pid < 0) { /* [v]fork failed */
9310 /* Clearly indicate, was it fork or vfork */
9311 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9312 } else {
9313 pi->alive_cmds++;
9314#if ENABLE_HUSH_JOB
9315 /* Second and next children need to know pid of first one */
9316 if (pi->pgrp < 0)
9317 pi->pgrp = command->pid;
9318#endif
9319 }
9320
9321 if (cmd_no > 1)
9322 close(next_infd);
9323 if (cmd_no < pi->num_cmds)
9324 close(pipefds.wr);
9325 /* Pass read (output) pipe end to next iteration */
9326 next_infd = pipefds.rd;
9327 }
9328
9329 if (!pi->alive_cmds) {
9330 debug_leave();
9331 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9332 return 1;
9333 }
9334
9335 debug_leave();
9336 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9337 return -1;
9338}
9339
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009340/* NB: called by pseudo_exec, and therefore must not modify any
9341 * global data until exec/_exit (we can be a child after vfork!) */
9342static int run_list(struct pipe *pi)
9343{
9344#if ENABLE_HUSH_CASE
9345 char *case_word = NULL;
9346#endif
9347#if ENABLE_HUSH_LOOPS
9348 struct pipe *loop_top = NULL;
9349 char **for_lcur = NULL;
9350 char **for_list = NULL;
9351#endif
9352 smallint last_followup;
9353 smalluint rcode;
9354#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9355 smalluint cond_code = 0;
9356#else
9357 enum { cond_code = 0 };
9358#endif
9359#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009360 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009361 smallint last_rword; /* ditto */
9362#endif
9363
9364 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9365 debug_enter();
9366
9367#if ENABLE_HUSH_LOOPS
9368 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009369 {
9370 struct pipe *cpipe;
9371 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9372 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9373 continue;
9374 /* current word is FOR or IN (BOLD in comments below) */
9375 if (cpipe->next == NULL) {
9376 syntax_error("malformed for");
9377 debug_leave();
9378 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9379 return 1;
9380 }
9381 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9382 if (cpipe->next->res_word == RES_DO)
9383 continue;
9384 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9385 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9386 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9387 ) {
9388 syntax_error("malformed for");
9389 debug_leave();
9390 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9391 return 1;
9392 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009393 }
9394 }
9395#endif
9396
9397 /* Past this point, all code paths should jump to ret: label
9398 * in order to return, no direct "return" statements please.
9399 * This helps to ensure that no memory is leaked. */
9400
9401#if ENABLE_HUSH_JOB
9402 G.run_list_level++;
9403#endif
9404
9405#if HAS_KEYWORDS
9406 rword = RES_NONE;
9407 last_rword = RES_XXXX;
9408#endif
9409 last_followup = PIPE_SEQ;
9410 rcode = G.last_exitcode;
9411
9412 /* Go through list of pipes, (maybe) executing them. */
9413 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009414 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009415 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009416
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009417 if (G.flag_SIGINT)
9418 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009419 if (G_flag_return_in_progress == 1)
9420 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009421
9422 IF_HAS_KEYWORDS(rword = pi->res_word;)
9423 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9424 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009425
9426 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009427 if (
9428#if ENABLE_HUSH_IF
9429 rword == RES_IF || rword == RES_ELIF ||
9430#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009431 pi->followup != PIPE_SEQ
9432 ) {
9433 G.errexit_depth++;
9434 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009435#if ENABLE_HUSH_LOOPS
9436 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9437 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9438 ) {
9439 /* start of a loop: remember where loop starts */
9440 loop_top = pi;
9441 G.depth_of_loop++;
9442 }
9443#endif
9444 /* Still in the same "if...", "then..." or "do..." branch? */
9445 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9446 if ((rcode == 0 && last_followup == PIPE_OR)
9447 || (rcode != 0 && last_followup == PIPE_AND)
9448 ) {
9449 /* It is "<true> || CMD" or "<false> && CMD"
9450 * and we should not execute CMD */
9451 debug_printf_exec("skipped cmd because of || or &&\n");
9452 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009453 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009454 }
9455 }
9456 last_followup = pi->followup;
9457 IF_HAS_KEYWORDS(last_rword = rword;)
9458#if ENABLE_HUSH_IF
9459 if (cond_code) {
9460 if (rword == RES_THEN) {
9461 /* if false; then ... fi has exitcode 0! */
9462 G.last_exitcode = rcode = EXIT_SUCCESS;
9463 /* "if <false> THEN cmd": skip cmd */
9464 continue;
9465 }
9466 } else {
9467 if (rword == RES_ELSE || rword == RES_ELIF) {
9468 /* "if <true> then ... ELSE/ELIF cmd":
9469 * skip cmd and all following ones */
9470 break;
9471 }
9472 }
9473#endif
9474#if ENABLE_HUSH_LOOPS
9475 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9476 if (!for_lcur) {
9477 /* first loop through for */
9478
9479 static const char encoded_dollar_at[] ALIGN1 = {
9480 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9481 }; /* encoded representation of "$@" */
9482 static const char *const encoded_dollar_at_argv[] = {
9483 encoded_dollar_at, NULL
9484 }; /* argv list with one element: "$@" */
9485 char **vals;
9486
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009487 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009488 vals = (char**)encoded_dollar_at_argv;
9489 if (pi->next->res_word == RES_IN) {
9490 /* if no variable values after "in" we skip "for" */
9491 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009492 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9493 break;
9494 }
9495 vals = pi->next->cmds[0].argv;
9496 } /* else: "for var; do..." -> assume "$@" list */
9497 /* create list of variable values */
9498 debug_print_strings("for_list made from", vals);
9499 for_list = expand_strvec_to_strvec(vals);
9500 for_lcur = for_list;
9501 debug_print_strings("for_list", for_list);
9502 }
9503 if (!*for_lcur) {
9504 /* "for" loop is over, clean up */
9505 free(for_list);
9506 for_list = NULL;
9507 for_lcur = NULL;
9508 break;
9509 }
9510 /* Insert next value from for_lcur */
9511 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009512 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009513 continue;
9514 }
9515 if (rword == RES_IN) {
9516 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9517 }
9518 if (rword == RES_DONE) {
9519 continue; /* "done" has no cmds too */
9520 }
9521#endif
9522#if ENABLE_HUSH_CASE
9523 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009524 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009525 case_word = expand_string_to_string(pi->cmds->argv[0],
9526 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009527 debug_printf_exec("CASE word1:'%s'\n", case_word);
9528 //unbackslash(case_word);
9529 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009530 continue;
9531 }
9532 if (rword == RES_MATCH) {
9533 char **argv;
9534
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009535 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009536 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9537 break;
9538 /* all prev words didn't match, does this one match? */
9539 argv = pi->cmds->argv;
9540 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009541 char *pattern;
9542 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9543 pattern = expand_string_to_string(*argv,
9544 EXP_FLAG_ESC_GLOB_CHARS,
9545 /*unbackslash:*/ 0
9546 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009547 /* TODO: which FNM_xxx flags to use? */
9548 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009549 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9550 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009551 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009552 if (cond_code == 0) {
9553 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009554 free(case_word);
9555 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009556 break;
9557 }
9558 argv++;
9559 }
9560 continue;
9561 }
9562 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009563 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009564 if (cond_code != 0)
9565 continue; /* not matched yet, skip this pipe */
9566 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009567 if (rword == RES_ESAC) {
9568 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9569 if (case_word) {
9570 /* "case" did not match anything: still set $? (to 0) */
9571 G.last_exitcode = rcode = EXIT_SUCCESS;
9572 }
9573 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009574#endif
9575 /* Just pressing <enter> in shell should check for jobs.
9576 * OTOH, in non-interactive shell this is useless
9577 * and only leads to extra job checks */
9578 if (pi->num_cmds == 0) {
9579 if (G_interactive_fd)
9580 goto check_jobs_and_continue;
9581 continue;
9582 }
9583
9584 /* After analyzing all keywords and conditions, we decided
9585 * to execute this pipe. NB: have to do checkjobs(NULL)
9586 * after run_pipe to collect any background children,
9587 * even if list execution is to be stopped. */
9588 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009589#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009590 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009591#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009592 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9593 if (r != -1) {
9594 /* We ran a builtin, function, or group.
9595 * rcode is already known
9596 * and we don't need to wait for anything. */
9597 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9598 G.last_exitcode = rcode;
9599 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009600#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009601 /* Was it "break" or "continue"? */
9602 if (G.flag_break_continue) {
9603 smallint fbc = G.flag_break_continue;
9604 /* We might fall into outer *loop*,
9605 * don't want to break it too */
9606 if (loop_top) {
9607 G.depth_break_continue--;
9608 if (G.depth_break_continue == 0)
9609 G.flag_break_continue = 0;
9610 /* else: e.g. "continue 2" should *break* once, *then* continue */
9611 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9612 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009613 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009614 break;
9615 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009616 /* "continue": simulate end of loop */
9617 rword = RES_DONE;
9618 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009619 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009620#endif
9621 if (G_flag_return_in_progress == 1) {
9622 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9623 break;
9624 }
9625 } else if (pi->followup == PIPE_BG) {
9626 /* What does bash do with attempts to background builtins? */
9627 /* even bash 3.2 doesn't do that well with nested bg:
9628 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9629 * I'm NOT treating inner &'s as jobs */
9630#if ENABLE_HUSH_JOB
9631 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009632 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009633#endif
9634 /* Last command's pid goes to $! */
9635 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009636 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009637 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009638/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009639 rcode = EXIT_SUCCESS;
9640 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009641 } else {
9642#if ENABLE_HUSH_JOB
9643 if (G.run_list_level == 1 && G_interactive_fd) {
9644 /* Waits for completion, then fg's main shell */
9645 rcode = checkjobs_and_fg_shell(pi);
9646 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009647 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009648 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009649#endif
9650 /* This one just waits for completion */
9651 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9652 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9653 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009654 G.last_exitcode = rcode;
9655 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009656 }
9657
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009658 /* Handle "set -e" */
9659 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9660 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9661 if (G.errexit_depth == 0)
9662 hush_exit(rcode);
9663 }
9664 G.errexit_depth = sv_errexit_depth;
9665
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009666 /* Analyze how result affects subsequent commands */
9667#if ENABLE_HUSH_IF
9668 if (rword == RES_IF || rword == RES_ELIF)
9669 cond_code = rcode;
9670#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009671 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009672 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009673 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009674#if ENABLE_HUSH_LOOPS
9675 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009676 if (pi->next
9677 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009678 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009679 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009680 if (rword == RES_WHILE) {
9681 if (rcode) {
9682 /* "while false; do...done" - exitcode 0 */
9683 G.last_exitcode = rcode = EXIT_SUCCESS;
9684 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009685 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009686 }
9687 }
9688 if (rword == RES_UNTIL) {
9689 if (!rcode) {
9690 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009691 break;
9692 }
9693 }
9694 }
9695#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009696 } /* for (pi) */
9697
9698#if ENABLE_HUSH_JOB
9699 G.run_list_level--;
9700#endif
9701#if ENABLE_HUSH_LOOPS
9702 if (loop_top)
9703 G.depth_of_loop--;
9704 free(for_list);
9705#endif
9706#if ENABLE_HUSH_CASE
9707 free(case_word);
9708#endif
9709 debug_leave();
9710 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9711 return rcode;
9712}
9713
9714/* Select which version we will use */
9715static int run_and_free_list(struct pipe *pi)
9716{
9717 int rcode = 0;
9718 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009719 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009720 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9721 rcode = run_list(pi);
9722 }
9723 /* free_pipe_list has the side effect of clearing memory.
9724 * In the long run that function can be merged with run_list,
9725 * but doing that now would hobble the debugging effort. */
9726 free_pipe_list(pi);
9727 debug_printf_exec("run_and_free_list return %d\n", rcode);
9728 return rcode;
9729}
9730
9731
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009732static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009733{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009734 sighandler_t old_handler;
9735 unsigned sig = 0;
9736 while ((mask >>= 1) != 0) {
9737 sig++;
9738 if (!(mask & 1))
9739 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009740 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009741 /* POSIX allows shell to re-enable SIGCHLD
9742 * even if it was SIG_IGN on entry.
9743 * Therefore we skip IGN check for it:
9744 */
9745 if (sig == SIGCHLD)
9746 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009747 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9748 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9749 */
9750 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009751 if (old_handler == SIG_IGN) {
9752 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009753 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009754#if ENABLE_HUSH_TRAP
9755 if (!G_traps)
9756 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9757 free(G_traps[sig]);
9758 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9759#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009760 }
9761 }
9762}
9763
9764/* Called a few times only (or even once if "sh -c") */
9765static void install_special_sighandlers(void)
9766{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009767 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009768
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009769 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009770 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009771 if (G_interactive_fd) {
9772 mask |= SPECIAL_INTERACTIVE_SIGS;
9773 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009774 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009775 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009776 /* Careful, do not re-install handlers we already installed */
9777 if (G.special_sig_mask != mask) {
9778 unsigned diff = mask & ~G.special_sig_mask;
9779 G.special_sig_mask = mask;
9780 install_sighandlers(diff);
9781 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009782}
9783
9784#if ENABLE_HUSH_JOB
9785/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009786/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009787static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009788{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009789 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009790
9791 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009792 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009793 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9794 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009795 + (1 << SIGBUS ) * HUSH_DEBUG
9796 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009797 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009798 + (1 << SIGABRT)
9799 /* bash 3.2 seems to handle these just like 'fatal' ones */
9800 + (1 << SIGPIPE)
9801 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009802 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009803 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009804 * we never want to restore pgrp on exit, and this fn is not called
9805 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009806 /*+ (1 << SIGHUP )*/
9807 /*+ (1 << SIGTERM)*/
9808 /*+ (1 << SIGINT )*/
9809 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009810 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009811
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009812 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009813}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009814#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009815
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009816static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009817{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009818 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009819 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009820 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009821 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009822 break;
9823 case 'x':
9824 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009825 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 +01009826 break;
9827 case 'o':
9828 if (!o_opt) {
9829 /* "set -+o" without parameter.
9830 * in bash, set -o produces this output:
9831 * pipefail off
9832 * and set +o:
9833 * set +o pipefail
9834 * We always use the second form.
9835 */
9836 const char *p = o_opt_strings;
9837 idx = 0;
9838 while (*p) {
9839 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9840 idx++;
9841 p += strlen(p) + 1;
9842 }
9843 break;
9844 }
9845 idx = index_in_strings(o_opt_strings, o_opt);
9846 if (idx >= 0) {
9847 G.o_opt[idx] = state;
9848 break;
9849 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009850 case 'e':
9851 G.o_opt[OPT_O_ERREXIT] = state;
9852 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009853 default:
9854 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009855 }
9856 return EXIT_SUCCESS;
9857}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009858
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009859int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009860int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009861{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009862 enum {
9863 OPT_login = (1 << 0),
9864 };
9865 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009866 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009867 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009868 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009869 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009870
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009871 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009872 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009873 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009874
Denys Vlasenko10c01312011-05-11 11:49:21 +02009875#if ENABLE_HUSH_FAST
9876 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9877#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009878#if !BB_MMU
9879 G.argv0_for_re_execing = argv[0];
9880#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009881
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009882 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009883 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9884 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009885 shell_ver = xzalloc(sizeof(*shell_ver));
9886 shell_ver->flg_export = 1;
9887 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009888 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009889 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009890 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009891
Denys Vlasenko605067b2010-09-06 12:10:51 +02009892 /* Create shell local variables from the values
9893 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009894 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009895 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009896 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009897 if (e) while (*e) {
9898 char *value = strchr(*e, '=');
9899 if (value) { /* paranoia */
9900 cur_var->next = xzalloc(sizeof(*cur_var));
9901 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009902 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009903 cur_var->max_len = strlen(*e);
9904 cur_var->flg_export = 1;
9905 }
9906 e++;
9907 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009908 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009909 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9910 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009911
9912 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009913 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009914
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009915#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009916 /* Set (but not export) HOSTNAME unless already set */
9917 if (!get_local_var_value("HOSTNAME")) {
9918 struct utsname uts;
9919 uname(&uts);
9920 set_local_var_from_halves("HOSTNAME", uts.nodename);
9921 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02009922#endif
9923 /* IFS is not inherited from the parent environment */
9924 set_local_var_from_halves("IFS", defifs);
9925
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02009926 if (!get_local_var_value("PATH"))
9927 set_local_var_from_halves("PATH", bb_default_root_path);
9928
Denys Vlasenko0c360192019-05-19 15:37:50 +02009929 /* PS1/PS2 are set later, if we determine that we are interactive */
9930
Denys Vlasenko6db47842009-09-05 20:15:17 +02009931 /* bash also exports SHLVL and _,
9932 * and sets (but doesn't export) the following variables:
9933 * BASH=/bin/bash
9934 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9935 * BASH_VERSION='3.2.0(1)-release'
9936 * HOSTTYPE=i386
9937 * MACHTYPE=i386-pc-linux-gnu
9938 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009939 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009940 * EUID=<NNNNN>
9941 * UID=<NNNNN>
9942 * GROUPS=()
9943 * LINES=<NNN>
9944 * COLUMNS=<NNN>
9945 * BASH_ARGC=()
9946 * BASH_ARGV=()
9947 * BASH_LINENO=()
9948 * BASH_SOURCE=()
9949 * DIRSTACK=()
9950 * PIPESTATUS=([0]="0")
9951 * HISTFILE=/<xxx>/.bash_history
9952 * HISTFILESIZE=500
9953 * HISTSIZE=500
9954 * MAILCHECK=60
9955 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9956 * SHELL=/bin/bash
9957 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9958 * TERM=dumb
9959 * OPTERR=1
9960 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +02009961 * PS4='+ '
9962 */
9963
Eric Andersen94ac2442001-05-22 19:05:18 +00009964 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009965 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009966
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009967 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009968 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009969 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009970 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009971 * in order to intercept (more) signals.
9972 */
9973
9974 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009975 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009976 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009977 builtin_argc = 0;
Ron Yorston71df2d32018-11-27 14:34:25 +00009978#if NUM_SCRIPTS > 0
9979 if (argc < 0) {
9980 optarg = get_script_content(-argc - 1);
9981 optind = 0;
9982 argc = string_array_len(argv);
9983 goto run_script;
9984 }
9985#endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009986 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009987 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009988#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009989 "<:$:R:V:"
9990# if ENABLE_HUSH_FUNCTIONS
9991 "F:"
9992# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009993#endif
9994 );
9995 if (opt <= 0)
9996 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009997 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009998 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009999 /* Possibilities:
10000 * sh ... -c 'script'
10001 * sh ... -c 'script' ARG0 [ARG1...]
10002 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +010010003 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010004 * "" needs to be replaced with NULL
10005 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +010010006 * Note: the form without ARG0 never happens:
10007 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010008 */
Ron Yorston71df2d32018-11-27 14:34:25 +000010009#if NUM_SCRIPTS > 0
10010 run_script:
10011#endif
Denys Vlasenkodea47882009-10-09 15:40:49 +020010012 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010013 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010014 G.root_ppid = getppid();
10015 }
Denis Vlasenko87a86552008-07-29 19:43:10 +000010016 G.global_argv = argv + optind;
10017 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010018 if (builtin_argc) {
10019 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10020 const struct built_in_command *x;
10021
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010022 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010023 x = find_builtin(optarg);
10024 if (x) { /* paranoia */
10025 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10026 G.global_argv += builtin_argc;
10027 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +010010028 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +010010029 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010030 }
10031 goto final_return;
10032 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010033 G.opt_c = 1;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010034 if (!G.global_argv[0]) {
10035 /* -c 'script' (no params): prevent empty $0 */
10036 G.global_argv--; /* points to argv[i] of 'script' */
10037 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +020010038 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010039 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010040 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010041 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010042 goto final_return;
10043 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010044 /* Well, we cannot just declare interactiveness,
10045 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010046 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010047 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010048 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010049 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010050 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010051 case 'l':
10052 flags |= OPT_login;
10053 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010054#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010055 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010056 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010057 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010058 case '$': {
10059 unsigned long long empty_trap_mask;
10060
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010061 G.root_pid = bb_strtou(optarg, &optarg, 16);
10062 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010063 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10064 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010065 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10066 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010067 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010068 optarg++;
10069 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010070 optarg++;
10071 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10072 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010073 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010074 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010075# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010076 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010077 for (sig = 1; sig < NSIG; sig++) {
10078 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010079 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010080 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010081 }
10082 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010083# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010084 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010085# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010086 optarg++;
10087 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010088# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010089# if ENABLE_HUSH_FUNCTIONS
10090 /* nommu uses re-exec trick for "... | func | ...",
10091 * should allow "return".
10092 * This accidentally allows returns in subshells.
10093 */
10094 G_flag_return_in_progress = -1;
10095# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010096 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010097 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010098 case 'R':
10099 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010100 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010101 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010102# if ENABLE_HUSH_FUNCTIONS
10103 case 'F': {
10104 struct function *funcp = new_function(optarg);
10105 /* funcp->name is already set to optarg */
10106 /* funcp->body is set to NULL. It's a special case. */
10107 funcp->body_as_string = argv[optind];
10108 optind++;
10109 break;
10110 }
10111# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010112#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010113 case 'n':
10114 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010115 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010116 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010117 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010118 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010119#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010120 fprintf(stderr, "Usage: sh [FILE]...\n"
10121 " or: sh -c command [args]...\n\n");
10122 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010123#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010124 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010125#endif
Eric Andersen25f27032001-04-26 23:22:31 +000010126 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010127 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010128
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010129 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10130 G.global_argc = argc - (optind - 1);
10131 G.global_argv = argv + (optind - 1);
10132 G.global_argv[0] = argv[0];
10133
Denys Vlasenkodea47882009-10-09 15:40:49 +020010134 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010135 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010136 G.root_ppid = getppid();
10137 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010138
10139 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010140 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010141 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010142 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010143 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010144 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010145 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010146 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010147 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010148 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010149 /* bash: after sourcing /etc/profile,
10150 * tries to source (in the given order):
10151 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010152 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010153 * bash also sources ~/.bash_logout on exit.
10154 * If called as sh, skips .bash_XXX files.
10155 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010156 }
10157
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010158 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010159 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010160 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010161 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010162 * "bash <script>" (which is never interactive (unless -i?))
10163 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010164 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010165 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010166 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010167 G.global_argc--;
10168 G.global_argv++;
10169 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010170 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010171 input = hfopen(G.global_argv[0]);
10172 if (!input) {
10173 bb_simple_perror_msg_and_die(G.global_argv[0]);
10174 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010175 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010176 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010177 parse_and_run_file(input);
10178#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010179 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010180#endif
10181 goto final_return;
10182 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010183 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010184 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010185
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010186 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010187 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010188 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010189
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010190 /* A shell is interactive if the '-i' flag was given,
10191 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010192 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010193 * no arguments remaining or the -s flag given
10194 * standard input is a terminal
10195 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010196 * Refer to Posix.2, the description of the 'sh' utility.
10197 */
10198#if ENABLE_HUSH_JOB
10199 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010200 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10201 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10202 if (G_saved_tty_pgrp < 0)
10203 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010204
10205 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010206 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010207 if (G_interactive_fd < 0) {
10208 /* try to dup to any fd */
10209 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010210 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010211 /* give up */
10212 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010213 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010214 }
10215 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010216// TODO: track & disallow any attempts of user
10217// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010218 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010219 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010220 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010221 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010222
Mike Frysinger38478a62009-05-20 04:48:06 -040010223 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010224 /* If we were run as 'hush &', sleep until we are
10225 * in the foreground (tty pgrp == our pgrp).
10226 * If we get started under a job aware app (like bash),
10227 * make sure we are now in charge so we don't fight over
10228 * who gets the foreground */
10229 while (1) {
10230 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010231 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10232 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010233 break;
10234 /* send TTIN to ourself (should stop us) */
10235 kill(- shell_pgrp, SIGTTIN);
10236 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010237 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010238
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010239 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010240 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010241
Mike Frysinger38478a62009-05-20 04:48:06 -040010242 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010243 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010244 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010245 /* Put ourselves in our own process group
10246 * (bash, too, does this only if ctty is available) */
10247 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10248 /* Grab control of the terminal */
10249 tcsetpgrp(G_interactive_fd, getpid());
10250 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010251 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010252
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010253# if ENABLE_FEATURE_EDITING
10254 G.line_input_state = new_line_input_t(FOR_SHELL);
10255# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010256# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10257 {
10258 const char *hp = get_local_var_value("HISTFILE");
10259 if (!hp) {
10260 hp = get_local_var_value("HOME");
10261 if (hp)
10262 hp = concat_path_file(hp, ".hush_history");
10263 } else {
10264 hp = xstrdup(hp);
10265 }
10266 if (hp) {
10267 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010268 //set_local_var(xasprintf("HISTFILE=%s", ...));
10269 }
10270# if ENABLE_FEATURE_SH_HISTFILESIZE
10271 hp = get_local_var_value("HISTFILESIZE");
10272 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10273# endif
10274 }
10275# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010276 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010277 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010278 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010279#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010280 /* No job control compiled in, only prompt/line editing */
10281 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010282 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010283 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010284 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010285 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010286 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010287 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010288 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010289 }
10290 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010291 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010292 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010293 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010294 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010295#else
10296 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010297 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010298#endif
10299 /* bash:
10300 * if interactive but not a login shell, sources ~/.bashrc
10301 * (--norc turns this off, --rcfile <file> overrides)
10302 */
10303
Denys Vlasenko0c360192019-05-19 15:37:50 +020010304 if (G_interactive_fd) {
10305#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10306 /* Set (but not export) PS1/2 unless already set */
10307 if (!get_local_var_value("PS1"))
10308 set_local_var_from_halves("PS1", "\\w \\$ ");
10309 if (!get_local_var_value("PS2"))
10310 set_local_var_from_halves("PS2", "> ");
10311#endif
10312 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10313 /* note: ash and hush share this string */
10314 printf("\n\n%s %s\n"
10315 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10316 "\n",
10317 bb_banner,
10318 "hush - the humble shell"
10319 );
10320 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010321 }
10322
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010323 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010324
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010325 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010326 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010327}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010328
10329
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010330/*
10331 * Built-ins
10332 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010333static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010334{
10335 return 0;
10336}
10337
Denys Vlasenko265062d2017-01-10 15:13:30 +010010338#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010339static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010340{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010341 int argc = string_array_len(argv);
10342 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010343}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010344#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010345#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010346static int FAST_FUNC builtin_test(char **argv)
10347{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010348 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010349}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010350#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010351#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010352static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010353{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010354 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010355}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010356#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010357#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010358static int FAST_FUNC builtin_printf(char **argv)
10359{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010360 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010361}
10362#endif
10363
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010364#if ENABLE_HUSH_HELP
10365static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10366{
10367 const struct built_in_command *x;
10368
10369 printf(
10370 "Built-in commands:\n"
10371 "------------------\n");
10372 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10373 if (x->b_descr)
10374 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10375 }
10376 return EXIT_SUCCESS;
10377}
10378#endif
10379
10380#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10381static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10382{
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010383 if (G.line_input_state)
10384 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010385 return EXIT_SUCCESS;
10386}
10387#endif
10388
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010389static char **skip_dash_dash(char **argv)
10390{
10391 argv++;
10392 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10393 argv++;
10394 return argv;
10395}
10396
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010397static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010398{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010399 const char *newdir;
10400
10401 argv = skip_dash_dash(argv);
10402 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010403 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010404 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010405 * bash says "bash: cd: HOME not set" and does nothing
10406 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010407 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010408 const char *home = get_local_var_value("HOME");
10409 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010410 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010411 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010412 /* Mimic bash message exactly */
10413 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010414 return EXIT_FAILURE;
10415 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010416 /* Read current dir (get_cwd(1) is inside) and set PWD.
10417 * Note: do not enforce exporting. If PWD was unset or unexported,
10418 * set it again, but do not export. bash does the same.
10419 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010420 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010421 return EXIT_SUCCESS;
10422}
10423
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010424static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10425{
10426 puts(get_cwd(0));
10427 return EXIT_SUCCESS;
10428}
10429
10430static int FAST_FUNC builtin_eval(char **argv)
10431{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010432 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010433
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010434 if (!argv[0])
10435 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010436
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010437 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010438 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010439 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010440 /* bash:
10441 * eval "echo Hi; done" ("done" is syntax error):
10442 * "echo Hi" will not execute too.
10443 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010444 parse_and_run_string(argv[0]);
10445 } else {
10446 /* "The eval utility shall construct a command by
10447 * concatenating arguments together, separating
10448 * each with a <space> character."
10449 */
10450 char *str, *p;
10451 unsigned len = 0;
10452 char **pp = argv;
10453 do
10454 len += strlen(*pp) + 1;
10455 while (*++pp);
10456 str = p = xmalloc(len);
10457 pp = argv;
10458 for (;;) {
10459 p = stpcpy(p, *pp);
10460 pp++;
10461 if (!*pp)
10462 break;
10463 *p++ = ' ';
10464 }
10465 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010466 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010467 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010468 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010469 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010470 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010471}
10472
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010473static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010474{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010475 argv = skip_dash_dash(argv);
10476 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010477 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010478
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010479 /* Careful: we can end up here after [v]fork. Do not restore
10480 * tty pgrp then, only top-level shell process does that */
10481 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10482 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10483
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010484 /* Saved-redirect fds, script fds and G_interactive_fd are still
10485 * open here. However, they are all CLOEXEC, and execv below
10486 * closes them. Try interactive "exec ls -l /proc/self/fd",
10487 * it should show no extra open fds in the "ls" process.
10488 * If we'd try to run builtins/NOEXECs, this would need improving.
10489 */
10490 //close_saved_fds_and_FILE_fds();
10491
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010492 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010493 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010494 * and tcsetpgrp, and this is inherently racy.
10495 */
10496 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497}
10498
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010499static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010500{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010501 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010502
10503 /* interactive bash:
10504 * # trap "echo EEE" EXIT
10505 * # exit
10506 * exit
10507 * There are stopped jobs.
10508 * (if there are _stopped_ jobs, running ones don't count)
10509 * # exit
10510 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010511 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010512 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010513 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010514 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010515
10516 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010517 argv = skip_dash_dash(argv);
10518 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010519 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010520 /* mimic bash: exit 123abc == exit 255 + error msg */
10521 xfunc_error_retval = 255;
10522 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010523 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010524}
10525
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010526#if ENABLE_HUSH_TYPE
10527/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10528static int FAST_FUNC builtin_type(char **argv)
10529{
10530 int ret = EXIT_SUCCESS;
10531
10532 while (*++argv) {
10533 const char *type;
10534 char *path = NULL;
10535
10536 if (0) {} /* make conditional compile easier below */
10537 /*else if (find_alias(*argv))
10538 type = "an alias";*/
10539#if ENABLE_HUSH_FUNCTIONS
10540 else if (find_function(*argv))
10541 type = "a function";
10542#endif
10543 else if (find_builtin(*argv))
10544 type = "a shell builtin";
10545 else if ((path = find_in_path(*argv)) != NULL)
10546 type = path;
10547 else {
10548 bb_error_msg("type: %s: not found", *argv);
10549 ret = EXIT_FAILURE;
10550 continue;
10551 }
10552
10553 printf("%s is %s\n", *argv, type);
10554 free(path);
10555 }
10556
10557 return ret;
10558}
10559#endif
10560
10561#if ENABLE_HUSH_READ
10562/* Interruptibility of read builtin in bash
10563 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10564 *
10565 * Empty trap makes read ignore corresponding signal, for any signal.
10566 *
10567 * SIGINT:
10568 * - terminates non-interactive shell;
10569 * - interrupts read in interactive shell;
10570 * if it has non-empty trap:
10571 * - executes trap and returns to command prompt in interactive shell;
10572 * - executes trap and returns to read in non-interactive shell;
10573 * SIGTERM:
10574 * - is ignored (does not interrupt) read in interactive shell;
10575 * - terminates non-interactive shell;
10576 * if it has non-empty trap:
10577 * - executes trap and returns to read;
10578 * SIGHUP:
10579 * - terminates shell (regardless of interactivity);
10580 * if it has non-empty trap:
10581 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010582 * SIGCHLD from children:
10583 * - does not interrupt read regardless of interactivity:
10584 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010585 */
10586static int FAST_FUNC builtin_read(char **argv)
10587{
10588 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010589 struct builtin_read_params params;
10590
10591 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010592
10593 /* "!": do not abort on errors.
10594 * Option string must start with "sr" to match BUILTIN_READ_xxx
10595 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010596 params.read_flags = getopt32(argv,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010597#if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010598 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010599#else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010600 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010601#endif
10602 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010603 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010604 return EXIT_FAILURE;
10605 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010606 params.argv = argv;
10607 params.setvar = set_local_var_from_halves;
10608 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010609
10610 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010611 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010612
10613 if ((uintptr_t)r == 1 && errno == EINTR) {
10614 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010615 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010616 goto again;
10617 }
10618
10619 if ((uintptr_t)r > 1) {
10620 bb_error_msg("%s", r);
10621 r = (char*)(uintptr_t)1;
10622 }
10623
10624 return (uintptr_t)r;
10625}
10626#endif
10627
10628#if ENABLE_HUSH_UMASK
10629static int FAST_FUNC builtin_umask(char **argv)
10630{
10631 int rc;
10632 mode_t mask;
10633
10634 rc = 1;
10635 mask = umask(0);
10636 argv = skip_dash_dash(argv);
10637 if (argv[0]) {
10638 mode_t old_mask = mask;
10639
10640 /* numeric umasks are taken as-is */
10641 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10642 if (!isdigit(argv[0][0]))
10643 mask ^= 0777;
10644 mask = bb_parse_mode(argv[0], mask);
10645 if (!isdigit(argv[0][0]))
10646 mask ^= 0777;
10647 if ((unsigned)mask > 0777) {
10648 mask = old_mask;
10649 /* bash messages:
10650 * bash: umask: 'q': invalid symbolic mode operator
10651 * bash: umask: 999: octal number out of range
10652 */
10653 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10654 rc = 0;
10655 }
10656 } else {
10657 /* Mimic bash */
10658 printf("%04o\n", (unsigned) mask);
10659 /* fall through and restore mask which we set to 0 */
10660 }
10661 umask(mask);
10662
10663 return !rc; /* rc != 0 - success */
10664}
10665#endif
10666
Denys Vlasenko41ade052017-01-08 18:56:24 +010010667#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010668static void print_escaped(const char *s)
10669{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010670 if (*s == '\'')
10671 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010672 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010673 const char *p = strchrnul(s, '\'');
10674 /* print 'xxxx', possibly just '' */
10675 printf("'%.*s'", (int)(p - s), s);
10676 if (*p == '\0')
10677 break;
10678 s = p;
10679 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010680 /* s points to '; print "'''...'''" */
10681 putchar('"');
10682 do putchar('\''); while (*++s == '\'');
10683 putchar('"');
10684 } while (*s);
10685}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010686#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010687
Denys Vlasenko1e660422017-07-17 21:10:50 +020010688#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010689static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010690{
10691 do {
10692 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010693 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010694
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010695 if (*name_end == '\0') {
10696 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010697
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010698 vpp = get_ptr_to_local_var(name, name_end - name);
10699 var = vpp ? *vpp : NULL;
10700
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010701 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010702 /* export -n NAME (without =VALUE) */
10703 if (var) {
10704 var->flg_export = 0;
10705 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10706 unsetenv(name);
10707 } /* else: export -n NOT_EXISTING_VAR: no-op */
10708 continue;
10709 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010710 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010711 /* export NAME (without =VALUE) */
10712 if (var) {
10713 var->flg_export = 1;
10714 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10715 putenv(var->varstr);
10716 continue;
10717 }
10718 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010719 if (flags & SETFLAG_MAKE_RO) {
10720 /* readonly NAME (without =VALUE) */
10721 if (var) {
10722 var->flg_read_only = 1;
10723 continue;
10724 }
10725 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010726# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010727 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010728 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010729 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10730 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010731 /* "local x=abc; ...; local x" - ignore second local decl */
10732 continue;
10733 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010734 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010735# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010736 /* Exporting non-existing variable.
10737 * bash does not put it in environment,
10738 * but remembers that it is exported,
10739 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010740 * We just set it to "" and export.
10741 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010742 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010743 * bash sets the value to "".
10744 */
10745 /* Or, it's "readonly NAME" (without =VALUE).
10746 * bash remembers NAME and disallows its creation
10747 * in the future.
10748 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010749 name = xasprintf("%s=", name);
10750 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010751 if (*name_end != '=') {
10752 bb_error_msg("'%s': bad variable name", name);
10753 /* do not parse following argv[]s: */
10754 return 1;
10755 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020010756 /* (Un)exporting/making local NAME=VALUE */
10757 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010758 /* Testcase: export PS1='\w \$ ' */
10759 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010760 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010761 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010762 if (set_local_var(name, flags))
10763 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010764 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010765 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010766}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010767#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010768
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010769#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010770static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010771{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010772 unsigned opt_unexport;
10773
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010774#if ENABLE_HUSH_EXPORT_N
10775 /* "!": do not abort on errors */
10776 opt_unexport = getopt32(argv, "!n");
10777 if (opt_unexport == (uint32_t)-1)
10778 return EXIT_FAILURE;
10779 argv += optind;
10780#else
10781 opt_unexport = 0;
10782 argv++;
10783#endif
10784
10785 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010786 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010787 if (e) {
10788 while (*e) {
10789#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010790 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010791#else
10792 /* ash emits: export VAR='VAL'
10793 * bash: declare -x VAR="VAL"
10794 * we follow ash example */
10795 const char *s = *e++;
10796 const char *p = strchr(s, '=');
10797
10798 if (!p) /* wtf? take next variable */
10799 continue;
10800 /* export var= */
10801 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010802 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010803 putchar('\n');
10804#endif
10805 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010806 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010807 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010808 return EXIT_SUCCESS;
10809 }
10810
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010811 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010812}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010813#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010814
Denys Vlasenko295fef82009-06-03 12:47:26 +020010815#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010816static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010817{
10818 if (G.func_nest_level == 0) {
10819 bb_error_msg("%s: not in a function", argv[0]);
10820 return EXIT_FAILURE; /* bash compat */
10821 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010822 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010823 /* Since all builtins run in a nested variable level,
10824 * need to use level - 1 here. Or else the variable will be removed at once
10825 * after builtin returns.
10826 */
10827 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010828}
10829#endif
10830
Denys Vlasenko1e660422017-07-17 21:10:50 +020010831#if ENABLE_HUSH_READONLY
10832static int FAST_FUNC builtin_readonly(char **argv)
10833{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010834 argv++;
10835 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010836 /* bash: readonly [-p]: list all readonly VARs
10837 * (-p has no effect in bash)
10838 */
10839 struct variable *e;
10840 for (e = G.top_var; e; e = e->next) {
10841 if (e->flg_read_only) {
10842//TODO: quote value: readonly VAR='VAL'
10843 printf("readonly %s\n", e->varstr);
10844 }
10845 }
10846 return EXIT_SUCCESS;
10847 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010848 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010849}
10850#endif
10851
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010852#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010853/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10854static int FAST_FUNC builtin_unset(char **argv)
10855{
10856 int ret;
10857 unsigned opts;
10858
10859 /* "!": do not abort on errors */
10860 /* "+": stop at 1st non-option */
10861 opts = getopt32(argv, "!+vf");
10862 if (opts == (unsigned)-1)
10863 return EXIT_FAILURE;
10864 if (opts == 3) {
10865 bb_error_msg("unset: -v and -f are exclusive");
10866 return EXIT_FAILURE;
10867 }
10868 argv += optind;
10869
10870 ret = EXIT_SUCCESS;
10871 while (*argv) {
10872 if (!(opts & 2)) { /* not -f */
10873 if (unset_local_var(*argv)) {
10874 /* unset <nonexistent_var> doesn't fail.
10875 * Error is when one tries to unset RO var.
10876 * Message was printed by unset_local_var. */
10877 ret = EXIT_FAILURE;
10878 }
10879 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010880# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010881 else {
10882 unset_func(*argv);
10883 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010884# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010885 argv++;
10886 }
10887 return ret;
10888}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010889#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010890
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010891#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010892/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10893 * built-in 'set' handler
10894 * SUSv3 says:
10895 * set [-abCefhmnuvx] [-o option] [argument...]
10896 * set [+abCefhmnuvx] [+o option] [argument...]
10897 * set -- [argument...]
10898 * set -o
10899 * set +o
10900 * Implementations shall support the options in both their hyphen and
10901 * plus-sign forms. These options can also be specified as options to sh.
10902 * Examples:
10903 * Write out all variables and their values: set
10904 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10905 * Turn on the -x and -v options: set -xv
10906 * Unset all positional parameters: set --
10907 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10908 * Set the positional parameters to the expansion of x, even if x expands
10909 * with a leading '-' or '+': set -- $x
10910 *
10911 * So far, we only support "set -- [argument...]" and some of the short names.
10912 */
10913static int FAST_FUNC builtin_set(char **argv)
10914{
10915 int n;
10916 char **pp, **g_argv;
10917 char *arg = *++argv;
10918
10919 if (arg == NULL) {
10920 struct variable *e;
10921 for (e = G.top_var; e; e = e->next)
10922 puts(e->varstr);
10923 return EXIT_SUCCESS;
10924 }
10925
10926 do {
10927 if (strcmp(arg, "--") == 0) {
10928 ++argv;
10929 goto set_argv;
10930 }
10931 if (arg[0] != '+' && arg[0] != '-')
10932 break;
10933 for (n = 1; arg[n]; ++n) {
10934 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10935 goto error;
10936 if (arg[n] == 'o' && argv[1])
10937 argv++;
10938 }
10939 } while ((arg = *++argv) != NULL);
10940 /* Now argv[0] is 1st argument */
10941
10942 if (arg == NULL)
10943 return EXIT_SUCCESS;
10944 set_argv:
10945
10946 /* NB: G.global_argv[0] ($0) is never freed/changed */
10947 g_argv = G.global_argv;
10948 if (G.global_args_malloced) {
10949 pp = g_argv;
10950 while (*++pp)
10951 free(*pp);
10952 g_argv[1] = NULL;
10953 } else {
10954 G.global_args_malloced = 1;
10955 pp = xzalloc(sizeof(pp[0]) * 2);
10956 pp[0] = g_argv[0]; /* retain $0 */
10957 g_argv = pp;
10958 }
10959 /* This realloc's G.global_argv */
10960 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10961
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010962 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010963
10964 return EXIT_SUCCESS;
10965
10966 /* Nothing known, so abort */
10967 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010968 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010969 return EXIT_FAILURE;
10970}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010971#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010972
10973static int FAST_FUNC builtin_shift(char **argv)
10974{
10975 int n = 1;
10976 argv = skip_dash_dash(argv);
10977 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010978 n = bb_strtou(argv[0], NULL, 10);
10979 if (errno || n < 0) {
10980 /* shared string with ash.c */
10981 bb_error_msg("Illegal number: %s", argv[0]);
10982 /*
10983 * ash aborts in this case.
10984 * bash prints error message and set $? to 1.
10985 * Interestingly, for "shift 99999" bash does not
10986 * print error message, but does set $? to 1
10987 * (and does no shifting at all).
10988 */
10989 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010990 }
10991 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010992 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010993 int m = 1;
10994 while (m <= n)
10995 free(G.global_argv[m++]);
10996 }
10997 G.global_argc -= n;
10998 memmove(&G.global_argv[1], &G.global_argv[n+1],
10999 G.global_argc * sizeof(G.global_argv[0]));
11000 return EXIT_SUCCESS;
11001 }
11002 return EXIT_FAILURE;
11003}
11004
Denys Vlasenko74d40582017-08-11 01:32:46 +020011005#if ENABLE_HUSH_GETOPTS
11006static int FAST_FUNC builtin_getopts(char **argv)
11007{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011008/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11009
Denys Vlasenko74d40582017-08-11 01:32:46 +020011010TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011011If a required argument is not found, and getopts is not silent,
11012a question mark (?) is placed in VAR, OPTARG is unset, and a
11013diagnostic message is printed. If getopts is silent, then a
11014colon (:) is placed in VAR and OPTARG is set to the option
11015character found.
11016
11017Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011018
11019"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011020*/
11021 char cbuf[2];
11022 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011023 int c, n, exitcode, my_opterr;
11024 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011025
11026 optstring = *++argv;
11027 if (!optstring || !(var = *++argv)) {
11028 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
11029 return EXIT_FAILURE;
11030 }
11031
Denys Vlasenko238ff982017-08-29 13:38:30 +020011032 if (argv[1])
11033 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11034 else
11035 argv = G.global_argv;
11036 cbuf[1] = '\0';
11037
11038 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011039 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011040 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011041 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011042 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011043 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011044
11045 /* getopts stops on first non-option. Add "+" to force that */
11046 /*if (optstring[0] != '+')*/ {
11047 char *s = alloca(strlen(optstring) + 2);
11048 sprintf(s, "+%s", optstring);
11049 optstring = s;
11050 }
11051
Denys Vlasenko238ff982017-08-29 13:38:30 +020011052 /* Naively, now we should just
11053 * cp = get_local_var_value("OPTIND");
11054 * optind = cp ? atoi(cp) : 0;
11055 * optarg = NULL;
11056 * opterr = my_opterr;
11057 * c = getopt(string_array_len(argv), argv, optstring);
11058 * and be done? Not so fast...
11059 * Unlike normal getopt() usage in C programs, here
11060 * each successive call will (usually) have the same argv[] CONTENTS,
11061 * but not the ADDRESSES. Worse yet, it's possible that between
11062 * invocations of "getopts", there will be calls to shell builtins
11063 * which use getopt() internally. Example:
11064 * while getopts "abc" RES -a -bc -abc de; do
11065 * unset -ff func
11066 * done
11067 * This would not work correctly: getopt() call inside "unset"
11068 * modifies internal libc state which is tracking position in
11069 * multi-option strings ("-abc"). At best, it can skip options
11070 * or return the same option infinitely. With glibc implementation
11071 * of getopt(), it would use outright invalid pointers and return
11072 * garbage even _without_ "unset" mangling internal state.
11073 *
11074 * We resort to resetting getopt() state and calling it N times,
11075 * until we get Nth result (or failure).
11076 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11077 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011078 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011079 count = 0;
11080 n = string_array_len(argv);
11081 do {
11082 optarg = NULL;
11083 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11084 c = getopt(n, argv, optstring);
11085 if (c < 0)
11086 break;
11087 count++;
11088 } while (count <= G.getopt_count);
11089
11090 /* Set OPTIND. Prevent resetting of the magic counter! */
11091 set_local_var_from_halves("OPTIND", utoa(optind));
11092 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011093 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011094
11095 /* Set OPTARG */
11096 /* Always set or unset, never left as-is, even on exit/error:
11097 * "If no option was found, or if the option that was found
11098 * does not have an option-argument, OPTARG shall be unset."
11099 */
11100 cp = optarg;
11101 if (c == '?') {
11102 /* If ":optstring" and unknown option is seen,
11103 * it is stored to OPTARG.
11104 */
11105 if (optstring[1] == ':') {
11106 cbuf[0] = optopt;
11107 cp = cbuf;
11108 }
11109 }
11110 if (cp)
11111 set_local_var_from_halves("OPTARG", cp);
11112 else
11113 unset_local_var("OPTARG");
11114
11115 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011116 exitcode = EXIT_SUCCESS;
11117 if (c < 0) { /* -1: end of options */
11118 exitcode = EXIT_FAILURE;
11119 c = '?';
11120 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011121
Denys Vlasenko238ff982017-08-29 13:38:30 +020011122 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011123 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011124 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011125
Denys Vlasenko74d40582017-08-11 01:32:46 +020011126 return exitcode;
11127}
11128#endif
11129
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011130static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011131{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011132 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011133 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011134 save_arg_t sv;
11135 char *args_need_save;
11136#if ENABLE_HUSH_FUNCTIONS
11137 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011138#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011139
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011140 argv = skip_dash_dash(argv);
11141 filename = argv[0];
11142 if (!filename) {
11143 /* bash says: "bash: .: filename argument required" */
11144 return 2; /* bash compat */
11145 }
11146 arg_path = NULL;
11147 if (!strchr(filename, '/')) {
11148 arg_path = find_in_path(filename);
11149 if (arg_path)
11150 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011151 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011152 errno = ENOENT;
11153 bb_simple_perror_msg(filename);
11154 return EXIT_FAILURE;
11155 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011156 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011157 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011158 free(arg_path);
11159 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011160 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011161 /* POSIX: non-interactive shell should abort here,
11162 * not merely fail. So far no one complained :)
11163 */
11164 return EXIT_FAILURE;
11165 }
11166
11167#if ENABLE_HUSH_FUNCTIONS
11168 sv_flg = G_flag_return_in_progress;
11169 /* "we are inside sourced file, ok to use return" */
11170 G_flag_return_in_progress = -1;
11171#endif
11172 args_need_save = argv[1]; /* used as a boolean variable */
11173 if (args_need_save)
11174 save_and_replace_G_args(&sv, argv);
11175
11176 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11177 G.last_exitcode = 0;
11178 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011179 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011180
11181 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11182 restore_G_args(&sv, argv);
11183#if ENABLE_HUSH_FUNCTIONS
11184 G_flag_return_in_progress = sv_flg;
11185#endif
11186
11187 return G.last_exitcode;
11188}
11189
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011190#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011191static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011192{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011193 int sig;
11194 char *new_cmd;
11195
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011196 if (!G_traps)
11197 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011198
11199 argv++;
11200 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011201 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011202 /* No args: print all trapped */
11203 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011204 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011205 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011206 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011207 /* note: bash adds "SIG", but only if invoked
11208 * as "bash". If called as "sh", or if set -o posix,
11209 * then it prints short signal names.
11210 * We are printing short names: */
11211 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011212 }
11213 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011214 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011215 return EXIT_SUCCESS;
11216 }
11217
11218 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011219 /* If first arg is a number: reset all specified signals */
11220 sig = bb_strtou(*argv, NULL, 10);
11221 if (errno == 0) {
11222 int ret;
11223 process_sig_list:
11224 ret = EXIT_SUCCESS;
11225 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011226 sighandler_t handler;
11227
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011228 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011229 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011230 ret = EXIT_FAILURE;
11231 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011232 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011233 continue;
11234 }
11235
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011236 free(G_traps[sig]);
11237 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011238
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011239 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011240 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011241
11242 /* There is no signal for 0 (EXIT) */
11243 if (sig == 0)
11244 continue;
11245
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011246 if (new_cmd)
11247 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11248 else
11249 /* We are removing trap handler */
11250 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011251 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011252 }
11253 return ret;
11254 }
11255
11256 if (!argv[1]) { /* no second arg */
11257 bb_error_msg("trap: invalid arguments");
11258 return EXIT_FAILURE;
11259 }
11260
11261 /* First arg is "-": reset all specified to default */
11262 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11263 /* Everything else: set arg as signal handler
11264 * (includes "" case, which ignores signal) */
11265 if (argv[0][0] == '-') {
11266 if (argv[0][1] == '\0') { /* "-" */
11267 /* new_cmd remains NULL: "reset these sigs" */
11268 goto reset_traps;
11269 }
11270 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11271 argv++;
11272 }
11273 /* else: "-something", no special meaning */
11274 }
11275 new_cmd = *argv;
11276 reset_traps:
11277 argv++;
11278 goto process_sig_list;
11279}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011280#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011281
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011282#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011283static struct pipe *parse_jobspec(const char *str)
11284{
11285 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011286 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011287
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011288 if (sscanf(str, "%%%u", &jobnum) != 1) {
11289 if (str[0] != '%'
11290 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11291 ) {
11292 bb_error_msg("bad argument '%s'", str);
11293 return NULL;
11294 }
11295 /* It is "%%", "%+" or "%" - current job */
11296 jobnum = G.last_jobid;
11297 if (jobnum == 0) {
11298 bb_error_msg("no current job");
11299 return NULL;
11300 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011301 }
11302 for (pi = G.job_list; pi; pi = pi->next) {
11303 if (pi->jobid == jobnum) {
11304 return pi;
11305 }
11306 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011307 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011308 return NULL;
11309}
11310
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011311static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11312{
11313 struct pipe *job;
11314 const char *status_string;
11315
11316 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11317 for (job = G.job_list; job; job = job->next) {
11318 if (job->alive_cmds == job->stopped_cmds)
11319 status_string = "Stopped";
11320 else
11321 status_string = "Running";
11322
11323 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11324 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011325
11326 clean_up_last_dead_job();
11327
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011328 return EXIT_SUCCESS;
11329}
11330
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011331/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011332static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011333{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011334 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011335 struct pipe *pi;
11336
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011337 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011338 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011339
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011340 /* If they gave us no args, assume they want the last backgrounded task */
11341 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011342 for (pi = G.job_list; pi; pi = pi->next) {
11343 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011344 goto found;
11345 }
11346 }
11347 bb_error_msg("%s: no current job", argv[0]);
11348 return EXIT_FAILURE;
11349 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011350
11351 pi = parse_jobspec(argv[1]);
11352 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011353 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011354 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011355 /* TODO: bash prints a string representation
11356 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011357 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011358 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011359 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011360 }
11361
11362 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011363 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11364 for (i = 0; i < pi->num_cmds; i++) {
11365 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011366 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011367 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011368
11369 i = kill(- pi->pgrp, SIGCONT);
11370 if (i < 0) {
11371 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011372 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011373 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011374 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011375 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011376 }
11377
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011378 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011379 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011380 return checkjobs_and_fg_shell(pi);
11381 }
11382 return EXIT_SUCCESS;
11383}
11384#endif
11385
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011386#if ENABLE_HUSH_KILL
11387static int FAST_FUNC builtin_kill(char **argv)
11388{
11389 int ret = 0;
11390
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011391# if ENABLE_HUSH_JOB
11392 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11393 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011394
11395 do {
11396 struct pipe *pi;
11397 char *dst;
11398 int j, n;
11399
11400 if (argv[i][0] != '%')
11401 continue;
11402 /*
11403 * "kill %N" - job kill
11404 * Converting to pgrp / pid kill
11405 */
11406 pi = parse_jobspec(argv[i]);
11407 if (!pi) {
11408 /* Eat bad jobspec */
11409 j = i;
11410 do {
11411 j++;
11412 argv[j - 1] = argv[j];
11413 } while (argv[j]);
11414 ret = 1;
11415 i--;
11416 continue;
11417 }
11418 /*
11419 * In jobs started under job control, we signal
11420 * entire process group by kill -PGRP_ID.
11421 * This happens, f.e., in interactive shell.
11422 *
11423 * Otherwise, we signal each child via
11424 * kill PID1 PID2 PID3.
11425 * Testcases:
11426 * sh -c 'sleep 1|sleep 1 & kill %1'
11427 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11428 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11429 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011430 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011431 dst = alloca(n * sizeof(int)*4);
11432 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011433 if (G_interactive_fd)
11434 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011435 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011436 struct command *cmd = &pi->cmds[j];
11437 /* Skip exited members of the job */
11438 if (cmd->pid == 0)
11439 continue;
11440 /*
11441 * kill_main has matching code to expect
11442 * leading space. Needed to not confuse
11443 * negative pids with "kill -SIGNAL_NO" syntax
11444 */
11445 dst += sprintf(dst, " %u", (int)cmd->pid);
11446 }
11447 *dst = '\0';
11448 } while (argv[++i]);
11449 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011450# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011451
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011452 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011453 ret = run_applet_main(argv, kill_main);
11454 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011455 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011456 return ret;
11457}
11458#endif
11459
11460#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011461/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011462#if !ENABLE_HUSH_JOB
11463# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11464#endif
11465static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011466{
11467 int ret = 0;
11468 for (;;) {
11469 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011470 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011471
Denys Vlasenko830ea352016-11-08 04:59:11 +010011472 if (!sigisemptyset(&G.pending_set))
11473 goto check_sig;
11474
Denys Vlasenko7e675362016-10-28 21:57:31 +020011475 /* waitpid is not interruptible by SA_RESTARTed
11476 * signals which we use. Thus, this ugly dance:
11477 */
11478
11479 /* Make sure possible SIGCHLD is stored in kernel's
11480 * pending signal mask before we call waitpid.
11481 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011482 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011483 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011484 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011485 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011486
11487 if (!sigisemptyset(&G.pending_set)) {
11488 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011489 goto restore;
11490 }
11491
11492 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011493/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011494 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011495 debug_printf_exec("checkjobs:%d\n", ret);
11496#if ENABLE_HUSH_JOB
11497 if (waitfor_pipe) {
11498 int rcode = job_exited_or_stopped(waitfor_pipe);
11499 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11500 if (rcode >= 0) {
11501 ret = rcode;
11502 sigprocmask(SIG_SETMASK, &oldset, NULL);
11503 break;
11504 }
11505 }
11506#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011507 /* if ECHILD, there are no children (ret is -1 or 0) */
11508 /* if ret == 0, no children changed state */
11509 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011510 if (errno == ECHILD || ret) {
11511 ret--;
11512 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011513 ret = 0;
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011514#if ENABLE_HUSH_BASH_COMPAT
11515 if (waitfor_pid == -1 && errno == ECHILD) {
11516 /* exitcode of "wait -n" with no children is 127, not 0 */
11517 ret = 127;
11518 }
11519#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011520 sigprocmask(SIG_SETMASK, &oldset, NULL);
11521 break;
11522 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011523 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011524 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11525 /* Note: sigsuspend invokes signal handler */
11526 sigsuspend(&oldset);
11527 restore:
11528 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011529 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011530 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011531 sig = check_and_run_traps();
11532 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011533 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011534 ret = 128 + sig;
11535 break;
11536 }
11537 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11538 }
11539 return ret;
11540}
11541
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011542static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011543{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011544 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011545 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011546
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011547 argv = skip_dash_dash(argv);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011548#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011549 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011550 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011551 /* (bash accepts "wait -n PID" too and ignores PID) */
11552 G.dead_job_exitcode = -1;
11553 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011554 }
11555#endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011556 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011557 /* Don't care about wait results */
11558 /* Note 1: must wait until there are no more children */
11559 /* Note 2: must be interruptible */
11560 /* Examples:
11561 * $ sleep 3 & sleep 6 & wait
11562 * [1] 30934 sleep 3
11563 * [2] 30935 sleep 6
11564 * [1] Done sleep 3
11565 * [2] Done sleep 6
11566 * $ sleep 3 & sleep 6 & wait
11567 * [1] 30936 sleep 3
11568 * [2] 30937 sleep 6
11569 * [1] Done sleep 3
11570 * ^C <-- after ~4 sec from keyboard
11571 * $
11572 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011573 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011574 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011575
Denys Vlasenko7e675362016-10-28 21:57:31 +020011576 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011577 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011578 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011579#if ENABLE_HUSH_JOB
11580 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011581 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011582 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011583 wait_pipe = parse_jobspec(*argv);
11584 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011585 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011586 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011587 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011588 } else {
11589 /* waiting on "last dead job" removes it */
11590 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011591 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011592 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011593 /* else: parse_jobspec() already emitted error msg */
11594 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011595 }
11596#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011597 /* mimic bash message */
11598 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011599 ret = EXIT_FAILURE;
11600 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011601 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011602
Denys Vlasenko7e675362016-10-28 21:57:31 +020011603 /* Do we have such child? */
11604 ret = waitpid(pid, &status, WNOHANG);
11605 if (ret < 0) {
11606 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011607 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011608 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011609 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011610 /* "wait $!" but last bg task has already exited. Try:
11611 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11612 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011613 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011614 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011615 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011616 } else {
11617 /* Example: "wait 1". mimic bash message */
11618 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011619 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011620 } else {
11621 /* ??? */
11622 bb_perror_msg("wait %s", *argv);
11623 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011624 continue; /* bash checks all argv[] */
11625 }
11626 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011627 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011628 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011629 } else {
11630 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011631 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011632 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011633 if (WIFSIGNALED(status))
11634 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011635 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011636 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011637
11638 return ret;
11639}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011640#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011641
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011642#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11643static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11644{
11645 if (argv[1]) {
11646 def = bb_strtou(argv[1], NULL, 10);
11647 if (errno || def < def_min || argv[2]) {
11648 bb_error_msg("%s: bad arguments", argv[0]);
11649 def = UINT_MAX;
11650 }
11651 }
11652 return def;
11653}
11654#endif
11655
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011656#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011657static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011658{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011659 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011660 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011661 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011662 /* if we came from builtin_continue(), need to undo "= 1" */
11663 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011664 return EXIT_SUCCESS; /* bash compat */
11665 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011666 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011667
11668 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11669 if (depth == UINT_MAX)
11670 G.flag_break_continue = BC_BREAK;
11671 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011672 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011673
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011674 return EXIT_SUCCESS;
11675}
11676
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011677static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011678{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011679 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11680 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011681}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011682#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011683
11684#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011685static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011686{
11687 int rc;
11688
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011689 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011690 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11691 return EXIT_FAILURE; /* bash compat */
11692 }
11693
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011694 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011695
11696 /* bash:
11697 * out of range: wraps around at 256, does not error out
11698 * non-numeric param:
11699 * f() { false; return qwe; }; f; echo $?
11700 * bash: return: qwe: numeric argument required <== we do this
11701 * 255 <== we also do this
11702 */
11703 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11704 return rc;
11705}
11706#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011707
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011708#if ENABLE_HUSH_TIMES
11709static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11710{
11711 static const uint8_t times_tbl[] ALIGN1 = {
11712 ' ', offsetof(struct tms, tms_utime),
11713 '\n', offsetof(struct tms, tms_stime),
11714 ' ', offsetof(struct tms, tms_cutime),
11715 '\n', offsetof(struct tms, tms_cstime),
11716 0
11717 };
11718 const uint8_t *p;
11719 unsigned clk_tck;
11720 struct tms buf;
11721
11722 clk_tck = bb_clk_tck();
11723
11724 times(&buf);
11725 p = times_tbl;
11726 do {
11727 unsigned sec, frac;
11728 unsigned long t;
11729 t = *(clock_t *)(((char *) &buf) + p[1]);
11730 sec = t / clk_tck;
11731 frac = t % clk_tck;
11732 printf("%um%u.%03us%c",
11733 sec / 60, sec % 60,
11734 (frac * 1000) / clk_tck,
11735 p[0]);
11736 p += 2;
11737 } while (*p);
11738
11739 return EXIT_SUCCESS;
11740}
11741#endif
11742
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011743#if ENABLE_HUSH_MEMLEAK
11744static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11745{
11746 void *p;
11747 unsigned long l;
11748
11749# ifdef M_TRIM_THRESHOLD
11750 /* Optional. Reduces probability of false positives */
11751 malloc_trim(0);
11752# endif
11753 /* Crude attempt to find where "free memory" starts,
11754 * sans fragmentation. */
11755 p = malloc(240);
11756 l = (unsigned long)p;
11757 free(p);
11758 p = malloc(3400);
11759 if (l < (unsigned long)p) l = (unsigned long)p;
11760 free(p);
11761
11762
11763# if 0 /* debug */
11764 {
11765 struct mallinfo mi = mallinfo();
11766 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11767 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11768 }
11769# endif
11770
11771 if (!G.memleak_value)
11772 G.memleak_value = l;
11773
11774 l -= G.memleak_value;
11775 if ((long)l < 0)
11776 l = 0;
11777 l /= 1024;
11778 if (l > 127)
11779 l = 127;
11780
11781 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11782 return l;
11783}
11784#endif