blob: 4b08232a4342231672d5db54be37849f4ef30037 [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 Vlasenko8d6eab32018-04-07 17:01:31 +0200906#if ENABLE_HUSH_INTERACTIVE
907 smallint promptmode; /* 0: PS1, 1: PS2 */
908#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000909 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000910#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000911 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000912#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000913#if ENABLE_HUSH_FUNCTIONS
914 /* 0: outside of a function (or sourced file)
915 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000916 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000917 */
918 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200919# define G_flag_return_in_progress (G.flag_return_in_progress)
920#else
921# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000922#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000923 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100924 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000925 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200926 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200927 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000929 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000930 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100931# define G_global_args_malloced (G.global_args_malloced)
932#else
933# define G_global_args_malloced 0
934#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100935#if ENABLE_HUSH_BASH_COMPAT
936 int dead_job_exitcode; /* for "wait -n" */
937#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000938 /* how many non-NULL argv's we have. NB: $# + 1 */
939 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000940 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000941#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000942 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000943#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000944#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000945 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000946 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000947#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200948#if ENABLE_HUSH_GETOPTS
949 unsigned getopt_count;
950#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000951 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200952 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000953 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200954 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200955 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200956 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200957 unsigned var_nest_level;
958#if ENABLE_HUSH_FUNCTIONS
959# if ENABLE_HUSH_LOCAL
960 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200961# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200962 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000963#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000964 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200965#if ENABLE_HUSH_FAST
966 unsigned count_SIGCHLD;
967 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200968 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200969#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100970#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200971 unsigned parse_lineno;
972 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100973#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200974 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200975 /* Which signals have non-DFL handler (even with no traps set)?
976 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200977 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200978 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200979 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200980 * Other than these two times, never modified.
981 */
982 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200983#if ENABLE_HUSH_JOB
984 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100985# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200986#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200987# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200988#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100989#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000990 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100991# define G_traps G.traps
992#else
993# define G_traps ((char**)NULL)
994#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200995 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100996#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000997 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100998#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +0200999#if ENABLE_HUSH_MODE_X
1000 unsigned x_mode_depth;
1001 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1002 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1003 * for all subsequent output.
1004 */
1005 int x_mode_fd;
1006 o_string x_mode_buf;
1007#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001008#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001009 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001010#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001011 struct sigaction sa;
Denys Vlasenkod8740b22019-05-19 19:11:21 +02001012 char optstring_buf[sizeof("eixs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001013#if BASH_EPOCH_VARS
1014 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1015#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001016#if ENABLE_FEATURE_EDITING
1017 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1018#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001019};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001020#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001021/* Not #defining name to G.name - this quickly gets unwieldy
1022 * (too many defines). Also, I actually prefer to see when a variable
1023 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001024#define INIT_G() do { \
1025 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001026 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1027 sigfillset(&G.sa.sa_mask); \
1028 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001029} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001030
1031
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001032/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001033static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001034#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001035static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001036#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_eval(char **argv) FAST_FUNC;
1038static int builtin_exec(char **argv) FAST_FUNC;
1039static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001040#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001041static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001042#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001043#if ENABLE_HUSH_READONLY
1044static int builtin_readonly(char **argv) FAST_FUNC;
1045#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001046#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_fg_bg(char **argv) FAST_FUNC;
1048static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001049#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001050#if ENABLE_HUSH_GETOPTS
1051static int builtin_getopts(char **argv) FAST_FUNC;
1052#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001053#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001055#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001056#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001057static int builtin_history(char **argv) FAST_FUNC;
1058#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001059#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001061#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001062#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001063static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001064#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001065#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001066static int builtin_printf(char **argv) FAST_FUNC;
1067#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001068static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001069#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001071#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001072#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001074#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_shift(char **argv) FAST_FUNC;
1076static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001077#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001078static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001079#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001080#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001081static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001082#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001083#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001084static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001085#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001086#if ENABLE_HUSH_TIMES
1087static int builtin_times(char **argv) FAST_FUNC;
1088#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001089static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001090#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001091static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001092#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001093#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001094static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001095#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001096#if ENABLE_HUSH_KILL
1097static int builtin_kill(char **argv) FAST_FUNC;
1098#endif
1099#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001100static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001101#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001102#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001103static int builtin_break(char **argv) FAST_FUNC;
1104static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001106#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001107static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001108#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001109
1110/* Table of built-in functions. They can be forked or not, depending on
1111 * context: within pipes, they fork. As simple commands, they do not.
1112 * When used in non-forking context, they can change global variables
1113 * in the parent shell process. If forked, of course they cannot.
1114 * For example, 'unset foo | whatever' will parse and run, but foo will
1115 * still be set at the end. */
1116struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001117 const char *b_cmd;
1118 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001120 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001121# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001123# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#endif
1125};
1126
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001127static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001128 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001129 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001130#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001131 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001132#endif
1133#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001134 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001135#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001136 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001137#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001139#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001140 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1141 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001142 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001143#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001144 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001145#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001146#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001147 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001148#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001149#if ENABLE_HUSH_GETOPTS
1150 BLTIN("getopts" , builtin_getopts , NULL),
1151#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001152#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001153 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001154#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001155#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001156 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001157#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001158#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001159 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001160#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001161#if ENABLE_HUSH_KILL
1162 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1163#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001164#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001165 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001166#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001167#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001168 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001169#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001170#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001171 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001172#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001173#if ENABLE_HUSH_READONLY
1174 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1175#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001176#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001177 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001178#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001179#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001180 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001181#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001183#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001184 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001185#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001186#if ENABLE_HUSH_TIMES
1187 BLTIN("times" , builtin_times , NULL),
1188#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001189#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001190 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001191#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001192 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001193#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001194 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001195#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001196#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001197 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001198#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001199#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001200 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001201#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001202#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001203 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001204#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001205#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001206 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001207#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001208};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001209/* These builtins won't be used if we are on NOMMU and need to re-exec
1210 * (it's cheaper to run an external program in this case):
1211 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001212static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001213#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001214 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001215#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001216#if BASH_TEST2
1217 BLTIN("[[" , builtin_test , NULL),
1218#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001219#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001220 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001221#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001222#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001223 BLTIN("printf" , builtin_printf , NULL),
1224#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001225 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001226#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001227 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001228#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001229};
1230
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001231
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001232/* Debug printouts.
1233 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001234#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001235/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001236# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237# define debug_enter() (G.debug_indent++)
1238# define debug_leave() (G.debug_indent--)
1239#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001240# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001241# define debug_enter() ((void)0)
1242# define debug_leave() ((void)0)
1243#endif
1244
1245#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247#endif
1248
1249#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251#endif
1252
Denys Vlasenko3675c372018-07-23 16:31:21 +02001253#ifndef debug_printf_heredoc
1254# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1255#endif
1256
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001258#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259#endif
1260
1261#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001262# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001263#endif
1264
1265#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001266# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001267# define DEBUG_JOBS 1
1268#else
1269# define DEBUG_JOBS 0
1270#endif
1271
1272#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001273# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001274# define DEBUG_EXPAND 1
1275#else
1276# define DEBUG_EXPAND 0
1277#endif
1278
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001279#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001280# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001281#endif
1282
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001283#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001284# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001285# define DEBUG_GLOB 1
1286#else
1287# define DEBUG_GLOB 0
1288#endif
1289
Denys Vlasenko2db74612017-07-07 22:07:28 +02001290#ifndef debug_printf_redir
1291# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1292#endif
1293
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001294#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001295# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001296#endif
1297
1298#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001299# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001300#endif
1301
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001302#ifndef debug_printf_prompt
1303# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1304#endif
1305
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001306#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001307# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001308# define DEBUG_CLEAN 1
1309#else
1310# define DEBUG_CLEAN 0
1311#endif
1312
1313#if DEBUG_EXPAND
1314static void debug_print_strings(const char *prefix, char **vv)
1315{
1316 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001317 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001318 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001319 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001320}
1321#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001322# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001323#endif
1324
1325
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001326/* Leak hunting. Use hush_leaktool.sh for post-processing.
1327 */
1328#if LEAK_HUNTING
1329static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001330{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001331 void *ptr = xmalloc((size + 0xff) & ~0xff);
1332 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1333 return ptr;
1334}
1335static void *xxrealloc(int lineno, void *ptr, size_t size)
1336{
1337 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1338 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1339 return ptr;
1340}
1341static char *xxstrdup(int lineno, const char *str)
1342{
1343 char *ptr = xstrdup(str);
1344 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1345 return ptr;
1346}
1347static void xxfree(void *ptr)
1348{
1349 fdprintf(2, "free %p\n", ptr);
1350 free(ptr);
1351}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001352# define xmalloc(s) xxmalloc(__LINE__, s)
1353# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1354# define xstrdup(s) xxstrdup(__LINE__, s)
1355# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001356#endif
1357
1358
1359/* Syntax and runtime errors. They always abort scripts.
1360 * In interactive use they usually discard unparsed and/or unexecuted commands
1361 * and return to the prompt.
1362 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1363 */
1364#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001365# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001366# define syntax_error(lineno, msg) syntax_error(msg)
1367# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1368# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1369# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1370# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001371#endif
1372
Denys Vlasenko39701202017-08-02 19:44:05 +02001373static void die_if_script(void)
1374{
1375 if (!G_interactive_fd) {
1376 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1377 xfunc_error_retval = G.last_exitcode;
1378 xfunc_die();
1379 }
1380}
1381
1382static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001383{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001384 va_list p;
1385
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386#if HUSH_DEBUG >= 2
1387 bb_error_msg("hush.c:%u", lineno);
1388#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001389 va_start(p, fmt);
1390 bb_verror_msg(fmt, p, NULL);
1391 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001392 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001393}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001394
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001395static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001396{
1397 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001398 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001399 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001400 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001401 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402}
1403
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001404static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001405{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001406 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001407 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001408}
1409
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001410static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001411{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001412 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001413//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1414// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001415}
1416
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001417static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001418{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001419 char msg[2] = { ch, '\0' };
1420 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001421}
1422
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001423static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001424{
1425 char msg[2];
1426 msg[0] = ch;
1427 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001428#if HUSH_DEBUG >= 2
1429 bb_error_msg("hush.c:%u", lineno);
1430#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001431 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001432 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001433}
1434
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001435#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001436# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001437# undef syntax_error
1438# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001439# undef syntax_error_unterm_ch
1440# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001441# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001442#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001443# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001444# define syntax_error(msg) syntax_error(__LINE__, msg)
1445# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1446# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1447# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1448# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001449#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001450
Denis Vlasenko552433b2009-04-04 19:29:21 +00001451
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001452/* Utility functions
1453 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001454/* Replace each \x with x in place, return ptr past NUL. */
1455static char *unbackslash(char *src)
1456{
Denys Vlasenko71885402009-09-24 01:44:13 +02001457 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001458 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001459 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001460 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001461 if (*src != '\0') {
1462 /* \x -> x */
1463 *dst++ = *src++;
1464 continue;
1465 }
1466 /* else: "\<nul>". Do not delete this backslash.
1467 * Testcase: eval 'echo ok\'
1468 */
1469 *dst++ = '\\';
1470 /* fallthrough */
1471 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001472 if ((*dst++ = *src++) == '\0')
1473 break;
1474 }
1475 return dst;
1476}
1477
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001478static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001479{
1480 int i;
1481 unsigned count1;
1482 unsigned count2;
1483 char **v;
1484
1485 v = strings;
1486 count1 = 0;
1487 if (v) {
1488 while (*v) {
1489 count1++;
1490 v++;
1491 }
1492 }
1493 count2 = 0;
1494 v = add;
1495 while (*v) {
1496 count2++;
1497 v++;
1498 }
1499 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1500 v[count1 + count2] = NULL;
1501 i = count2;
1502 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001503 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001504 return v;
1505}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001506#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001507static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1508{
1509 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1510 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1511 return ptr;
1512}
1513#define add_strings_to_strings(strings, add, need_to_dup) \
1514 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1515#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001516
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001517/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001518static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001519{
1520 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001521 v[0] = add;
1522 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001523 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001524}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001525#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001526static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1527{
1528 char **ptr = add_string_to_strings(strings, add);
1529 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1530 return ptr;
1531}
1532#define add_string_to_strings(strings, add) \
1533 xx_add_string_to_strings(__LINE__, strings, add)
1534#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001535
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001536static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001537{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001538 char **v;
1539
1540 if (!strings)
1541 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001542 v = strings;
1543 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001544 free(*v);
1545 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001546 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001547 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001548}
1549
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001550static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001551{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001552 int newfd;
1553 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001554 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1555 if (newfd >= 0) {
1556 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1557 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1558 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001559 if (errno == EBUSY)
1560 goto repeat;
1561 if (errno == EINTR)
1562 goto repeat;
1563 }
1564 return newfd;
1565}
1566
Denys Vlasenko657e9002017-07-30 23:34:04 +02001567static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001568{
1569 int newfd;
1570 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001571 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001572 if (newfd < 0) {
1573 if (errno == EBUSY)
1574 goto repeat;
1575 if (errno == EINTR)
1576 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001577 /* fd was not open? */
1578 if (errno == EBADF)
1579 return fd;
1580 xfunc_die();
1581 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001582 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1583 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001584 close(fd);
1585 return newfd;
1586}
1587
1588
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001589/* Manipulating HFILEs */
1590static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001591{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001592 HFILE *fp;
1593 int fd;
1594
1595 fd = STDIN_FILENO;
1596 if (name) {
1597 fd = open(name, O_RDONLY | O_CLOEXEC);
1598 if (fd < 0)
1599 return NULL;
1600 if (O_CLOEXEC == 0) /* ancient libc */
1601 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001602 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001603
1604 fp = xmalloc(sizeof(*fp));
1605 fp->is_stdin = (name == NULL);
1606 fp->fd = fd;
1607 fp->cur = fp->end = fp->buf;
1608 fp->next_hfile = G.HFILE_list;
1609 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001610 return fp;
1611}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001612static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001613{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001614 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001615 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001616 HFILE *cur = *pp;
1617 if (cur == fp) {
1618 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619 break;
1620 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001621 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001622 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001623 if (fp->fd >= 0)
1624 close(fp->fd);
1625 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001626}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001627static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001628{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001629 int n;
1630
1631 if (fp->fd < 0) {
1632 /* Already saw EOF */
1633 return EOF;
1634 }
1635 /* Try to buffer more input */
1636 fp->cur = fp->buf;
1637 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1638 if (n < 0) {
1639 bb_perror_msg("read error");
1640 n = 0;
1641 }
1642 fp->end = fp->buf + n;
1643 if (n == 0) {
1644 /* EOF/error */
1645 close(fp->fd);
1646 fp->fd = -1;
1647 return EOF;
1648 }
1649 return (unsigned char)(*fp->cur++);
1650}
1651/* Inlined for common case of non-empty buffer.
1652 */
1653static ALWAYS_INLINE int hfgetc(HFILE *fp)
1654{
1655 if (fp->cur < fp->end)
1656 return (unsigned char)(*fp->cur++);
1657 /* Buffer empty */
1658 return refill_HFILE_and_getc(fp);
1659}
1660static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1661{
1662 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001663 while (fl) {
1664 if (fd == fl->fd) {
1665 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001666 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001667 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 +02001668 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001669 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001670 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001671 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001672#if ENABLE_HUSH_MODE_X
1673 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1674 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1675 return 1; /* "found and moved" */
1676 }
1677#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001678 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001679}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001680#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001681static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001682{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001683 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001684 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001685 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001686 * It is disastrous if we share memory with a vforked parent.
1687 * I'm not sure we never come here after vfork.
1688 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001689 *
1690 * ">" instead of ">=": we don't close fd#0,
1691 * interactive shell uses hfopen(NULL) as stdin input
1692 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1693 * If we'd close it here, then e.g. interactive "set | sort"
1694 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001695 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001696 if (fl->fd > 0)
1697 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001698 close(fl->fd);
1699 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001700 }
1701}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001702#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001703static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001704{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001705 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001706 while (fl) {
1707 if (fl->fd == fd)
1708 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001709 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001710 }
1711 return 0;
1712}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001713
1714
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001715/* Helpers for setting new $n and restoring them back
1716 */
1717typedef struct save_arg_t {
1718 char *sv_argv0;
1719 char **sv_g_argv;
1720 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001721 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001722} save_arg_t;
1723
1724static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1725{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001726 sv->sv_argv0 = argv[0];
1727 sv->sv_g_argv = G.global_argv;
1728 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001729 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001730
1731 argv[0] = G.global_argv[0]; /* retain $0 */
1732 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001733 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001734
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001735 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001736}
1737
1738static void restore_G_args(save_arg_t *sv, char **argv)
1739{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001740#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001741 if (G.global_args_malloced) {
1742 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001743 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001744 while (*++pp) /* note: does not free $0 */
1745 free(*pp);
1746 free(G.global_argv);
1747 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001748#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001749 argv[0] = sv->sv_argv0;
1750 G.global_argv = sv->sv_g_argv;
1751 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001752 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001753}
1754
1755
Denis Vlasenkod5762932009-03-31 11:22:57 +00001756/* Basic theory of signal handling in shell
1757 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001758 * This does not describe what hush does, rather, it is current understanding
1759 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001760 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1761 *
1762 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1763 * is finished or backgrounded. It is the same in interactive and
1764 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001765 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001766 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001767 * backgrounds (i.e. stops) or kills all members of currently running
1768 * pipe.
1769 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001770 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001771 * or by SIGINT in interactive shell.
1772 *
1773 * Trap handlers will execute even within trap handlers. (right?)
1774 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001775 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1776 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001777 *
1778 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001779 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001780 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001781 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001782 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001783 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001784 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001785 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001786 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001787 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001788 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001789 *
1790 * SIGQUIT: ignore
1791 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001792 * SIGHUP (interactive):
1793 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001794 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001795 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1796 * that all pipe members are stopped. Try this in bash:
1797 * while :; do :; done - ^Z does not background it
1798 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001799 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001800 * of the command line, show prompt. NB: ^C does not send SIGINT
1801 * to interactive shell while shell is waiting for a pipe,
1802 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001803 * Example 1: this waits 5 sec, but does not execute ls:
1804 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1805 * Example 2: this does not wait and does not execute ls:
1806 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1807 * Example 3: this does not wait 5 sec, but executes ls:
1808 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001809 * Example 4: this does not wait and does not execute ls:
1810 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001811 *
1812 * (What happens to signals which are IGN on shell start?)
1813 * (What happens with signal mask on shell start?)
1814 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001815 * Old implementation
1816 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 * We use in-kernel pending signal mask to determine which signals were sent.
1818 * We block all signals which we don't want to take action immediately,
1819 * i.e. we block all signals which need to have special handling as described
1820 * above, and all signals which have traps set.
1821 * After each pipe execution, we extract any pending signals via sigtimedwait()
1822 * and act on them.
1823 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001824 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001825 * sigset_t blocked_set: current blocked signal set
1826 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001827 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001828 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001829 * "trap 'cmd' SIGxxx":
1830 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001831 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001832 * unblock signals with special interactive handling
1833 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001834 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001835 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001836 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001837 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001838 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001839 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001840 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001841 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001842 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001843 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001844 * Standard says "When a subshell is entered, traps that are not being ignored
1845 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001846 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001847 *
1848 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001849 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001850 * masked signals are not visible!
1851 *
1852 * New implementation
1853 * ==================
1854 * We record each signal we are interested in by installing signal handler
1855 * for them - a bit like emulating kernel pending signal mask in userspace.
1856 * We are interested in: signals which need to have special handling
1857 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001858 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001859 * After each pipe execution, we extract any pending signals
1860 * and act on them.
1861 *
1862 * unsigned special_sig_mask: a mask of shell-special signals.
1863 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1864 * char *traps[sig] if trap for sig is set (even if it's '').
1865 * sigset_t pending_set: set of sigs we received.
1866 *
1867 * "trap - SIGxxx":
1868 * if sig is in special_sig_mask, set handler back to:
1869 * record_pending_signo, or to IGN if it's a tty stop signal
1870 * if sig is in fatal_sig_mask, set handler back to sigexit.
1871 * else: set handler back to SIG_DFL
1872 * "trap 'cmd' SIGxxx":
1873 * set handler to record_pending_signo.
1874 * "trap '' SIGxxx":
1875 * set handler to SIG_IGN.
1876 * after [v]fork, if we plan to be a shell:
1877 * set signals with special interactive handling to SIG_DFL
1878 * (because child shell is not interactive),
1879 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1880 * after [v]fork, if we plan to exec:
1881 * POSIX says fork clears pending signal mask in child - no need to clear it.
1882 *
1883 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1884 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1885 *
1886 * Note (compat):
1887 * Standard says "When a subshell is entered, traps that are not being ignored
1888 * are set to the default actions". bash interprets it so that traps which
1889 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001890 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001891enum {
1892 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001893 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001894 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001895 | (1 << SIGHUP)
1896 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001897 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001898#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001899 | (1 << SIGTTIN)
1900 | (1 << SIGTTOU)
1901 | (1 << SIGTSTP)
1902#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001904};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001905
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001906static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001907{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001908 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001909#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001910 if (sig == SIGCHLD) {
1911 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001912//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 +02001913 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001914#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001915}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001916
Denys Vlasenko0806e402011-05-12 23:06:20 +02001917static sighandler_t install_sighandler(int sig, sighandler_t handler)
1918{
1919 struct sigaction old_sa;
1920
1921 /* We could use signal() to install handlers... almost:
1922 * except that we need to mask ALL signals while handlers run.
1923 * I saw signal nesting in strace, race window isn't small.
1924 * SA_RESTART is also needed, but in Linux, signal()
1925 * sets SA_RESTART too.
1926 */
1927 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1928 /* sigfillset(&G.sa.sa_mask); - already done */
1929 /* G.sa.sa_flags = SA_RESTART; - already done */
1930 G.sa.sa_handler = handler;
1931 sigaction(sig, &G.sa, &old_sa);
1932 return old_sa.sa_handler;
1933}
1934
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001935static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001936
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001937static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001938static void restore_ttypgrp_and__exit(void)
1939{
1940 /* xfunc has failed! die die die */
1941 /* no EXIT traps, this is an escape hatch! */
1942 G.exiting = 1;
1943 hush_exit(xfunc_error_retval);
1944}
1945
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001946#if ENABLE_HUSH_JOB
1947
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001948/* Needed only on some libc:
1949 * It was observed that on exit(), fgetc'ed buffered data
1950 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1951 * With the net effect that even after fork(), not vfork(),
1952 * exit() in NOEXECed applet in "sh SCRIPT":
1953 * noexec_applet_here
1954 * echo END_OF_SCRIPT
1955 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1956 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001957 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001958 * and in `cmd` handling.
1959 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1960 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001961static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001962static void fflush_and__exit(void)
1963{
1964 fflush_all();
1965 _exit(xfunc_error_retval);
1966}
1967
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001968/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001969# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001970/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001971# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001972
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001973/* Restores tty foreground process group, and exits.
1974 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001975 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001976 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001977 * We also call it if xfunc is exiting.
1978 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001979static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001980static void sigexit(int sig)
1981{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001982 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001983 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001984 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1985 /* Disable all signals: job control, SIGPIPE, etc.
1986 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1987 */
1988 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001989 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001990 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001991
1992 /* Not a signal, just exit */
1993 if (sig <= 0)
1994 _exit(- sig);
1995
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001996 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001997}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001998#else
1999
Denys Vlasenko8391c482010-05-22 17:50:43 +02002000# define disable_restore_tty_pgrp_on_exit() ((void)0)
2001# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002002
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002003#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002004
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002005static sighandler_t pick_sighandler(unsigned sig)
2006{
2007 sighandler_t handler = SIG_DFL;
2008 if (sig < sizeof(unsigned)*8) {
2009 unsigned sigmask = (1 << sig);
2010
2011#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002012 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002013 if (G_fatal_sig_mask & sigmask)
2014 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002015 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002016#endif
2017 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002018 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002019 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002020 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002021 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002022 * in an endless loop when we try to do some
2023 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002024 */
2025 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2026 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002027 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002028 }
2029 return handler;
2030}
2031
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002032/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002033static void hush_exit(int exitcode)
2034{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002035#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko76a4e832019-05-19 18:24:52 +02002036 if (G.line_input_state)
2037 save_history(G.line_input_state);
Denys Vlasenkobede2152011-09-04 16:12:33 +02002038#endif
2039
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002040 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002041 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002042 char *argv[3];
2043 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002044 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002045 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002046 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002047 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002048 * "trap" will still show it, if executed
2049 * in the handler */
2050 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002051 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002052
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002053#if ENABLE_FEATURE_CLEAN_UP
2054 {
2055 struct variable *cur_var;
2056 if (G.cwd != bb_msg_unknown)
2057 free((char*)G.cwd);
2058 cur_var = G.top_var;
2059 while (cur_var) {
2060 struct variable *tmp = cur_var;
2061 if (!cur_var->max_len)
2062 free(cur_var->varstr);
2063 cur_var = cur_var->next;
2064 free(tmp);
2065 }
2066 }
2067#endif
2068
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002069 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002070#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002071 sigexit(- (exitcode & 0xff));
2072#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002073 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002074#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002075}
2076
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002077
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002078//TODO: return a mask of ALL handled sigs?
2079static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002080{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002081 int last_sig = 0;
2082
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002083 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002084 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002085
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002086 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002087 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002088 sig = 0;
2089 do {
2090 sig++;
2091 if (sigismember(&G.pending_set, sig)) {
2092 sigdelset(&G.pending_set, sig);
2093 goto got_sig;
2094 }
2095 } while (sig < NSIG);
2096 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002097 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002098 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002099 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002100 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002101 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002102 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002103 char *argv[3];
2104 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002105 argv[1] = xstrdup(G_traps[sig]);
2106 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002107 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002108 save_rcode = G.last_exitcode;
2109 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002110 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002111//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002112 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002113 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002114 } /* else: "" trap, ignoring signal */
2115 continue;
2116 }
2117 /* not a trap: special action */
2118 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002119 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002120 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002121 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002122 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002123 break;
2124#if ENABLE_HUSH_JOB
2125 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002126//TODO: why are we doing this? ash and dash don't do this,
2127//they have no handler for SIGHUP at all,
2128//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002129 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002130 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002131 /* bash is observed to signal whole process groups,
2132 * not individual processes */
2133 for (job = G.job_list; job; job = job->next) {
2134 if (job->pgrp <= 0)
2135 continue;
2136 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2137 if (kill(- job->pgrp, SIGHUP) == 0)
2138 kill(- job->pgrp, SIGCONT);
2139 }
2140 sigexit(SIGHUP);
2141 }
2142#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002143#if ENABLE_HUSH_FAST
2144 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002145 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002146 G.count_SIGCHLD++;
2147//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2148 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002149 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002150 * This simplifies wait builtin a bit.
2151 */
2152 break;
2153#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002154 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002155 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002156 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002157 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002158 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002159 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002160 * in interactive shell, because TERM is ignored.
2161 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002162 break;
2163 }
2164 }
2165 return last_sig;
2166}
2167
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002168
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002169static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002170{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002171 if (force || G.cwd == NULL) {
2172 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2173 * we must not try to free(bb_msg_unknown) */
2174 if (G.cwd == bb_msg_unknown)
2175 G.cwd = NULL;
2176 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2177 if (!G.cwd)
2178 G.cwd = bb_msg_unknown;
2179 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002180 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002181}
2182
Denis Vlasenko83506862007-11-23 13:11:42 +00002183
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002184/*
2185 * Shell and environment variable support
2186 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002187static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002188{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002189 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002190 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002191
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002192 pp = &G.top_var;
2193 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002194 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002195 return pp;
2196 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197 }
2198 return NULL;
2199}
2200
Denys Vlasenko03dad222010-01-12 23:29:57 +01002201static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002202{
Denys Vlasenko29082232010-07-16 13:52:32 +02002203 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002204 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002205
2206 if (G.expanded_assignments) {
2207 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002208 while (*cpp) {
2209 char *cp = *cpp;
2210 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2211 return cp + len + 1;
2212 cpp++;
2213 }
2214 }
2215
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002216 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002217 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002218 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002219
Denys Vlasenkodea47882009-10-09 15:40:49 +02002220 if (strcmp(name, "PPID") == 0)
2221 return utoa(G.root_ppid);
2222 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002223#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002224 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002225 return utoa(next_random(&G.random_gen));
2226#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002227#if ENABLE_HUSH_LINENO_VAR
2228 if (strcmp(name, "LINENO") == 0)
2229 return utoa(G.execute_lineno);
2230#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002231#if BASH_EPOCH_VARS
2232 {
2233 const char *fmt = NULL;
2234 if (strcmp(name, "EPOCHSECONDS") == 0)
2235 fmt = "%lu";
2236 else if (strcmp(name, "EPOCHREALTIME") == 0)
2237 fmt = "%lu.%06u";
2238 if (fmt) {
2239 struct timeval tv;
2240 gettimeofday(&tv, NULL);
2241 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2242 (unsigned)tv.tv_usec);
2243 return G.epoch_buf;
2244 }
2245 }
2246#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002247 return NULL;
2248}
2249
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002250#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002251static void handle_changed_special_names(const char *name, unsigned name_len)
2252{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002253 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002254 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002255 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002256 return;
2257 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002258 }
2259}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002260#else
2261/* Do not even bother evaluating arguments */
2262# define handle_changed_special_names(...) ((void)0)
2263#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002264
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002265/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002266 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002267 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002268#define SETFLAG_EXPORT (1 << 0)
2269#define SETFLAG_UNEXPORT (1 << 1)
2270#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002271#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002272static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002273{
Denys Vlasenko61407802018-04-04 21:14:28 +02002274 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002275 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002276 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002277 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002278 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002279 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002280 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281
Denis Vlasenko950bd722009-04-21 11:23:56 +00002282 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002283 if (HUSH_DEBUG && !eq_sign)
2284 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002285
Denis Vlasenko950bd722009-04-21 11:23:56 +00002286 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002287 cur_pp = &G.top_var;
2288 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002290 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291 continue;
2292 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002293
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002294 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002295 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002296 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002297 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002298//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2299//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002300 return -1;
2301 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002302 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002303 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2304 *eq_sign = '\0';
2305 unsetenv(str);
2306 *eq_sign = '=';
2307 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002308 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002309 /* bash 3.2.33(1) and exported vars:
2310 * # export z=z
2311 * # f() { local z=a; env | grep ^z; }
2312 * # f
2313 * z=a
2314 * # env | grep ^z
2315 * z=z
2316 */
2317 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002318 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002319 /* New variable is local ("local VAR=VAL" or
2320 * "VAR=VAL cmd")
2321 * and existing one is global, or local
2322 * on a lower level that new one.
2323 * Remove it from global variable list:
2324 */
2325 *cur_pp = cur->next;
2326 if (G.shadowed_vars_pp) {
2327 /* Save in "shadowed" list */
2328 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2329 cur->flg_export ? "exported " : "",
2330 cur->varstr, cur->var_nest_level, str, local_lvl
2331 );
2332 cur->next = *G.shadowed_vars_pp;
2333 *G.shadowed_vars_pp = cur;
2334 } else {
2335 /* Came from pseudo_exec_argv(), no need to save: delete it */
2336 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2337 cur->flg_export ? "exported " : "",
2338 cur->varstr, cur->var_nest_level, str, local_lvl
2339 );
2340 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2341 free_me = cur->varstr; /* then free it later */
2342 free(cur);
2343 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002344 break;
2345 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002346
Denis Vlasenko950bd722009-04-21 11:23:56 +00002347 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002348 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002349 free_and_exp:
2350 free(str);
2351 goto exp;
2352 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002353
2354 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002355 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002356 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002357 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002358 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002359 strcpy(cur->varstr, str);
2360 goto free_and_exp;
2361 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002362 /* Can't reuse */
2363 cur->max_len = 0;
2364 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002365 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002366 /* max_len == 0 signifies "malloced" var, which we can
2367 * (and have to) free. But we can't free(cur->varstr) here:
2368 * if cur->flg_export is 1, it is in the environment.
2369 * We should either unsetenv+free, or wait until putenv,
2370 * then putenv(new)+free(old).
2371 */
2372 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002373 goto set_str_and_exp;
2374 }
2375
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002376 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002377 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002378 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002379 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002380 cur->next = *cur_pp;
2381 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002382
2383 set_str_and_exp:
2384 cur->varstr = str;
2385 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002386#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002387 if (flags & SETFLAG_MAKE_RO) {
2388 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002389 }
2390#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002391 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002392 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002393 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002394 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002395 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002396 cur->flg_export = 0;
2397 /* unsetenv was already done */
2398 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002399 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002400 retval = putenv(cur->varstr);
2401 /* fall through to "free(free_me)" -
2402 * only now we can free old exported malloced string
2403 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002404 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002405 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002406 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002407
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002408 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002409
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002410 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002411}
2412
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002413static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2414{
2415 char *var = xasprintf("%s=%s", name, val);
2416 set_local_var(var, /*flag:*/ 0);
2417}
2418
Denys Vlasenko6db47842009-09-05 20:15:17 +02002419/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002420static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002421{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002422 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002423}
2424
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002425#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002426static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002427{
2428 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002429 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002430
Denys Vlasenko61407802018-04-04 21:14:28 +02002431 cur_pp = &G.top_var;
2432 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002433 if (strncmp(cur->varstr, name, name_len) == 0
2434 && cur->varstr[name_len] == '='
2435 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002436 if (cur->flg_read_only) {
2437 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002438 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002439 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002440
Denys Vlasenko61407802018-04-04 21:14:28 +02002441 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002442 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2443 bb_unsetenv(cur->varstr);
2444 if (!cur->max_len)
2445 free(cur->varstr);
2446 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002447
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002448 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002449 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002450 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002452
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002453 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002454 handle_changed_special_names(name, name_len);
2455
Mike Frysingerd690f682009-03-30 06:50:54 +00002456 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002457}
2458
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002459static int unset_local_var(const char *name)
2460{
2461 return unset_local_var_len(name, strlen(name));
2462}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002463#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002464
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002465
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002466/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002467 * Helpers for "var1=val1 var2=val2 cmd" feature
2468 */
2469static void add_vars(struct variable *var)
2470{
2471 struct variable *next;
2472
2473 while (var) {
2474 next = var->next;
2475 var->next = G.top_var;
2476 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002477 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002478 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002479 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002480 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002481 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002482 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002483 var = next;
2484 }
2485}
2486
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002487/* We put strings[i] into variable table and possibly putenv them.
2488 * If variable is read only, we can free the strings[i]
2489 * which attempts to overwrite it.
2490 * The strings[] vector itself is freed.
2491 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002492static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002493{
2494 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002495
2496 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002497 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002498
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002499 s = strings;
2500 while (*s) {
2501 struct variable *var_p;
2502 struct variable **var_pp;
2503 char *eq;
2504
2505 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002506 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002507 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002508 var_pp = get_ptr_to_local_var(*s, eq - *s);
2509 if (var_pp) {
2510 var_p = *var_pp;
2511 if (var_p->flg_read_only) {
2512 char **p;
2513 bb_error_msg("%s: readonly variable", *s);
2514 /*
2515 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2516 * If VAR is readonly, leaving it in the list
2517 * after asssignment error (msg above)
2518 * causes doubled error message later, on unset.
2519 */
2520 debug_printf_env("removing/freeing '%s' element\n", *s);
2521 free(*s);
2522 p = s;
2523 do { *p = p[1]; p++; } while (*p);
2524 goto next;
2525 }
2526 /* below, set_local_var() with nest level will
2527 * "shadow" (remove) this variable from
2528 * global linked list.
2529 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002530 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002531 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2532 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002533 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002534 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002535 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002536 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002537}
2538
2539
2540/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002541 * Unicode helper
2542 */
2543static void reinit_unicode_for_hush(void)
2544{
2545 /* Unicode support should be activated even if LANG is set
2546 * _during_ shell execution, not only if it was set when
2547 * shell was started. Therefore, re-check LANG every time:
2548 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002549 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2550 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002551 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002552 const char *s = get_local_var_value("LC_ALL");
2553 if (!s) s = get_local_var_value("LC_CTYPE");
2554 if (!s) s = get_local_var_value("LANG");
2555 reinit_unicode(s);
2556 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002557}
2558
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002559/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002560 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002562
2563#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002564/* To test correct lineedit/interactive behavior, type from command line:
2565 * echo $P\
2566 * \
2567 * AT\
2568 * H\
2569 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002570 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002571 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002572static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002573{
2574 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002575
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002576 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002577
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002578# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2579 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2580 if (!prompt_str)
2581 prompt_str = "";
2582# else
2583 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002584 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002585 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2586 free(G.PS1);
2587 /* bash uses $PWD value, even if it is set by user.
2588 * It uses current dir only if PWD is unset.
2589 * We always use current dir. */
2590 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002591 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002592# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002593 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002594 return prompt_str;
2595}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002596static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002597{
2598 int r;
2599 const char *prompt_str;
2600
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002601 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002602# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002603 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002604 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002605 if (G.flag_SIGINT) {
2606 /* There was ^C'ed, make it look prettier: */
2607 bb_putchar('\n');
2608 G.flag_SIGINT = 0;
2609 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002610 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002611 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002612 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002613 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002614 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002615 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002616 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002617 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002618 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002619 if (r != 0 && !G.flag_SIGINT)
2620 break;
2621 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002622 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2623 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002624 G.last_exitcode = 128 + SIGINT;
2625 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002626 if (r < 0) {
2627 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002628 i->p = NULL;
2629 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002630 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002631 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002632 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002633 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002634# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002635 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002636 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002637 if (i->last_char == '\0' || i->last_char == '\n') {
2638 /* Why check_and_run_traps here? Try this interactively:
2639 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2640 * $ <[enter], repeatedly...>
2641 * Without check_and_run_traps, handler never runs.
2642 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002643 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002644 fputs(prompt_str, stdout);
2645 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002646 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002647//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002648 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002649 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2650 * no ^C masking happens during fgetc, no special code for ^C:
2651 * it generates SIGINT as usual.
2652 */
2653 check_and_run_traps();
2654 if (G.flag_SIGINT)
2655 G.last_exitcode = 128 + SIGINT;
2656 if (r != '\0')
2657 break;
2658 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002659 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002660# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002661}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002662/* This is the magic location that prints prompts
2663 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002664static int fgetc_interactive(struct in_str *i)
2665{
2666 int ch;
2667 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002668 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002669 /* Returns first char (or EOF), the rest is in i->p[] */
2670 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002671 G.promptmode = 1; /* PS2 */
2672 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002673 } else {
2674 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002675 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002676 }
2677 return ch;
2678}
2679#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002680static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002681{
2682 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002683 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002684 return ch;
2685}
2686#endif /* INTERACTIVE */
2687
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002688static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002689{
2690 int ch;
2691
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002692 if (!i->file) {
2693 /* string-based in_str */
2694 ch = (unsigned char)*i->p;
2695 if (ch != '\0') {
2696 i->p++;
2697 i->last_char = ch;
2698 return ch;
2699 }
2700 return EOF;
2701 }
2702
2703 /* FILE-based in_str */
2704
Denys Vlasenko4074d492016-09-30 01:49:53 +02002705#if ENABLE_FEATURE_EDITING
2706 /* This can be stdin, check line editing char[] buffer */
2707 if (i->p && *i->p != '\0') {
2708 ch = (unsigned char)*i->p++;
2709 goto out;
2710 }
2711#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002712 /* peek_buf[] is an int array, not char. Can contain EOF. */
2713 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002714 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002715 int ch2 = i->peek_buf[1];
2716 i->peek_buf[0] = ch2;
2717 if (ch2 == 0) /* very likely, avoid redundant write */
2718 goto out;
2719 i->peek_buf[1] = 0;
2720 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002721 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002722
Denys Vlasenko4074d492016-09-30 01:49:53 +02002723 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002724 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002725 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002726 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002727#if ENABLE_HUSH_LINENO_VAR
2728 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002729 G.parse_lineno++;
2730 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002731 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002732#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002733 return ch;
2734}
2735
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002736static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737{
2738 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002739
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002740 if (!i->file) {
2741 /* string-based in_str */
2742 /* Doesn't report EOF on NUL. None of the callers care. */
2743 return (unsigned char)*i->p;
2744 }
2745
2746 /* FILE-based in_str */
2747
Denys Vlasenko4074d492016-09-30 01:49:53 +02002748#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002749 /* This can be stdin, check line editing char[] buffer */
2750 if (i->p && *i->p != '\0')
2751 return (unsigned char)*i->p;
2752#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002753 /* peek_buf[] is an int array, not char. Can contain EOF. */
2754 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002755 if (ch != 0)
2756 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002757
Denys Vlasenko4074d492016-09-30 01:49:53 +02002758 /* Need to get a new char */
2759 ch = fgetc_interactive(i);
2760 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2761
2762 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2763#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2764 if (i->p) {
2765 i->p -= 1;
2766 return ch;
2767 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002768#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002769 i->peek_buf[0] = ch;
2770 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002771 return ch;
2772}
2773
Denys Vlasenko4074d492016-09-30 01:49:53 +02002774/* Only ever called if i_peek() was called, and did not return EOF.
2775 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2776 * not end-of-line. Therefore we never need to read a new editing line here.
2777 */
2778static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002779{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002780 int ch;
2781
2782 /* There are two cases when i->p[] buffer exists.
2783 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002784 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002785 * In both cases, we know that i->p[0] exists and not NUL, and
2786 * the peek2 result is in i->p[1].
2787 */
2788 if (i->p)
2789 return (unsigned char)i->p[1];
2790
2791 /* Now we know it is a file-based in_str. */
2792
2793 /* peek_buf[] is an int array, not char. Can contain EOF. */
2794 /* Is there 2nd char? */
2795 ch = i->peek_buf[1];
2796 if (ch == 0) {
2797 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002798 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002799 i->peek_buf[1] = ch;
2800 }
2801
2802 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2803 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002804}
2805
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002806static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2807{
2808 for (;;) {
2809 int ch, ch2;
2810
2811 ch = i_getch(input);
2812 if (ch != '\\')
2813 return ch;
2814 ch2 = i_peek(input);
2815 if (ch2 != '\n')
2816 return ch;
2817 /* backslash+newline, skip it */
2818 i_getch(input);
2819 }
2820}
2821
2822/* Note: this function _eats_ \<newline> pairs, safe to use plain
2823 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2824 */
2825static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2826{
2827 for (;;) {
2828 int ch, ch2;
2829
2830 ch = i_peek(input);
2831 if (ch != '\\')
2832 return ch;
2833 ch2 = i_peek2(input);
2834 if (ch2 != '\n')
2835 return ch;
2836 /* backslash+newline, skip it */
2837 i_getch(input);
2838 i_getch(input);
2839 }
2840}
2841
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002842static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002843{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002844 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002845 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002846 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002847}
2848
2849static void setup_string_in_str(struct in_str *i, const char *s)
2850{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002851 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002852 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002853 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002854}
2855
2856
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002857/*
2858 * o_string support
2859 */
2860#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002861
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002862static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002863{
2864 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002865 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002866 if (o->data)
2867 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002868}
2869
Denys Vlasenko18567402018-07-20 17:51:31 +02002870static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002871{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002872 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002873 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002874}
2875
Denys Vlasenko18567402018-07-20 17:51:31 +02002876static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002877{
2878 free(o->data);
2879}
2880
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002881static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002882{
2883 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002884 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002885 o->data = xrealloc(o->data, 1 + o->maxlen);
2886 }
2887}
2888
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002889static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002890{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002891 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002892 if (o->length < o->maxlen) {
2893 /* likely. avoid o_grow_by() call */
2894 add:
2895 o->data[o->length] = ch;
2896 o->length++;
2897 o->data[o->length] = '\0';
2898 return;
2899 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002900 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002901 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002902}
2903
Denys Vlasenko657086a2016-09-29 18:07:42 +02002904#if 0
2905/* Valid only if we know o_string is not empty */
2906static void o_delchr(o_string *o)
2907{
2908 o->length--;
2909 o->data[o->length] = '\0';
2910}
2911#endif
2912
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002913static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002914{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002915 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002916 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002917 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002918}
2919
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002920static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002921{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002922 o_addblock(o, str, strlen(str));
2923}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002924
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002925static void o_addstr_with_NUL(o_string *o, const char *str)
2926{
2927 o_addblock(o, str, strlen(str) + 1);
2928}
2929
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002930#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002931static void nommu_addchr(o_string *o, int ch)
2932{
2933 if (o)
2934 o_addchr(o, ch);
2935}
2936#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002937# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002938#endif
2939
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002940#if ENABLE_HUSH_MODE_X
2941static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002942{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002943 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002944}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002945static void x_mode_addstr(const char *str)
2946{
2947 o_addstr(&G.x_mode_buf, str);
2948}
2949static void x_mode_addblock(const char *str, int len)
2950{
2951 o_addblock(&G.x_mode_buf, str, len);
2952}
2953static void x_mode_prefix(void)
2954{
2955 int n = G.x_mode_depth;
2956 do x_mode_addchr('+'); while (--n >= 0);
2957}
2958static void x_mode_flush(void)
2959{
2960 int len = G.x_mode_buf.length;
2961 if (len <= 0)
2962 return;
2963 if (G.x_mode_fd > 0) {
2964 G.x_mode_buf.data[len] = '\n';
2965 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2966 }
2967 G.x_mode_buf.length = 0;
2968}
2969#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002970
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002971/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002972 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002973 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2974 * Apparently, on unquoted $v bash still does globbing
2975 * ("v='*.txt'; echo $v" prints all .txt files),
2976 * but NOT brace expansion! Thus, there should be TWO independent
2977 * quoting mechanisms on $v expansion side: one protects
2978 * $v from brace expansion, and other additionally protects "$v" against globbing.
2979 * We have only second one.
2980 */
2981
Denys Vlasenko9e800222010-10-03 14:28:04 +02002982#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002983# define MAYBE_BRACES "{}"
2984#else
2985# define MAYBE_BRACES ""
2986#endif
2987
Eric Andersen25f27032001-04-26 23:22:31 +00002988/* My analysis of quoting semantics tells me that state information
2989 * is associated with a destination, not a source.
2990 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002991static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002992{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002993 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002994 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002995 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002996 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002997 o_grow_by(o, sz);
2998 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002999 o->data[o->length] = '\\';
3000 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003001 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003002 o->data[o->length] = ch;
3003 o->length++;
3004 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003005}
3006
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003007static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003008{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003009 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003010 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3011 && strchr("*?[\\" MAYBE_BRACES, ch)
3012 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003013 sz++;
3014 o->data[o->length] = '\\';
3015 o->length++;
3016 }
3017 o_grow_by(o, sz);
3018 o->data[o->length] = ch;
3019 o->length++;
3020 o->data[o->length] = '\0';
3021}
3022
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003023static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003024{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003025 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003026 char ch;
3027 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003028 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003029 if (ordinary_cnt > len) /* paranoia */
3030 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003031 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003032 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003033 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003034 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003035 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003036
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003037 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003038 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003039 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003040 sz++;
3041 o->data[o->length] = '\\';
3042 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003043 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003044 o_grow_by(o, sz);
3045 o->data[o->length] = ch;
3046 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003047 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003048 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003049}
3050
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003051static void o_addQblock(o_string *o, const char *str, int len)
3052{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003053 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003054 o_addblock(o, str, len);
3055 return;
3056 }
3057 o_addqblock(o, str, len);
3058}
3059
Denys Vlasenko38292b62010-09-05 14:49:40 +02003060static void o_addQstr(o_string *o, const char *str)
3061{
3062 o_addQblock(o, str, strlen(str));
3063}
3064
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003065/* A special kind of o_string for $VAR and `cmd` expansion.
3066 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003067 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003068 * list[i] contains an INDEX (int!) into this string data.
3069 * It means that if list[] needs to grow, data needs to be moved higher up
3070 * but list[i]'s need not be modified.
3071 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003072 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003073 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3074 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003075#if DEBUG_EXPAND || DEBUG_GLOB
3076static void debug_print_list(const char *prefix, o_string *o, int n)
3077{
3078 char **list = (char**)o->data;
3079 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3080 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003081
3082 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003083 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 +02003084 prefix, list, n, string_start, o->length, o->maxlen,
3085 !!(o->o_expflags & EXP_FLAG_GLOB),
3086 o->has_quoted_part,
3087 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003088 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003089 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003090 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3091 o->data + (int)(uintptr_t)list[i] + string_start,
3092 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003093 i++;
3094 }
3095 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003096 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003097 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003098 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003099 }
3100}
3101#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003102# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003103#endif
3104
3105/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3106 * in list[n] so that it points past last stored byte so far.
3107 * It returns n+1. */
3108static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003109{
3110 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003111 int string_start;
3112 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003113
3114 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003115 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3116 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003117 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003118 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003119 /* list[n] points to string_start, make space for 16 more pointers */
3120 o->maxlen += 0x10 * sizeof(list[0]);
3121 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003122 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003123 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003124 /*
3125 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3126 * check. (grep for -prev-ifs-check-).
3127 * Ensure that argv[-1][last] is not garbage
3128 * but zero bytes, to save index check there.
3129 */
3130 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003131 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003132 } else {
3133 debug_printf_list("list[%d]=%d string_start=%d\n",
3134 n, string_len, string_start);
3135 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003136 } else {
3137 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003138 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3139 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003140 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3141 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003142 o->has_empty_slot = 0;
3143 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003144 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003145 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003146 return n + 1;
3147}
3148
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003149/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003150static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003151{
3152 char **list = (char**)o->data;
3153 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3154
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003155 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003156}
3157
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003158/*
3159 * Globbing routines.
3160 *
3161 * Most words in commands need to be globbed, even ones which are
3162 * (single or double) quoted. This stems from the possiblity of
3163 * constructs like "abc"* and 'abc'* - these should be globbed.
3164 * Having a different code path for fully-quoted strings ("abc",
3165 * 'abc') would only help performance-wise, but we still need
3166 * code for partially-quoted strings.
3167 *
3168 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003169 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003170 * to a string, then globbed, and if globbing does not match anything,
3171 * it is used verbatim". Here are two examples where it fails:
3172 *
3173 * echo 'b\*'?
3174 *
3175 * The globbing can't be avoided (because of '?' at the end).
3176 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3177 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003178 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003179 * Now, look at this:
3180 *
3181 * v='\\\*'; echo b$v?
3182 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003183 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003184 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003185 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003186 *
3187 * ash implements this by having an encoded representation of the word
3188 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3189 * Glob pattern is derived from it. If glob fails, the decision what result
3190 * should be is made using that encoded representation. Not glob pattern.
3191 */
3192
Denys Vlasenko9e800222010-10-03 14:28:04 +02003193#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003194/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3195 * first, it processes even {a} (no commas), second,
3196 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003197 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003198 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003199
3200/* Helper */
3201static int glob_needed(const char *s)
3202{
3203 while (*s) {
3204 if (*s == '\\') {
3205 if (!s[1])
3206 return 0;
3207 s += 2;
3208 continue;
3209 }
3210 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3211 return 1;
3212 s++;
3213 }
3214 return 0;
3215}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003216/* Return pointer to next closing brace or to comma */
3217static const char *next_brace_sub(const char *cp)
3218{
3219 unsigned depth = 0;
3220 cp++;
3221 while (*cp != '\0') {
3222 if (*cp == '\\') {
3223 if (*++cp == '\0')
3224 break;
3225 cp++;
3226 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003227 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003228 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003229 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003230 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003231 depth++;
3232 }
3233
3234 return *cp != '\0' ? cp : NULL;
3235}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003236/* Recursive brace globber. Note: may garble pattern[]. */
3237static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003238{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003239 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003240 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003241 const char *next;
3242 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003243 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003244 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003245
3246 debug_printf_glob("glob_brace('%s')\n", pattern);
3247
3248 begin = pattern;
3249 while (1) {
3250 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003251 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003252 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003253 /* Find the first sub-pattern and at the same time
3254 * find the rest after the closing brace */
3255 next = next_brace_sub(begin);
3256 if (next == NULL) {
3257 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003258 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003259 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003260 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003261 /* "{abc}" with no commas - illegal
3262 * brace expr, disregard and skip it */
3263 begin = next + 1;
3264 continue;
3265 }
3266 break;
3267 }
3268 if (*begin == '\\' && begin[1] != '\0')
3269 begin++;
3270 begin++;
3271 }
3272 debug_printf_glob("begin:%s\n", begin);
3273 debug_printf_glob("next:%s\n", next);
3274
3275 /* Now find the end of the whole brace expression */
3276 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003277 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003278 rest = next_brace_sub(rest);
3279 if (rest == NULL) {
3280 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003281 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003282 }
3283 debug_printf_glob("rest:%s\n", rest);
3284 }
3285 rest_len = strlen(++rest) + 1;
3286
3287 /* We are sure the brace expression is well-formed */
3288
3289 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003290 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003291
3292 /* We have a brace expression. BEGIN points to the opening {,
3293 * NEXT points past the terminator of the first element, and REST
3294 * points past the final }. We will accumulate result names from
3295 * recursive runs for each brace alternative in the buffer using
3296 * GLOB_APPEND. */
3297
3298 p = begin + 1;
3299 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003300 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003301 memcpy(
3302 mempcpy(
3303 mempcpy(new_pattern_buf,
3304 /* We know the prefix for all sub-patterns */
3305 pattern, begin - pattern),
3306 p, next - p),
3307 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003308
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003309 /* Note: glob_brace() may garble new_pattern_buf[].
3310 * That's why we re-copy prefix every time (1st memcpy above).
3311 */
3312 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003313 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003314 /* We saw the last entry */
3315 break;
3316 }
3317 p = next + 1;
3318 next = next_brace_sub(next);
3319 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003320 free(new_pattern_buf);
3321 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003322
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003323 simple_glob:
3324 {
3325 int gr;
3326 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003327
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003328 memset(&globdata, 0, sizeof(globdata));
3329 gr = glob(pattern, 0, NULL, &globdata);
3330 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3331 if (gr != 0) {
3332 if (gr == GLOB_NOMATCH) {
3333 globfree(&globdata);
3334 /* NB: garbles parameter */
3335 unbackslash(pattern);
3336 o_addstr_with_NUL(o, pattern);
3337 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3338 return o_save_ptr_helper(o, n);
3339 }
3340 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003341 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003342 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3343 * but we didn't specify it. Paranoia again. */
3344 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3345 }
3346 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3347 char **argv = globdata.gl_pathv;
3348 while (1) {
3349 o_addstr_with_NUL(o, *argv);
3350 n = o_save_ptr_helper(o, n);
3351 argv++;
3352 if (!*argv)
3353 break;
3354 }
3355 }
3356 globfree(&globdata);
3357 }
3358 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003359}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003360/* Performs globbing on last list[],
3361 * saving each result as a new list[].
3362 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003363static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003364{
3365 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003366
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003367 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003368 if (!o->data)
3369 return o_save_ptr_helper(o, n);
3370 pattern = o->data + o_get_last_ptr(o, n);
3371 debug_printf_glob("glob pattern '%s'\n", pattern);
3372 if (!glob_needed(pattern)) {
3373 /* unbackslash last string in o in place, fix length */
3374 o->length = unbackslash(pattern) - o->data;
3375 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3376 return o_save_ptr_helper(o, n);
3377 }
3378
3379 copy = xstrdup(pattern);
3380 /* "forget" pattern in o */
3381 o->length = pattern - o->data;
3382 n = glob_brace(copy, o, n);
3383 free(copy);
3384 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003385 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003386 return n;
3387}
3388
Denys Vlasenko238081f2010-10-03 14:26:26 +02003389#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003390
3391/* Helper */
3392static int glob_needed(const char *s)
3393{
3394 while (*s) {
3395 if (*s == '\\') {
3396 if (!s[1])
3397 return 0;
3398 s += 2;
3399 continue;
3400 }
3401 if (*s == '*' || *s == '[' || *s == '?')
3402 return 1;
3403 s++;
3404 }
3405 return 0;
3406}
3407/* Performs globbing on last list[],
3408 * saving each result as a new list[].
3409 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003410static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003411{
3412 glob_t globdata;
3413 int gr;
3414 char *pattern;
3415
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003416 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003417 if (!o->data)
3418 return o_save_ptr_helper(o, n);
3419 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003420 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003421 if (!glob_needed(pattern)) {
3422 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003423 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003424 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003425 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003426 return o_save_ptr_helper(o, n);
3427 }
3428
3429 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003430 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3431 * If we glob "*.\*" and don't find anything, we need
3432 * to fall back to using literal "*.*", but GLOB_NOCHECK
3433 * will return "*.\*"!
3434 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003435 gr = glob(pattern, 0, NULL, &globdata);
3436 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003437 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003438 if (gr == GLOB_NOMATCH) {
3439 globfree(&globdata);
3440 goto literal;
3441 }
3442 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003443 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003444 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3445 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003446 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003447 }
3448 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3449 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003450 /* "forget" pattern in o */
3451 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003452 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003453 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003454 n = o_save_ptr_helper(o, n);
3455 argv++;
3456 if (!*argv)
3457 break;
3458 }
3459 }
3460 globfree(&globdata);
3461 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003462 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003463 return n;
3464}
3465
Denys Vlasenko238081f2010-10-03 14:26:26 +02003466#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003467
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003468/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003469 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003470static int o_save_ptr(o_string *o, int n)
3471{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003472 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003473 /* If o->has_empty_slot, list[n] was already globbed
3474 * (if it was requested back then when it was filled)
3475 * so don't do that again! */
3476 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003477 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003478 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003479 return o_save_ptr_helper(o, n);
3480}
3481
3482/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003483static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003484{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003485 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003486 int string_start;
3487
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003488 if (DEBUG_EXPAND)
3489 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003490 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003491 list = (char**)o->data;
3492 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3493 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003494 while (n) {
3495 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003496 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003497 }
3498 return list;
3499}
3500
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003501static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003502
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003503/* Returns pi->next - next pipe in the list */
3504static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003505{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003506 struct pipe *next;
3507 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003508
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003509 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003510 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003511 struct command *command;
3512 struct redir_struct *r, *rnext;
3513
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003514 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003515 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003516 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003517 if (DEBUG_CLEAN) {
3518 int a;
3519 char **p;
3520 for (a = 0, p = command->argv; *p; a++, p++) {
3521 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3522 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003523 }
3524 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003525 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003526 }
3527 /* not "else if": on syntax error, we may have both! */
3528 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003529 debug_printf_clean(" begin group (cmd_type:%d)\n",
3530 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003531 free_pipe_list(command->group);
3532 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003533 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003534 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003535 /* else is crucial here.
3536 * If group != NULL, child_func is meaningless */
3537#if ENABLE_HUSH_FUNCTIONS
3538 else if (command->child_func) {
3539 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3540 command->child_func->parent_cmd = NULL;
3541 }
3542#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003543#if !BB_MMU
3544 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003545 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003546#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003547 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003548 debug_printf_clean(" redirect %d%s",
3549 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003550 /* guard against the case >$FOO, where foo is unset or blank */
3551 if (r->rd_filename) {
3552 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3553 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003554 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003555 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003556 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003557 rnext = r->next;
3558 free(r);
3559 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003560 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003561 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003562 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003563 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003564#if ENABLE_HUSH_JOB
3565 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003566 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003567#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003568
3569 next = pi->next;
3570 free(pi);
3571 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003572}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003573
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003574static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003575{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003576 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003577#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003578 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003579#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003580 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003581 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003582 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003583}
3584
3585
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003586/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003587
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003588#ifndef debug_print_tree
3589static void debug_print_tree(struct pipe *pi, int lvl)
3590{
3591 static const char *const PIPE[] = {
3592 [PIPE_SEQ] = "SEQ",
3593 [PIPE_AND] = "AND",
3594 [PIPE_OR ] = "OR" ,
3595 [PIPE_BG ] = "BG" ,
3596 };
3597 static const char *RES[] = {
3598 [RES_NONE ] = "NONE" ,
3599# if ENABLE_HUSH_IF
3600 [RES_IF ] = "IF" ,
3601 [RES_THEN ] = "THEN" ,
3602 [RES_ELIF ] = "ELIF" ,
3603 [RES_ELSE ] = "ELSE" ,
3604 [RES_FI ] = "FI" ,
3605# endif
3606# if ENABLE_HUSH_LOOPS
3607 [RES_FOR ] = "FOR" ,
3608 [RES_WHILE] = "WHILE",
3609 [RES_UNTIL] = "UNTIL",
3610 [RES_DO ] = "DO" ,
3611 [RES_DONE ] = "DONE" ,
3612# endif
3613# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3614 [RES_IN ] = "IN" ,
3615# endif
3616# if ENABLE_HUSH_CASE
3617 [RES_CASE ] = "CASE" ,
3618 [RES_CASE_IN ] = "CASE_IN" ,
3619 [RES_MATCH] = "MATCH",
3620 [RES_CASE_BODY] = "CASE_BODY",
3621 [RES_ESAC ] = "ESAC" ,
3622# endif
3623 [RES_XXXX ] = "XXXX" ,
3624 [RES_SNTX ] = "SNTX" ,
3625 };
3626 static const char *const CMDTYPE[] = {
3627 "{}",
3628 "()",
3629 "[noglob]",
3630# if ENABLE_HUSH_FUNCTIONS
3631 "func()",
3632# endif
3633 };
3634
3635 int pin, prn;
3636
3637 pin = 0;
3638 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003639 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3640 lvl*2, "",
3641 pin,
3642 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3643 RES[pi->res_word],
3644 pi->followup, PIPE[pi->followup]
3645 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003646 prn = 0;
3647 while (prn < pi->num_cmds) {
3648 struct command *command = &pi->cmds[prn];
3649 char **argv = command->argv;
3650
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003651 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003652 lvl*2, "", prn,
3653 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003654#if ENABLE_HUSH_LINENO_VAR
3655 fdprintf(2, " LINENO:%u", command->lineno);
3656#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003657 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003658 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003659 CMDTYPE[command->cmd_type],
3660 argv
3661# if !BB_MMU
3662 , " group_as_string:", command->group_as_string
3663# else
3664 , "", ""
3665# endif
3666 );
3667 debug_print_tree(command->group, lvl+1);
3668 prn++;
3669 continue;
3670 }
3671 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003672 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003673 argv++;
3674 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003675 if (command->redirects)
3676 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003677 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003678 prn++;
3679 }
3680 pi = pi->next;
3681 pin++;
3682 }
3683}
3684#endif /* debug_print_tree */
3685
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003686static struct pipe *new_pipe(void)
3687{
Eric Andersen25f27032001-04-26 23:22:31 +00003688 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003689 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003690 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003691 return pi;
3692}
3693
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003694/* Command (member of a pipe) is complete, or we start a new pipe
3695 * if ctx->command is NULL.
3696 * No errors possible here.
3697 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003698static int done_command(struct parse_context *ctx)
3699{
3700 /* The command is really already in the pipe structure, so
3701 * advance the pipe counter and make a new, null command. */
3702 struct pipe *pi = ctx->pipe;
3703 struct command *command = ctx->command;
3704
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003705#if 0 /* Instead we emit error message at run time */
3706 if (ctx->pending_redirect) {
3707 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003708 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003709 ctx->pending_redirect = NULL;
3710 }
3711#endif
3712
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003713 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003714 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003715 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003716 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003717 }
3718 pi->num_cmds++;
3719 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003720 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003721 } else {
3722 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3723 }
3724
3725 /* Only real trickiness here is that the uncommitted
3726 * command structure is not counted in pi->num_cmds. */
3727 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003728 ctx->command = command = &pi->cmds[pi->num_cmds];
3729 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003730 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003731#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003732 command->lineno = G.parse_lineno;
3733 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003734#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003735 return pi->num_cmds; /* used only for 0/nonzero check */
3736}
3737
3738static void done_pipe(struct parse_context *ctx, pipe_style type)
3739{
3740 int not_null;
3741
3742 debug_printf_parse("done_pipe entered, followup %d\n", type);
3743 /* Close previous command */
3744 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003745#if HAS_KEYWORDS
3746 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3747 ctx->ctx_inverted = 0;
3748 ctx->pipe->res_word = ctx->ctx_res_w;
3749#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003750 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3751 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003752 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3753 * in a backgrounded subshell.
3754 */
3755 struct pipe *pi;
3756 struct command *command;
3757
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003758 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003759 pi = ctx->list_head;
3760 while (pi != ctx->pipe) {
3761 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3762 goto no_conv;
3763 pi = pi->next;
3764 }
3765
3766 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3767 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3768 pi = xzalloc(sizeof(*pi));
3769 pi->followup = PIPE_BG;
3770 pi->num_cmds = 1;
3771 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3772 command = &pi->cmds[0];
3773 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3774 command->cmd_type = CMD_NORMAL;
3775 command->group = ctx->list_head;
3776#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003777 command->group_as_string = xstrndup(
3778 ctx->as_string.data,
3779 ctx->as_string.length - 1 /* do not copy last char, "&" */
3780 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003781#endif
3782 /* Replace all pipes in ctx with one newly created */
3783 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003784 } else {
3785 no_conv:
3786 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003787 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003788
3789 /* Without this check, even just <enter> on command line generates
3790 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003791 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003792 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003793#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003794 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003795#endif
3796#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003797 || ctx->ctx_res_w == RES_DONE
3798 || ctx->ctx_res_w == RES_FOR
3799 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003800#endif
3801#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003802 || ctx->ctx_res_w == RES_ESAC
3803#endif
3804 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003805 struct pipe *new_p;
3806 debug_printf_parse("done_pipe: adding new pipe: "
3807 "not_null:%d ctx->ctx_res_w:%d\n",
3808 not_null, ctx->ctx_res_w);
3809 new_p = new_pipe();
3810 ctx->pipe->next = new_p;
3811 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003812 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003813 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003814 * This is used to control execution.
3815 * RES_FOR and RES_IN are NOT sticky (needed to support
3816 * cases where variable or value happens to match a keyword):
3817 */
3818#if ENABLE_HUSH_LOOPS
3819 if (ctx->ctx_res_w == RES_FOR
3820 || ctx->ctx_res_w == RES_IN)
3821 ctx->ctx_res_w = RES_NONE;
3822#endif
3823#if ENABLE_HUSH_CASE
3824 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003825 ctx->ctx_res_w = RES_CASE_BODY;
3826 if (ctx->ctx_res_w == RES_CASE)
3827 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003828#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003829 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003830 /* Create the memory for command, roughly:
3831 * ctx->pipe->cmds = new struct command;
3832 * ctx->command = &ctx->pipe->cmds[0];
3833 */
3834 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003835 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003836 }
3837 debug_printf_parse("done_pipe return\n");
3838}
3839
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003840static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003841{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003842 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003843 if (MAYBE_ASSIGNMENT != 0)
3844 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003845 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003846 /* Create the memory for command, roughly:
3847 * ctx->pipe->cmds = new struct command;
3848 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003849 */
3850 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003851}
3852
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003853/* If a reserved word is found and processed, parse context is modified
3854 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003855 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003856#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003857struct reserved_combo {
3858 char literal[6];
3859 unsigned char res;
3860 unsigned char assignment_flag;
3861 int flag;
3862};
3863enum {
3864 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003865# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003866 FLAG_IF = (1 << RES_IF ),
3867 FLAG_THEN = (1 << RES_THEN ),
3868 FLAG_ELIF = (1 << RES_ELIF ),
3869 FLAG_ELSE = (1 << RES_ELSE ),
3870 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003871# endif
3872# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003873 FLAG_FOR = (1 << RES_FOR ),
3874 FLAG_WHILE = (1 << RES_WHILE),
3875 FLAG_UNTIL = (1 << RES_UNTIL),
3876 FLAG_DO = (1 << RES_DO ),
3877 FLAG_DONE = (1 << RES_DONE ),
3878 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003879# endif
3880# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003881 FLAG_MATCH = (1 << RES_MATCH),
3882 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003883# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003884 FLAG_START = (1 << RES_XXXX ),
3885};
3886
3887static const struct reserved_combo* match_reserved_word(o_string *word)
3888{
Eric Andersen25f27032001-04-26 23:22:31 +00003889 /* Mostly a list of accepted follow-up reserved words.
3890 * FLAG_END means we are done with the sequence, and are ready
3891 * to turn the compound list into a command.
3892 * FLAG_START means the word must start a new compound list.
3893 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003894 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003895# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003896 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3897 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3898 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3899 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3900 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3901 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003902# endif
3903# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003904 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3905 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3906 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3907 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3908 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3909 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003910# endif
3911# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003912 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3913 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003914# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003915 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003916 const struct reserved_combo *r;
3917
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003918 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003919 if (strcmp(word->data, r->literal) == 0)
3920 return r;
3921 }
3922 return NULL;
3923}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003924/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003925 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003926static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003927{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003928# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003929 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003930 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003931 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003932# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003933 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003934
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003935 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003936 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003937 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003938 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003939 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003940
3941 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003942# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003943 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3944 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003945 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003946 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003947# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003948 if (r->flag == 0) { /* '!' */
3949 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003950 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003951 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003952 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003953 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003954 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003955 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003956 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003957 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003958
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003959 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003960 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003961 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003962 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003963 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003964 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003965 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003966 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003967 } else {
3968 /* "{...} fi" is ok. "{...} if" is not
3969 * Example:
3970 * if { echo foo; } then { echo bar; } fi */
3971 if (ctx->command->group)
3972 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003973 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003974
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003975 ctx->ctx_res_w = r->res;
3976 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003977 ctx->is_assignment = r->assignment_flag;
3978 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003979
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003980 if (ctx->old_flag & FLAG_END) {
3981 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003982
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003983 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003984 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003985 old = ctx->stack;
3986 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003987 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003988# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003989 /* At this point, the compound command's string is in
3990 * ctx->as_string... except for the leading keyword!
3991 * Consider this example: "echo a | if true; then echo a; fi"
3992 * ctx->as_string will contain "true; then echo a; fi",
3993 * with "if " remaining in old->as_string!
3994 */
3995 {
3996 char *str;
3997 int len = old->as_string.length;
3998 /* Concatenate halves */
3999 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004000 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004001 /* Find where leading keyword starts in first half */
4002 str = old->as_string.data + len;
4003 if (str > old->as_string.data)
4004 str--; /* skip whitespace after keyword */
4005 while (str > old->as_string.data && isalpha(str[-1]))
4006 str--;
4007 /* Ugh, we're done with this horrid hack */
4008 old->command->group_as_string = xstrdup(str);
4009 debug_printf_parse("pop, remembering as:'%s'\n",
4010 old->command->group_as_string);
4011 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004012# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004013 *ctx = *old; /* physical copy */
4014 free(old);
4015 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004016 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004017}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004018#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004019
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004020/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004021 * Normal return is 0. Syntax errors return 1.
4022 * Note: on return, word is reset, but not o_free'd!
4023 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004024static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004025{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004026 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004027
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004028 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4029 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004030 debug_printf_parse("done_word return 0: true null, ignored\n");
4031 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004032 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004033
Eric Andersen25f27032001-04-26 23:22:31 +00004034 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004035 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4036 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004037 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004038 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004039 * If the redirection operator is "<<" or "<<-", the word
4040 * that follows the redirection operator shall be
4041 * subjected to quote removal; it is unspecified whether
4042 * any of the other expansions occur. For the other
4043 * redirection operators, the word that follows the
4044 * redirection operator shall be subjected to tilde
4045 * expansion, parameter expansion, command substitution,
4046 * arithmetic expansion, and quote removal.
4047 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004048 * on the word by a non-interactive shell; an interactive
4049 * shell may perform it, but shall do so only when
4050 * the expansion would result in one word."
4051 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004052//bash does not do parameter/command substitution or arithmetic expansion
4053//for _heredoc_ redirection word: these constructs look for exact eof marker
4054// as written:
4055// <<EOF$t
4056// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004057// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4058
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004059 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004060 /* Cater for >\file case:
4061 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4062 * Same with heredocs:
4063 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4064 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004065 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4066 unbackslash(ctx->pending_redirect->rd_filename);
4067 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004068 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004069 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4070 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004071 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004072 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004073 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004074 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004075#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004076# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004077 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004078 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004079 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004080 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004081 /* ctx->ctx_res_w = RES_MATCH; */
4082 ctx->ctx_dsemicolon = 0;
4083 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004084# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004085 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004086# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004087 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4088 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004089# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004090# if ENABLE_HUSH_CASE
4091 && ctx->ctx_res_w != RES_CASE
4092# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004093 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004094 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004095 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004096 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004097 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004098# if ENABLE_HUSH_LINENO_VAR
4099/* Case:
4100 * "while ...; do
4101 * cmd ..."
4102 * If we don't close the pipe _now_, immediately after "do", lineno logic
4103 * sees "cmd" as starting at "do" - i.e., at the previous line.
4104 */
4105 if (0
4106 IF_HUSH_IF(|| reserved->res == RES_THEN)
4107 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4108 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4109 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4110 ) {
4111 done_pipe(ctx, PIPE_SEQ);
4112 }
4113# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004114 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004115 debug_printf_parse("done_word return %d\n",
4116 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004117 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004118 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004119# if defined(CMD_SINGLEWORD_NOGLOB)
4120 if (0
4121# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004122 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004123# endif
4124 /* In bash, local/export/readonly are special, args
4125 * are assignments and therefore expansion of them
4126 * should be "one-word" expansion:
4127 * $ export i=`echo 'a b'` # one arg: "i=a b"
4128 * compare with:
4129 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4130 * ls: cannot access i=a: No such file or directory
4131 * ls: cannot access b: No such file or directory
4132 * Note: bash 3.2.33(1) does this only if export word
4133 * itself is not quoted:
4134 * $ export i=`echo 'aaa bbb'`; echo "$i"
4135 * aaa bbb
4136 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4137 * aaa
4138 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004139 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4140 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4141 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004142 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004143 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4144 }
4145 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004146# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004147 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004148#endif /* HAS_KEYWORDS */
4149
Denis Vlasenkobb929512009-04-16 10:59:40 +00004150 if (command->group) {
4151 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004152 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004153 debug_printf_parse("done_word return 1: syntax error, "
4154 "groups and arglists don't mix\n");
4155 return 1;
4156 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004157
4158 /* If this word wasn't an assignment, next ones definitely
4159 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004160 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4161 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004162 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004163 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004164 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004165 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004166 command->assignment_cnt++;
4167 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4168 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004169 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4170 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004171 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004172 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4173 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004174 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004175 }
Eric Andersen25f27032001-04-26 23:22:31 +00004176
Denis Vlasenko06810332007-05-21 23:30:54 +00004177#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004178 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004179 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004180 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004181 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004182 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004183 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004184 return 1;
4185 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004186 /* Force FOR to have just one word (variable name) */
4187 /* NB: basically, this makes hush see "for v in ..."
4188 * syntax as if it is "for v; in ...". FOR and IN become
4189 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004190 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004191 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004192#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004193#if ENABLE_HUSH_CASE
4194 /* Force CASE to have just one word */
4195 if (ctx->ctx_res_w == RES_CASE) {
4196 done_pipe(ctx, PIPE_SEQ);
4197 }
4198#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004199
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004200 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004201
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004202 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004203 return 0;
4204}
4205
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206
4207/* Peek ahead in the input to find out if we have a "&n" construct,
4208 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004209 * Return:
4210 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4211 * REDIRFD_SYNTAX_ERR if syntax error,
4212 * REDIRFD_TO_FILE if no & was seen,
4213 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004214 */
4215#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004216#define parse_redir_right_fd(as_string, input) \
4217 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004218#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004219static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004220{
4221 int ch, d, ok;
4222
4223 ch = i_peek(input);
4224 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004225 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004226
4227 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004228 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004229 ch = i_peek(input);
4230 if (ch == '-') {
4231 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004232 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004233 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004234 }
4235 d = 0;
4236 ok = 0;
4237 while (ch != EOF && isdigit(ch)) {
4238 d = d*10 + (ch-'0');
4239 ok = 1;
4240 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004241 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004242 ch = i_peek(input);
4243 }
4244 if (ok) return d;
4245
4246//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4247
4248 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004249 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250}
4251
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004252/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004253 */
4254static int parse_redirect(struct parse_context *ctx,
4255 int fd,
4256 redir_type style,
4257 struct in_str *input)
4258{
4259 struct command *command = ctx->command;
4260 struct redir_struct *redir;
4261 struct redir_struct **redirp;
4262 int dup_num;
4263
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004264 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004265 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004266 /* Check for a '>&1' type redirect */
4267 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4268 if (dup_num == REDIRFD_SYNTAX_ERR)
4269 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004270 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004271 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004272 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004273 if (dup_num) { /* <<-... */
4274 ch = i_getch(input);
4275 nommu_addchr(&ctx->as_string, ch);
4276 ch = i_peek(input);
4277 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004278 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004279
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004280 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004281 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004282 if (ch == '|') {
4283 /* >|FILE redirect ("clobbering" >).
4284 * Since we do not support "set -o noclobber" yet,
4285 * >| and > are the same for now. Just eat |.
4286 */
4287 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004288 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 }
4290 }
4291
4292 /* Create a new redir_struct and append it to the linked list */
4293 redirp = &command->redirects;
4294 while ((redir = *redirp) != NULL) {
4295 redirp = &(redir->next);
4296 }
4297 *redirp = redir = xzalloc(sizeof(*redir));
4298 /* redir->next = NULL; */
4299 /* redir->rd_filename = NULL; */
4300 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004301 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004302
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004303 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4304 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004305
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004306 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004307 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004308 /* Erik had a check here that the file descriptor in question
4309 * is legit; I postpone that to "run time"
4310 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004311 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4312 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004313 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004314#if 0 /* Instead we emit error message at run time */
4315 if (ctx->pending_redirect) {
4316 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004317 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004318 }
4319#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004320 /* Set ctx->pending_redirect, so we know what to do at the
4321 * end of the next parsed word. */
4322 ctx->pending_redirect = redir;
4323 }
4324 return 0;
4325}
4326
Eric Andersen25f27032001-04-26 23:22:31 +00004327/* If a redirect is immediately preceded by a number, that number is
4328 * supposed to tell which file descriptor to redirect. This routine
4329 * looks for such preceding numbers. In an ideal world this routine
4330 * needs to handle all the following classes of redirects...
4331 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4332 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4333 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4334 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004335 *
4336 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4337 * "2.7 Redirection
4338 * ... If n is quoted, the number shall not be recognized as part of
4339 * the redirection expression. For example:
4340 * echo \2>a
4341 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004342 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004343 *
4344 * A -1 return means no valid number was found,
4345 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004346 */
4347static int redirect_opt_num(o_string *o)
4348{
4349 int num;
4350
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004351 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004352 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004353 num = bb_strtou(o->data, NULL, 10);
4354 if (errno || num < 0)
4355 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004356 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004357 return num;
4358}
4359
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004360#if BB_MMU
4361#define fetch_till_str(as_string, input, word, skip_tabs) \
4362 fetch_till_str(input, word, skip_tabs)
4363#endif
4364static char *fetch_till_str(o_string *as_string,
4365 struct in_str *input,
4366 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004367 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004368{
4369 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004370 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004371 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004372 int ch;
4373
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004374 /* Starting with "" is necessary for this case:
4375 * cat <<EOF
4376 *
4377 * xxx
4378 * EOF
4379 */
4380 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4381
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004382 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004383
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004384 while (1) {
4385 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004386 if (ch != EOF)
4387 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004388 if (ch == '\n' || ch == EOF) {
4389 check_heredoc_end:
4390 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004391 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004392 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4393 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004394 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004395 return heredoc.data;
4396 }
4397 if (ch == '\n') {
4398 /* This is a new line.
4399 * Remember position and backslash-escaping status.
4400 */
4401 o_addchr(&heredoc, ch);
4402 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004403 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004404 past_EOL = heredoc.length;
4405 /* Get 1st char of next line, possibly skipping leading tabs */
4406 do {
4407 ch = i_getch(input);
4408 if (ch != EOF)
4409 nommu_addchr(as_string, ch);
4410 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4411 /* If this immediately ended the line,
4412 * go back to end-of-line checks.
4413 */
4414 if (ch == '\n')
4415 goto check_heredoc_end;
4416 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004417 } else {
4418 /* Backslash-line continuation in an unquoted
4419 * heredoc. This does not need special handling
4420 * for heredoc body (unquoted heredocs are
4421 * expanded on "execution" and that would take
4422 * care of this case too), but not the case
4423 * of line continuation *in terminator*:
4424 * cat <<EOF
4425 * Ok1
4426 * EO\
4427 * F
4428 */
4429 heredoc.data[--heredoc.length] = '\0';
4430 prev = 0; /* not '\' */
4431 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004432 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004433 }
4434 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004435 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004436 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004437 }
4438 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004439 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004440 if (prev == '\\' && ch == '\\')
4441 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004442 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004443 else
4444 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004445 }
4446}
4447
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004448/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4449 * and load them all. There should be exactly heredoc_cnt of them.
4450 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004451#if BB_MMU
4452#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4453 fetch_heredocs(pi, heredoc_cnt, input)
4454#endif
4455static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004456{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004457 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004458 int i;
4459 struct command *cmd = pi->cmds;
4460
Denys Vlasenko3675c372018-07-23 16:31:21 +02004461 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004462 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004463 cmd->argv ? cmd->argv[0] : "NONE"
4464 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004465 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004466 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004467
Denys Vlasenko3675c372018-07-23 16:31:21 +02004468 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004469 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004470 while (redir) {
4471 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004472 char *p;
4473
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004474 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004475 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004476 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004477 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004478 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004479 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004480 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004481 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004482 free(redir->rd_filename);
4483 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004484 heredoc_cnt--;
4485 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004486 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004487 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004488 if (cmd->group) {
4489 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4490 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4491 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4492 if (heredoc_cnt < 0)
4493 return heredoc_cnt; /* error */
4494 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004495 cmd++;
4496 }
4497 pi = pi->next;
4498 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004499 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004500}
4501
4502
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004503static int run_list(struct pipe *pi);
4504#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004505#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4506 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004507#endif
4508static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004509 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004510 struct in_str *input,
4511 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004512
Denys Vlasenko474cb202018-07-24 13:03:03 +02004513/* Returns number of heredocs not yet consumed,
4514 * or -1 on error.
4515 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004516static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004517 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004518{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004519 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004520 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004521 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004522#if BB_MMU
4523# define as_string NULL
4524#else
4525 char *as_string = NULL;
4526#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004527 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004528 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004529 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004530 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004531
4532 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004533#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004534 if (ch == '(' && !ctx->word.has_quoted_part) {
4535 if (ctx->word.length)
4536 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004537 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004538 if (!command->argv)
4539 goto skip; /* (... */
4540 if (command->argv[1]) { /* word word ... (... */
4541 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004542 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004543 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004544 /* it is "word(..." or "word (..." */
4545 do
4546 ch = i_getch(input);
4547 while (ch == ' ' || ch == '\t');
4548 if (ch != ')') {
4549 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004550 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004551 }
4552 nommu_addchr(&ctx->as_string, ch);
4553 do
4554 ch = i_getch(input);
4555 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004556 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004557 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004558 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004559 }
4560 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004561 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004562 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004563 }
4564#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004565
4566#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004567 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004568 || ctx->word.length /* word{... */
4569 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004570 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004571 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004572 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004573 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004574 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004575 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004576#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004577
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004578 IF_HUSH_FUNCTIONS(skip:)
4579
Denis Vlasenko240c2552009-04-03 03:45:05 +00004580 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004581 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004582 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004583 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4584 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004585 } else {
4586 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004587 ch = i_peek(input);
4588 if (ch != ' ' && ch != '\t' && ch != '\n'
4589 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4590 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004591 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004592 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004593 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004594 if (ch != '(') {
4595 ch = i_getch(input);
4596 nommu_addchr(&ctx->as_string, ch);
4597 }
Eric Andersen25f27032001-04-26 23:22:31 +00004598 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004599
Denys Vlasenko474cb202018-07-24 13:03:03 +02004600 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4601 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4602 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004603#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004604 if (as_string)
4605 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004606#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004607
4608 /* empty ()/{} or parse error? */
4609 if (!pipe_list || pipe_list == ERR_PTR) {
4610 /* parse_stream already emitted error msg */
4611 if (!BB_MMU)
4612 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004613 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004614 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004615 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004616 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004617#if !BB_MMU
4618 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4619 command->group_as_string = as_string;
4620 debug_printf_parse("end of group, remembering as:'%s'\n",
4621 command->group_as_string);
4622#endif
4623
4624#if ENABLE_HUSH_FUNCTIONS
4625 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4626 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4627 struct command *cmd2;
4628
4629 cmd2 = xzalloc(sizeof(*cmd2));
4630 cmd2->cmd_type = CMD_SUBSHELL;
4631 cmd2->group = pipe_list;
4632# if !BB_MMU
4633//UNTESTED!
4634 cmd2->group_as_string = command->group_as_string;
4635 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4636# endif
4637
4638 pipe_list = new_pipe();
4639 pipe_list->cmds = cmd2;
4640 pipe_list->num_cmds = 1;
4641 }
4642#endif
4643
4644 command->group = pipe_list;
4645
Denys Vlasenko474cb202018-07-24 13:03:03 +02004646 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4647 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004648 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004649#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004650}
4651
Denys Vlasenko0b883582016-12-23 16:49:07 +01004652#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004653/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004654/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004655static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004656{
4657 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004658 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004659 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004660 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004661 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004662 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004663 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004664 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004665 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004666 }
4667}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004668static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4669{
4670 while (1) {
4671 int ch = i_getch(input);
4672 if (ch == EOF) {
4673 syntax_error_unterm_ch('\'');
4674 return 0;
4675 }
4676 if (ch == '\'')
4677 return 1;
4678 o_addqchr(dest, ch);
4679 }
4680}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004681/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004682static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004683static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004684{
4685 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004686 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004687 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004688 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004689 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004690 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004691 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004692 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004693 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004694 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004695 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004696 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004697 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004698 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004699 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4700 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004701 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004702 continue;
4703 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004704 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004705 }
4706}
4707/* Process `cmd` - copy contents until "`" is seen. Complicated by
4708 * \` quoting.
4709 * "Within the backquoted style of command substitution, backslash
4710 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4711 * The search for the matching backquote shall be satisfied by the first
4712 * backquote found without a preceding backslash; during this search,
4713 * if a non-escaped backquote is encountered within a shell comment,
4714 * a here-document, an embedded command substitution of the $(command)
4715 * form, or a quoted string, undefined results occur. A single-quoted
4716 * or double-quoted string that begins, but does not end, within the
4717 * "`...`" sequence produces undefined results."
4718 * Example Output
4719 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4720 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004721static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004722{
4723 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004724 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004725 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004726 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004727 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004728 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4729 ch = i_getch(input);
4730 if (ch != '`'
4731 && ch != '$'
4732 && ch != '\\'
4733 && (!in_dquote || ch != '"')
4734 ) {
4735 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004736 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004737 }
4738 if (ch == EOF) {
4739 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004740 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004741 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004742 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004743 }
4744}
4745/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4746 * quoting and nested ()s.
4747 * "With the $(command) style of command substitution, all characters
4748 * following the open parenthesis to the matching closing parenthesis
4749 * constitute the command. Any valid shell script can be used for command,
4750 * except a script consisting solely of redirections which produces
4751 * unspecified results."
4752 * Example Output
4753 * echo $(echo '(TEST)' BEST) (TEST) BEST
4754 * echo $(echo 'TEST)' BEST) TEST) BEST
4755 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004756 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004757 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004758 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004759 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4760 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004761 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004762#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004763static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004764{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004765 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004766 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004767# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004768 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004769# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004770 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4771
Denys Vlasenko817a2022018-06-26 15:35:17 +02004772#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004773 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004774#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004775 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4776
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004777 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004778 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004779 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004780 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004781 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004782 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004783 if (ch == end_ch
4784# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004785 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004786# endif
4787 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004788 if (!dbl)
4789 break;
4790 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004791 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004792 i_getch(input); /* eat second ')' */
4793 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004794 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004795 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004796 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004797 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004798 if (ch == '(' || ch == '{') {
4799 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004800 if (!add_till_closing_bracket(dest, input, ch))
4801 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004802 o_addchr(dest, ch);
4803 continue;
4804 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004805 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004806 if (!add_till_single_quote(dest, input))
4807 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004808 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004809 continue;
4810 }
4811 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004812 if (!add_till_double_quote(dest, input))
4813 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004814 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004815 continue;
4816 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004817 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004818 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4819 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004820 o_addchr(dest, ch);
4821 continue;
4822 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004823 if (ch == '\\') {
4824 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004825 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004826 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004827 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004828 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004829 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004830#if 0
4831 if (ch == '\n') {
4832 /* "backslash+newline", ignore both */
4833 o_delchr(dest); /* undo insertion of '\' */
4834 continue;
4835 }
4836#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004837 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004838 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004839 continue;
4840 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004841 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004842 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004843 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004844}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004845#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004846
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004847/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004848#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004849#define parse_dollar(as_string, dest, input, quote_mask) \
4850 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004851#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004852#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004853static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004854 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004855 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004856{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004857 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004858
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004859 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004860 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004861 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004862 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004863 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004864 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004865 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004866 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004867 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004868 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004869 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004870 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004871 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004872 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004873 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004874 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004875 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004876 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004877 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004879 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004880 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004881 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004882 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004883 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004884 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004885 o_addchr(dest, ch | quote_mask);
4886 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004887 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004888 case '$': /* pid */
4889 case '!': /* last bg pid */
4890 case '?': /* last exit code */
4891 case '#': /* number of args */
4892 case '*': /* args */
4893 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02004894 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004895 goto make_one_char_var;
4896 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004897 char len_single_ch;
4898
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004899 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4900
Denys Vlasenko74369502010-05-21 19:52:01 +02004901 ch = i_getch(input); /* eat '{' */
4902 nommu_addchr(as_string, ch);
4903
Denys Vlasenko46e64982016-09-29 19:50:55 +02004904 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004905 /* It should be ${?}, or ${#var},
4906 * or even ${?+subst} - operator acting on a special variable,
4907 * or the beginning of variable name.
4908 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004909 if (ch == EOF
4910 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4911 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004912 bad_dollar_syntax:
4913 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004914 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4915 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004916 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004917 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004918 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004919 ch |= quote_mask;
4920
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004921 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004922 * However, this regresses some of our testsuite cases
4923 * which check invalid constructs like ${%}.
4924 * Oh well... let's check that the var name part is fine... */
4925
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004926 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004927 unsigned pos;
4928
Denys Vlasenko74369502010-05-21 19:52:01 +02004929 o_addchr(dest, ch);
4930 debug_printf_parse(": '%c'\n", ch);
4931
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004932 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004933 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004934 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004935 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004936
Denys Vlasenko74369502010-05-21 19:52:01 +02004937 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004938 unsigned end_ch;
4939 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004940 /* handle parameter expansions
4941 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4942 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004943 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4944 if (len_single_ch != '#'
4945 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4946 || i_peek(input) != '}'
4947 ) {
4948 goto bad_dollar_syntax;
4949 }
4950 /* else: it's "length of C" ${#C} op,
4951 * where C is a single char
4952 * special var name, e.g. ${#!}.
4953 */
4954 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004955 /* Eat everything until closing '}' (or ':') */
4956 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004957 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004958 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004959 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004960 ) {
4961 /* It's ${var:N[:M]} thing */
4962 end_ch = '}' * 0x100 + ':';
4963 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004964 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004965 && ch == '/'
4966 ) {
4967 /* It's ${var/[/]pattern[/repl]} thing */
4968 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4969 i_getch(input);
4970 nommu_addchr(as_string, '/');
4971 ch = '\\';
4972 }
4973 end_ch = '}' * 0x100 + '/';
4974 }
4975 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02004976 /* The pattern can't be empty.
4977 * IOW: if the first char after "${v//" is a slash,
4978 * it does not terminate the pattern - it's the first char of the pattern:
4979 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4980 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4981 */
4982 if (i_peek(input) == '/') {
4983 o_addchr(dest, i_getch(input));
4984 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004985 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004986 if (!BB_MMU)
4987 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004988#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004989 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004990 if (last_ch == 0) /* error? */
4991 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004992#else
4993#error Simple code to only allow ${var} is not implemented
4994#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004995 if (as_string) {
4996 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004997 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004998 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004999
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005000 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5001 && (end_ch & 0xff00)
5002 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005003 /* close the first block: */
5004 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005005 /* while parsing N from ${var:N[:M]}
5006 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005007 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005008 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005009 end_ch = '}';
5010 goto again;
5011 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005012 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005013 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005014 /* it's ${var:N} - emulate :999999999 */
5015 o_addstr(dest, "999999999");
5016 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005017 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005018 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005019 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005020 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005021 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005022 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5023 break;
5024 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005025#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005026 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005027 unsigned pos;
5028
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005029 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005030 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005031# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005032 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005033 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005034 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005035 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5036 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005037 if (!BB_MMU)
5038 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005039 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5040 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005041 if (as_string) {
5042 o_addstr(as_string, dest->data + pos);
5043 o_addchr(as_string, ')');
5044 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005045 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005046 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005047 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005048 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005049# endif
5050# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005051 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5052 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005053 if (!BB_MMU)
5054 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005055 if (!add_till_closing_bracket(dest, input, ')'))
5056 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005057 if (as_string) {
5058 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005059 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005060 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005061 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005062# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005063 break;
5064 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005065#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005066 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005067 goto make_var;
5068#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005069 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005070 /* $_ Shell or shell script name; or last argument of last command
5071 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5072 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005073 ch = i_getch(input);
5074 nommu_addchr(as_string, ch);
5075 ch = i_peek_and_eat_bkslash_nl(input);
5076 if (isalnum(ch)) { /* it's $_name or $_123 */
5077 ch = '_';
5078 goto make_var1;
5079 }
5080 /* else: it's $_ */
5081#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005082 default:
5083 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005084 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005085 debug_printf_parse("parse_dollar return 1 (ok)\n");
5086 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005087#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005088}
5089
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005090#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005091#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005092 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005093#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005094#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005095static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005096 o_string *dest,
5097 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005098 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005099{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005100 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005101 int next;
5102
5103 again:
5104 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005105 if (ch != EOF)
5106 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005107 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005108 debug_printf_parse("encode_string return 1 (ok)\n");
5109 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005110 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005111 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005112 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005113 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005114 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005115 }
5116 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005117 if (ch != '\n') {
5118 next = i_peek(input);
5119 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005120 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005121 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005122 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005123 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005124 /* Testcase: in interactive shell a file with
5125 * echo "unterminated string\<eof>
5126 * is sourced.
5127 */
5128 syntax_error_unterm_ch('"');
5129 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005130 }
5131 /* bash:
5132 * "The backslash retains its special meaning [in "..."]
5133 * only when followed by one of the following characters:
5134 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005135 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005136 * NB: in (unquoted) heredoc, above does not apply to ",
5137 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005138 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005139 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005140 ch = i_getch(input); /* eat next */
5141 if (ch == '\n')
5142 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005143 } /* else: ch remains == '\\', and we double it below: */
5144 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005145 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005146 goto again;
5147 }
5148 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005149 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5150 debug_printf_parse("encode_string return 0: "
5151 "parse_dollar returned 0 (error)\n");
5152 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005153 }
5154 goto again;
5155 }
5156#if ENABLE_HUSH_TICK
5157 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005158 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005159 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5160 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005161 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5162 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005163 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5164 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005165 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005166 }
5167#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005168 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005169 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005170#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005171}
5172
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005173/*
5174 * Scan input until EOF or end_trigger char.
5175 * Return a list of pipes to execute, or NULL on EOF
5176 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005177 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005178 * reset parsing machinery and start parsing anew,
5179 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005180 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005181static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005182 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005183 struct in_str *input,
5184 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005185{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005186 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005187 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005188
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005189 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005190 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005191 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005192 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005193 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005194 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005195
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005196 initialize_context(&ctx);
5197
5198 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5199 * Preventing this:
5200 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005201 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005202
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005203 /* We used to separate words on $IFS here. This was wrong.
5204 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005205 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005206 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005207
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005208 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005209 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005210 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005211 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005212 int ch;
5213 int next;
5214 int redir_fd;
5215 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005216
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005217 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005218 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005219 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005220 if (ch == EOF) {
5221 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005222
5223 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005224 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005225 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005226 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005227 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005228 syntax_error_unterm_ch('(');
5229 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005230 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005231 if (end_trigger == '}') {
5232 syntax_error_unterm_ch('{');
5233 goto parse_error;
5234 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005235
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005236 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005237 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005238 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005239 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005240 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005241 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005242 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005243 /* (this makes bare "&" cmd a no-op.
5244 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005245 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005246 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005247 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005248 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005249 pi = NULL;
5250 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005251#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005252 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005253 if (pstring)
5254 *pstring = ctx.as_string.data;
5255 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005256 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005257#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005258 // heredoc_cnt must be 0 here anyway
5259 //if (heredoc_cnt_ptr)
5260 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005261 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005262 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005263 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005264 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005265 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005266
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005267 /* Handle "'" and "\" first, as they won't play nice with
5268 * i_peek_and_eat_bkslash_nl() anyway:
5269 * echo z\\
5270 * and
5271 * echo '\
5272 * '
5273 * would break.
5274 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005275 if (ch == '\\') {
5276 ch = i_getch(input);
5277 if (ch == '\n')
5278 continue; /* drop \<newline>, get next char */
5279 nommu_addchr(&ctx.as_string, '\\');
5280 o_addchr(&ctx.word, '\\');
5281 if (ch == EOF) {
5282 /* Testcase: eval 'echo Ok\' */
5283 /* bash-4.3.43 was removing backslash,
5284 * but 4.4.19 retains it, most other shells too
5285 */
5286 continue; /* get next char */
5287 }
5288 /* Example: echo Hello \2>file
5289 * we need to know that word 2 is quoted
5290 */
5291 ctx.word.has_quoted_part = 1;
5292 nommu_addchr(&ctx.as_string, ch);
5293 o_addchr(&ctx.word, ch);
5294 continue; /* get next char */
5295 }
5296 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005297 if (ch == '\'') {
5298 ctx.word.has_quoted_part = 1;
5299 next = i_getch(input);
5300 if (next == '\'' && !ctx.pending_redirect)
5301 goto insert_empty_quoted_str_marker;
5302
5303 ch = next;
5304 while (1) {
5305 if (ch == EOF) {
5306 syntax_error_unterm_ch('\'');
5307 goto parse_error;
5308 }
5309 nommu_addchr(&ctx.as_string, ch);
5310 if (ch == '\'')
5311 break;
5312 if (ch == SPECIAL_VAR_SYMBOL) {
5313 /* Convert raw ^C to corresponding special variable reference */
5314 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5315 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5316 }
5317 o_addqchr(&ctx.word, ch);
5318 ch = i_getch(input);
5319 }
5320 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005321 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005322
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005323 next = '\0';
5324 if (ch != '\n')
5325 next = i_peek_and_eat_bkslash_nl(input);
5326
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005327 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005328 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005329 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005330 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005331 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005332 || ctx.word.length /* word{... - non-special */
5333 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005334 || (next != ';' /* }; - special */
5335 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005336 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005337 && next != '&' /* }& and }&& ... - special */
5338 && next != '|' /* }|| ... - special */
5339 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005340 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005341 ) {
5342 /* They are not special, skip "{}" */
5343 is_special += 2;
5344 }
5345 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005346 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005347
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005348 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005349 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005350 o_addQchr(&ctx.word, ch);
5351 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5352 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005353 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005354 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005355 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005356 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5357 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005358 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005359 continue;
5360 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005361
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005362 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005363#if ENABLE_HUSH_LINENO_VAR
5364/* Case:
5365 * "while ...; do<whitespace><newline>
5366 * cmd ..."
5367 * would think that "cmd" starts in <whitespace> -
5368 * i.e., at the previous line.
5369 * We need to skip all whitespace before newlines.
5370 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005371 while (ch != '\n') {
5372 next = i_peek(input);
5373 if (next != ' ' && next != '\t' && next != '\n')
5374 break; /* next char is not ws */
5375 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005376 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005377 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005378#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005379 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005380 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005381 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005382 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005383 /* Is this a case when newline is simply ignored?
5384 * Some examples:
5385 * "cmd | <newline> cmd ..."
5386 * "case ... in <newline> word) ..."
5387 */
5388 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005389 && ctx.word.length == 0
5390 && !ctx.word.has_quoted_part
5391 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005392 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005393 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005394 * Without check #1, interactive shell
5395 * ignores even bare <newline>,
5396 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005397 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005398 * ps2> _ <=== wrong, should be ps1
5399 * Without check #2, "cmd & <newline>"
5400 * is similarly mistreated.
5401 * (BTW, this makes "cmd & cmd"
5402 * and "cmd && cmd" non-orthogonal.
5403 * Really, ask yourself, why
5404 * "cmd && <newline>" doesn't start
5405 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005406 * The only reason is that it might be
5407 * a "cmd1 && <nl> cmd2 &" construct,
5408 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005409 */
5410 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005411 if (pi->num_cmds != 0 /* check #1 */
5412 && pi->followup != PIPE_BG /* check #2 */
5413 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005414 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005415 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005416 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005417 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005418 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005419 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005420 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005421 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5422 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005423 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005424 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005425 ctx.is_assignment = MAYBE_ASSIGNMENT;
5426 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005427 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005428 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005429 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005430 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005431 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005432
5433 /* "cmd}" or "cmd }..." without semicolon or &:
5434 * } is an ordinary char in this case, even inside { cmd; }
5435 * Pathological example: { ""}; } should exec "}" cmd
5436 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005437 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005438 if (ctx.word.length != 0 /* word} */
5439 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005440 ) {
5441 goto ordinary_char;
5442 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005443 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5444 /* Generally, there should be semicolon: "cmd; }"
5445 * However, bash allows to omit it if "cmd" is
5446 * a group. Examples:
5447 * { { echo 1; } }
5448 * {(echo 1)}
5449 * { echo 0 >&2 | { echo 1; } }
5450 * { while false; do :; done }
5451 * { case a in b) ;; esac }
5452 */
5453 if (ctx.command->group)
5454 goto term_group;
5455 goto ordinary_char;
5456 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005457 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005458 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005459 goto skip_end_trigger;
5460 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005461 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005462 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005463 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005464 && (ch != ';' || heredoc_cnt == 0)
5465#if ENABLE_HUSH_CASE
5466 && (ch != ')'
5467 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005468 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005469 )
5470#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005471 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005472 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005473 goto parse_error;
5474 }
5475 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005476 ctx.is_assignment = MAYBE_ASSIGNMENT;
5477 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005478 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005479 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005480 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005481 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005482 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005483#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005484 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005485 if (pstring)
5486 *pstring = ctx.as_string.data;
5487 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005488 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005489#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005490 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5491 /* Example: bare "{ }", "()" */
5492 G.last_exitcode = 2; /* bash compat */
5493 syntax_error_unexpected_ch(ch);
5494 goto parse_error2;
5495 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005496 if (heredoc_cnt_ptr)
5497 *heredoc_cnt_ptr = heredoc_cnt;
5498 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005499 debug_printf_parse("parse_stream return %p: "
5500 "end_trigger char found\n",
5501 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005502 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005503 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005504 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005505 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005506
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005507 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005508 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005509
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005510 /* Catch <, > before deciding whether this word is
5511 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5512 switch (ch) {
5513 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005514 redir_fd = redirect_opt_num(&ctx.word);
5515 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005516 goto parse_error;
5517 }
5518 redir_style = REDIRECT_OVERWRITE;
5519 if (next == '>') {
5520 redir_style = REDIRECT_APPEND;
5521 ch = i_getch(input);
5522 nommu_addchr(&ctx.as_string, ch);
5523 }
5524#if 0
5525 else if (next == '(') {
5526 syntax_error(">(process) not supported");
5527 goto parse_error;
5528 }
5529#endif
5530 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5531 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005532 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005533 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005534 redir_fd = redirect_opt_num(&ctx.word);
5535 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005536 goto parse_error;
5537 }
5538 redir_style = REDIRECT_INPUT;
5539 if (next == '<') {
5540 redir_style = REDIRECT_HEREDOC;
5541 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005542 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005543 ch = i_getch(input);
5544 nommu_addchr(&ctx.as_string, ch);
5545 } else if (next == '>') {
5546 redir_style = REDIRECT_IO;
5547 ch = i_getch(input);
5548 nommu_addchr(&ctx.as_string, ch);
5549 }
5550#if 0
5551 else if (next == '(') {
5552 syntax_error("<(process) not supported");
5553 goto parse_error;
5554 }
5555#endif
5556 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5557 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005558 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005559 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005560 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005561 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005562 /* note: we do not add it to &ctx.as_string */
5563/* TODO: in bash:
5564 * comment inside $() goes to the next \n, even inside quoted string (!):
5565 * cmd "$(cmd2 #comment)" - syntax error
5566 * cmd "`cmd2 #comment`" - ok
5567 * We accept both (comment ends where command subst ends, in both cases).
5568 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005569 while (1) {
5570 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005571 if (ch == '\n') {
5572 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005573 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005574 }
5575 ch = i_getch(input);
5576 if (ch == EOF)
5577 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005578 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005579 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005580 }
5581 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005582 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005583 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005584
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005585 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005586 /* check that we are not in word in "a=1 2>word b=1": */
5587 && !ctx.pending_redirect
5588 ) {
5589 /* ch is a special char and thus this word
5590 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005591 ctx.is_assignment = NOT_ASSIGNMENT;
5592 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005593 }
5594
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005595 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5596
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005597 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005598 case SPECIAL_VAR_SYMBOL:
5599 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005600 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5601 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005602 /* fall through */
5603 case '#':
5604 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005605 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005606 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005607 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005608 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005609 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005610 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005611 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005612 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005613 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005614 case '"':
5615 ctx.word.has_quoted_part = 1;
5616 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005617 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005618 insert_empty_quoted_str_marker:
5619 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005620 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5621 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005622 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005623 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005624 if (ctx.is_assignment == NOT_ASSIGNMENT)
5625 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005626 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005627 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005628 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005629 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005630#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005631 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005632 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005633
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005634 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5635 o_addchr(&ctx.word, '`');
5636 USE_FOR_NOMMU(pos = ctx.word.length;)
5637 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005638 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005639# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005640 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005641 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005642# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005643 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5644 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005645 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005646 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005647#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005648 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005649#if ENABLE_HUSH_CASE
5650 case_semi:
5651#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005652 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005653 goto parse_error;
5654 }
5655 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005656#if ENABLE_HUSH_CASE
5657 /* Eat multiple semicolons, detect
5658 * whether it means something special */
5659 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005660 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005661 if (ch != ';')
5662 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005663 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005664 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005665 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005666 ctx.ctx_dsemicolon = 1;
5667 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005668 break;
5669 }
5670 }
5671#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005672 new_cmd:
5673 /* We just finished a cmd. New one may start
5674 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005675 ctx.is_assignment = MAYBE_ASSIGNMENT;
5676 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005677 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005678 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005679 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005680 goto parse_error;
5681 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005682 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005683 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005684 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005685 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005686 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005687 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005688 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005689 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005690 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005691 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005692 goto parse_error;
5693 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005694#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005695 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005696 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005697#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005698 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005699 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005700 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005701 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005702 } else {
5703 /* we could pick up a file descriptor choice here
5704 * with redirect_opt_num(), but bash doesn't do it.
5705 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005706 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005707 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005708 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005709 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005710#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005711 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005712 if (ctx.ctx_res_w == RES_MATCH
5713 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005714 && ctx.word.length == 0 /* not word(... */
5715 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005716 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005717 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005718 }
5719#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005720 /* fall through */
5721 case '{': {
5722 int n = parse_group(&ctx, input, ch);
5723 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005724 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005725 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005726 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5727 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005728 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005729 }
Eric Andersen25f27032001-04-26 23:22:31 +00005730 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005731#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005732 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005733 goto case_semi;
5734#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005735
Eric Andersen25f27032001-04-26 23:22:31 +00005736 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005737 /* proper use of this character is caught by end_trigger:
5738 * if we see {, we call parse_group(..., end_trigger='}')
5739 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005740 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005741 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005742 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005743 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005744 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005745 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005746 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005747 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005748
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005749 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005750 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005751 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005752 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005753 struct parse_context *pctx;
5754 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005755
5756 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005757 * Sample for finding leaks on syntax error recovery path.
5758 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005759 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005760 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005761 * while if (true | { true;}); then echo ok; fi; do break; done
5762 * 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 +00005763 */
5764 pctx = &ctx;
5765 do {
5766 /* Update pipe/command counts,
5767 * otherwise freeing may miss some */
5768 done_pipe(pctx, PIPE_SEQ);
5769 debug_printf_clean("freeing list %p from ctx %p\n",
5770 pctx->list_head, pctx);
5771 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005772 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005773 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005774#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005775 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005776#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005777 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005778 if (pctx != &ctx) {
5779 free(pctx);
5780 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005781 IF_HAS_KEYWORDS(pctx = p2;)
5782 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005783
Denys Vlasenko474cb202018-07-24 13:03:03 +02005784 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005785#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005786 if (pstring)
5787 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005788#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005789 debug_leave();
5790 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005791 }
Eric Andersen25f27032001-04-26 23:22:31 +00005792}
5793
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005794
5795/*** Execution routines ***/
5796
5797/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005798#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005799#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005800 expand_string_to_string(str)
5801#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005802static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005803#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005804static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005805#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005806static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005807
5808/* expand_strvec_to_strvec() takes a list of strings, expands
5809 * all variable references within and returns a pointer to
5810 * a list of expanded strings, possibly with larger number
5811 * of strings. (Think VAR="a b"; echo $VAR).
5812 * This new list is allocated as a single malloc block.
5813 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005814 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005815 * Caller can deallocate entire list by single free(list). */
5816
Denys Vlasenko238081f2010-10-03 14:26:26 +02005817/* A horde of its helpers come first: */
5818
5819static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5820{
5821 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005822 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005823
Denys Vlasenko9e800222010-10-03 14:28:04 +02005824#if ENABLE_HUSH_BRACE_EXPANSION
5825 if (c == '{' || c == '}') {
5826 /* { -> \{, } -> \} */
5827 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005828 /* And now we want to add { or } and continue:
5829 * o_addchr(o, c);
5830 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005831 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005832 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005833 }
5834#endif
5835 o_addchr(o, c);
5836 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005837 /* \z -> \\\z; \<eol> -> \\<eol> */
5838 o_addchr(o, '\\');
5839 if (len) {
5840 len--;
5841 o_addchr(o, '\\');
5842 o_addchr(o, *str++);
5843 }
5844 }
5845 }
5846}
5847
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005848/* Store given string, finalizing the word and starting new one whenever
5849 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005850 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005851 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005852 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5853 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005854static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005855{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005856 int last_is_ifs = 0;
5857
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005858 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005859 int word_len;
5860
5861 if (!*str) /* EOL - do not finalize word */
5862 break;
5863 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005864 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005865 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005866 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005867 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005868 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005869 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005870 * Example: "v='\*'; echo b$v" prints "b\*"
5871 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005872 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005873 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005874 /*/ Why can't we do it easier? */
5875 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5876 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5877 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005878 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005879 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005880 if (!*str) /* EOL - do not finalize word */
5881 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005882 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005883
5884 /* We know str here points to at least one IFS char */
5885 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005886 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005887 if (!*str) /* EOL - do not finalize word */
5888 break;
5889
Denys Vlasenko96786362018-04-11 16:02:58 +02005890 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5891 && strchr(G.ifs, *str) /* the second check would fail */
5892 ) {
5893 /* This is a non-whitespace $IFS char */
5894 /* Skip it and IFS whitespace chars, start new word */
5895 str++;
5896 str += strspn(str, G.ifs_whitespace);
5897 goto new_word;
5898 }
5899
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005900 /* Start new word... but not always! */
5901 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005902 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005903 /*
5904 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005905 * here nothing precedes the space in $v expansion,
5906 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005907 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005908 * It's okay if this accesses the byte before first argv[]:
5909 * past call to o_save_ptr() cleared it to zero byte
5910 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005911 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005912 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005913 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005914 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005915 o_addchr(output, '\0');
5916 debug_print_list("expand_on_ifs", output, n);
5917 n = o_save_ptr(output, n);
5918 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005919 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005920
Denys Vlasenko168579a2018-07-19 13:45:54 +02005921 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005922 debug_print_list("expand_on_ifs[1]", output, n);
5923 return n;
5924}
5925
5926/* Helper to expand $((...)) and heredoc body. These act as if
5927 * they are in double quotes, with the exception that they are not :).
5928 * Just the rules are similar: "expand only $var and `cmd`"
5929 *
5930 * Returns malloced string.
5931 * As an optimization, we return NULL if expansion is not needed.
5932 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005933static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005934{
5935 char *exp_str;
5936 struct in_str input;
5937 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005938 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005939
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005940 cp = str;
5941 for (;;) {
5942 if (!*cp) return NULL; /* string has no special chars */
5943 if (*cp == '$') break;
5944 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005945#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005946 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005947#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005948 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005949 }
5950
5951 /* We need to expand. Example:
5952 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5953 */
5954 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005955 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005956//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005957 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005958 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005959 EXP_FLAG_ESC_GLOB_CHARS,
5960 /*unbackslash:*/ 1
5961 );
5962 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005963 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005964 return exp_str;
5965}
5966
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005967static const char *first_special_char_in_vararg(const char *cp)
5968{
5969 for (;;) {
5970 if (!*cp) return NULL; /* string has no special chars */
5971 if (*cp == '$') return cp;
5972 if (*cp == '\\') return cp;
5973 if (*cp == '\'') return cp;
5974 if (*cp == '"') return cp;
5975#if ENABLE_HUSH_TICK
5976 if (*cp == '`') return cp;
5977#endif
5978 /* dquoted "${x:+ARG}" should not glob, therefore
5979 * '*' et al require some non-literal processing: */
5980 if (*cp == '*') return cp;
5981 if (*cp == '?') return cp;
5982 if (*cp == '[') return cp;
5983 cp++;
5984 }
5985}
5986
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005987/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5988 * These can contain single- and double-quoted strings,
5989 * and treated as if the ARG string is initially unquoted. IOW:
5990 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5991 * a dquoted string: "${var#"zz"}"), the difference only comes later
5992 * (word splitting and globbing of the ${var...} result).
5993 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005994#if !BASH_PATTERN_SUBST
5995#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5996 encode_then_expand_vararg(str, handle_squotes)
5997#endif
5998static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5999{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006000#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006001 const int do_unbackslash = 0;
6002#endif
6003 char *exp_str;
6004 struct in_str input;
6005 o_string dest = NULL_O_STRING;
6006
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006007 if (!first_special_char_in_vararg(str)) {
6008 /* string has no special chars */
6009 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006010 }
6011
Denys Vlasenkob762c782018-07-17 14:21:38 +02006012 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006013 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006014 exp_str = NULL;
6015
6016 for (;;) {
6017 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006018
6019 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006020 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6021 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006022
6023 if (!dest.o_expflags) {
6024 if (ch == EOF)
6025 break;
6026 if (handle_squotes && ch == '\'') {
6027 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006028 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006029 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006030 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006031 }
6032 if (ch == EOF) {
6033 syntax_error_unterm_ch('"');
6034 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006035 }
6036 if (ch == '"') {
6037 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6038 continue;
6039 }
6040 if (ch == '\\') {
6041 ch = i_getch(&input);
6042 if (ch == EOF) {
6043//example? error message? syntax_error_unterm_ch('"');
6044 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6045 goto ret;
6046 }
6047 o_addqchr(&dest, ch);
6048 continue;
6049 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006050 if (ch == '$') {
6051 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6052 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6053 goto ret;
6054 }
6055 continue;
6056 }
6057#if ENABLE_HUSH_TICK
6058 if (ch == '`') {
6059 //unsigned pos = dest->length;
6060 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6061 o_addchr(&dest, 0x80 | '`');
6062 if (!add_till_backquote(&dest, &input,
6063 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6064 )
6065 ) {
6066 goto ret; /* error */
6067 }
6068 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6069 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6070 continue;
6071 }
6072#endif
6073 o_addQchr(&dest, ch);
6074 } /* for (;;) */
6075
6076 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6077 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006078 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6079 do_unbackslash
6080 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006081 ret:
6082 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006083 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006084 return exp_str;
6085}
6086
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006087/* Expanding ARG in ${var+ARG}, ${var-ARG}
6088 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006089static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006090 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006091{
6092 struct in_str input;
6093 o_string dest = NULL_O_STRING;
6094
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006095 if (!first_special_char_in_vararg(str)
6096 && '\0' == str[strcspn(str, G.ifs)]
6097 ) {
6098 /* string has no special chars
6099 * && string has no $IFS chars
6100 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006101 if (dquoted) {
6102 /* Prints 1 (quoted expansion is a "" word, not nothing):
6103 * set -- "${notexist-}"; echo $#
6104 */
6105 output->has_quoted_part = 1;
6106 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006107 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006108 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006109
Denys Vlasenko294eb462018-07-20 16:18:59 +02006110 setup_string_in_str(&input, str);
6111
6112 for (;;) {
6113 int ch;
6114
6115 ch = i_getch(&input);
6116 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6117 __func__, ch, ch, dest.o_expflags);
6118
6119 if (!dest.o_expflags) {
6120 if (ch == EOF)
6121 break;
6122 if (!dquoted && strchr(G.ifs, ch)) {
6123 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6124 * do not assume we are at the start of the word (PREFIX above).
6125 */
6126 if (dest.data) {
6127 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006128 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006129 o_addchr(output, '\0');
6130 n = o_save_ptr(output, n); /* create next word */
6131 } else
6132 if (output->length != o_get_last_ptr(output, n)
6133 || output->has_quoted_part
6134 ) {
6135 /* For these cases:
6136 * f() { for i; do echo "|$i|"; done; }; x=x
6137 * f a${x:+ }b # 1st condition
6138 * |a|
6139 * |b|
6140 * f ""${x:+ }b # 2nd condition
6141 * ||
6142 * |b|
6143 */
6144 o_addchr(output, '\0');
6145 n = o_save_ptr(output, n); /* create next word */
6146 }
6147 continue;
6148 }
6149 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006150 if (!add_till_single_quote_dquoted(&dest, &input))
6151 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006152 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6153 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006154 continue;
6155 }
6156 }
6157 if (ch == EOF) {
6158 syntax_error_unterm_ch('"');
6159 goto ret; /* error */
6160 }
6161 if (ch == '"') {
6162 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006163 if (dest.o_expflags) {
6164 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6165 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6166 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006167 continue;
6168 }
6169 if (ch == '\\') {
6170 ch = i_getch(&input);
6171 if (ch == EOF) {
6172//example? error message? syntax_error_unterm_ch('"');
6173 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6174 goto ret;
6175 }
6176 o_addqchr(&dest, ch);
6177 continue;
6178 }
6179 if (ch == '$') {
6180 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6181 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6182 goto ret;
6183 }
6184 continue;
6185 }
6186#if ENABLE_HUSH_TICK
6187 if (ch == '`') {
6188 //unsigned pos = dest->length;
6189 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6190 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6191 if (!add_till_backquote(&dest, &input,
6192 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6193 )
6194 ) {
6195 goto ret; /* error */
6196 }
6197 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6198 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6199 continue;
6200 }
6201#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006202 if (dquoted) {
6203 /* Always glob-protect if in dquotes:
6204 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6205 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6206 */
6207 o_addqchr(&dest, ch);
6208 } else {
6209 /* Glob-protect only if char is quoted:
6210 * x=x; echo ${x:+/bin/c*} - prints many filenames
6211 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6212 */
6213 o_addQchr(&dest, ch);
6214 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006215 } /* for (;;) */
6216
6217 if (dest.data) {
6218 n = expand_vars_to_list(output, n, dest.data);
6219 }
6220 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006221 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006222 return n;
6223}
6224
Denys Vlasenko0b883582016-12-23 16:49:07 +01006225#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006226static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006227{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006228 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006229 arith_t res;
6230 char *exp_str;
6231
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006232 math_state.lookupvar = get_local_var_value;
6233 math_state.setvar = set_local_var_from_halves;
6234 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006235 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006236 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006237 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006238 if (errmsg_p)
6239 *errmsg_p = math_state.errmsg;
6240 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006241 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006242 return res;
6243}
6244#endif
6245
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006246#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006247/* ${var/[/]pattern[/repl]} helpers */
6248static char *strstr_pattern(char *val, const char *pattern, int *size)
6249{
6250 while (1) {
6251 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6252 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6253 if (end) {
6254 *size = end - val;
6255 return val;
6256 }
6257 if (*val == '\0')
6258 return NULL;
6259 /* Optimization: if "*pat" did not match the start of "string",
6260 * we know that "tring", "ring" etc will not match too:
6261 */
6262 if (pattern[0] == '*')
6263 return NULL;
6264 val++;
6265 }
6266}
6267static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6268{
6269 char *result = NULL;
6270 unsigned res_len = 0;
6271 unsigned repl_len = strlen(repl);
6272
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006273 /* Null pattern never matches, including if "var" is empty */
6274 if (!pattern[0])
6275 return result; /* NULL, no replaces happened */
6276
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006277 while (1) {
6278 int size;
6279 char *s = strstr_pattern(val, pattern, &size);
6280 if (!s)
6281 break;
6282
6283 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006284 strcpy(mempcpy(result + res_len, val, s - val), repl);
6285 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006286 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6287
6288 val = s + size;
6289 if (exp_op == '/')
6290 break;
6291 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006292 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006293 result = xrealloc(result, res_len + strlen(val) + 1);
6294 strcpy(result + res_len, val);
6295 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6296 }
6297 debug_printf_varexp("result:'%s'\n", result);
6298 return result;
6299}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006300#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006301
Denys Vlasenko168579a2018-07-19 13:45:54 +02006302static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006303 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006304{
6305 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6306 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6307 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6308 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006309 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006310 } else { /* quoted "$VAR" */
6311 output->has_quoted_part = 1;
6312 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6313 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6314 if (val && val[0])
6315 o_addQstr(output, val);
6316 }
6317 return n;
6318}
6319
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006320/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006321 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006322static NOINLINE int expand_one_var(o_string *output, int n,
6323 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006325 const char *val;
6326 char *to_be_freed;
6327 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006328 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006329 char exp_op;
6330 char exp_save = exp_save; /* for compiler */
6331 char *exp_saveptr; /* points to expansion operator */
6332 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006333 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006334
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006335 val = NULL;
6336 to_be_freed = NULL;
6337 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006338 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006339 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006340 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006341 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006342 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343 exp_op = 0;
6344
Denys Vlasenkob762c782018-07-17 14:21:38 +02006345 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006346 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6347 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6348 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006349 ) {
6350 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006351 var++;
6352 exp_op = 'L';
6353 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006354 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006356 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006357 ) {
6358 /* ${?:0}, ${#[:]%0} etc */
6359 exp_saveptr = var + 1;
6360 } else {
6361 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6362 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6363 }
6364 exp_op = exp_save = *exp_saveptr;
6365 if (exp_op) {
6366 exp_word = exp_saveptr + 1;
6367 if (exp_op == ':') {
6368 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006369//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006370 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006371 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006372 ) {
6373 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6374 exp_op = ':';
6375 exp_word--;
6376 }
6377 }
6378 *exp_saveptr = '\0';
6379 } /* else: it's not an expansion op, but bare ${var} */
6380 }
6381
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006382 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006383 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006384 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006385 int nn = xatoi_positive(var);
6386 if (nn < G.global_argc)
6387 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006388 /* else val remains NULL: $N with too big N */
6389 } else {
6390 switch (var[0]) {
6391 case '$': /* pid */
6392 val = utoa(G.root_pid);
6393 break;
6394 case '!': /* bg pid */
6395 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6396 break;
6397 case '?': /* exitcode */
6398 val = utoa(G.last_exitcode);
6399 break;
6400 case '#': /* argc */
6401 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6402 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006403 case '-': { /* active options */
6404 /* Check set_mode() to see what option chars we support */
6405 char *cp;
6406 val = cp = G.optstring_buf;
6407 if (G.o_opt[OPT_O_ERREXIT])
6408 *cp++ = 'e';
6409 if (G_interactive_fd)
6410 *cp++ = 'i';
6411 if (G_x_mode)
6412 *cp++ = 'x';
6413 /* If G.o_opt[OPT_O_NOEXEC] is true,
6414 * commands read but are not executed,
6415 * so $- can not execute too, 'n' is never seen in $-.
6416 */
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006417 if (G.opt_s)
6418 *cp++ = 's';
Denys Vlasenko76a4e832019-05-19 18:24:52 +02006419//TODO: show 'c' if executed via "hush -c 'CMDS'" (bash only, not ash)
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006420 *cp = '\0';
6421 break;
6422 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006423 default:
6424 val = get_local_var_value(var);
6425 }
6426 }
6427
6428 /* Handle any expansions */
6429 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006430 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006431 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006432 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006433 debug_printf_expand("%s\n", val);
6434 } else if (exp_op) {
6435 if (exp_op == '%' || exp_op == '#') {
6436 /* Standard-mandated substring removal ops:
6437 * ${parameter%word} - remove smallest suffix pattern
6438 * ${parameter%%word} - remove largest suffix pattern
6439 * ${parameter#word} - remove smallest prefix pattern
6440 * ${parameter##word} - remove largest prefix pattern
6441 *
6442 * Word is expanded to produce a glob pattern.
6443 * Then var's value is matched to it and matching part removed.
6444 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006445//FIXME: ${x#...${...}...}
6446//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6447//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006448 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006449 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006450 char *exp_exp_word;
6451 char *loc;
6452 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006453 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006454 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006455 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006456 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006457 if (exp_exp_word)
6458 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006459 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6460 /*
6461 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006462 * G.global_argv and results of utoa and get_local_var_value
6463 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006464 * scan_and_match momentarily stores NULs there.
6465 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006466 t = (char*)val;
6467 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006468 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 +02006469 free(exp_exp_word);
6470 if (loc) { /* match was found */
6471 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006472 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006473 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006474 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475 }
6476 }
6477 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006478#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006479 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006480 /* It's ${var/[/]pattern[/repl]} thing.
6481 * Note that in encoded form it has TWO parts:
6482 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006483 * and if // is used, it is encoded as \:
6484 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006485 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006486 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006487 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006488 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006489 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006490 * >az >bz
6491 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6492 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6493 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6494 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006495 * (note that a*z _pattern_ is never globbed!)
6496 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006498 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006499 if (!pattern)
6500 pattern = xstrdup(exp_word);
6501 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6502 *p++ = SPECIAL_VAR_SYMBOL;
6503 exp_word = p;
6504 p = strchr(p, SPECIAL_VAR_SYMBOL);
6505 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006506 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006507 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6508 /* HACK ALERT. We depend here on the fact that
6509 * G.global_argv and results of utoa and get_local_var_value
6510 * are actually in writable memory:
6511 * replace_pattern momentarily stores NULs there. */
6512 t = (char*)val;
6513 to_be_freed = replace_pattern(t,
6514 pattern,
6515 (repl ? repl : exp_word),
6516 exp_op);
6517 if (to_be_freed) /* at least one replace happened */
6518 val = to_be_freed;
6519 free(pattern);
6520 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006521 } else {
6522 /* Empty variable always gives nothing */
6523 // "v=''; echo ${v/*/w}" prints "", not "w"
6524 /* Just skip "replace" part */
6525 *p++ = SPECIAL_VAR_SYMBOL;
6526 p = strchr(p, SPECIAL_VAR_SYMBOL);
6527 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006528 }
6529 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006530#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006531 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006532#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533 /* It's ${var:N[:M]} bashism.
6534 * Note that in encoded form it has TWO parts:
6535 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6536 */
6537 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006538 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006539
Denys Vlasenko063847d2010-09-15 13:33:02 +02006540 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6541 if (errmsg)
6542 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006543 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6544 *p++ = SPECIAL_VAR_SYMBOL;
6545 exp_word = p;
6546 p = strchr(p, SPECIAL_VAR_SYMBOL);
6547 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006548 len = expand_and_evaluate_arith(exp_word, &errmsg);
6549 if (errmsg)
6550 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006552 if (beg < 0) {
6553 /* negative beg counts from the end */
6554 beg = (arith_t)strlen(val) + beg;
6555 if (beg < 0) /* ${v: -999999} is "" */
6556 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006557 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006558 debug_printf_varexp("from val:'%s'\n", val);
6559 if (len < 0) {
6560 /* in bash, len=-n means strlen()-n */
6561 len = (arith_t)strlen(val) - beg + len;
6562 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006563 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006564 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006565 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006566 arith_err:
6567 val = NULL;
6568 } else {
6569 /* Paranoia. What if user entered 9999999999999
6570 * which fits in arith_t but not int? */
6571 if (len >= INT_MAX)
6572 len = INT_MAX;
6573 val = to_be_freed = xstrndup(val + beg, len);
6574 }
6575 debug_printf_varexp("val:'%s'\n", val);
6576#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006577 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006578 val = NULL;
6579#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006580 } else { /* one of "-=+?" */
6581 /* Standard-mandated substitution ops:
6582 * ${var?word} - indicate error if unset
6583 * If var is unset, word (or a message indicating it is unset
6584 * if word is null) is written to standard error
6585 * and the shell exits with a non-zero exit status.
6586 * Otherwise, the value of var is substituted.
6587 * ${var-word} - use default value
6588 * If var is unset, word is substituted.
6589 * ${var=word} - assign and use default value
6590 * If var is unset, word is assigned to var.
6591 * In all cases, final value of var is substituted.
6592 * ${var+word} - use alternative value
6593 * If var is unset, null is substituted.
6594 * Otherwise, word is substituted.
6595 *
6596 * Word is subjected to tilde expansion, parameter expansion,
6597 * command substitution, and arithmetic expansion.
6598 * If word is not needed, it is not expanded.
6599 *
6600 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6601 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006602 *
6603 * Word-splitting and single quote behavior:
6604 *
6605 * $ f() { for i; do echo "|$i|"; done; };
6606 *
6607 * $ x=; f ${x:?'x y' z}
6608 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6609 * $ x=; f "${x:?'x y' z}"
6610 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6611 *
6612 * $ x=; f ${x:='x y' z}
6613 * |x|
6614 * |y|
6615 * |z|
6616 * $ x=; f "${x:='x y' z}"
6617 * |'x y' z|
6618 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006619 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006620 * |x y|
6621 * |z|
6622 * $ x=x; f "${x:+'x y' z}"
6623 * |'x y' z|
6624 *
6625 * $ x=; f ${x:-'x y' z}
6626 * |x y|
6627 * |z|
6628 * $ x=; f "${x:-'x y' z}"
6629 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006630 */
6631 int use_word = (!val || ((exp_save == ':') && !val[0]));
6632 if (exp_op == '+')
6633 use_word = !use_word;
6634 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6635 (exp_save == ':') ? "true" : "false", use_word);
6636 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006637 if (exp_op == '+' || exp_op == '-') {
6638 /* ${var+word} - use alternative value */
6639 /* ${var-word} - use default value */
6640 n = encode_then_append_var_plusminus(output, n, exp_word,
6641 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006642 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006643 val = NULL;
6644 } else {
6645 /* ${var?word} - indicate error if unset */
6646 /* ${var=word} - assign and use default value */
6647 to_be_freed = encode_then_expand_vararg(exp_word,
6648 /*handle_squotes:*/ !(arg0 & 0x80),
6649 /*unbackslash:*/ 0
6650 );
6651 if (to_be_freed)
6652 exp_word = to_be_freed;
6653 if (exp_op == '?') {
6654 /* mimic bash message */
6655 msg_and_die_if_script("%s: %s",
6656 var,
6657 exp_word[0]
6658 ? exp_word
6659 : "parameter null or not set"
6660 /* ash has more specific messages, a-la: */
6661 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6662 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006663//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006664//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006665// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6666// bash: x: x y z
6667// $
6668// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006669 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006670 val = exp_word;
6671 }
6672 if (exp_op == '=') {
6673 /* ${var=[word]} or ${var:=[word]} */
6674 if (isdigit(var[0]) || var[0] == '#') {
6675 /* mimic bash message */
6676 msg_and_die_if_script("$%s: cannot assign in this way", var);
6677 val = NULL;
6678 } else {
6679 char *new_var = xasprintf("%s=%s", var, val);
6680 set_local_var(new_var, /*flag:*/ 0);
6681 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006682 }
6683 }
6684 }
6685 } /* one of "-=+?" */
6686
6687 *exp_saveptr = exp_save;
6688 } /* if (exp_op) */
6689
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006690 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006691 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006692
Denys Vlasenko168579a2018-07-19 13:45:54 +02006693 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006694
6695 free(to_be_freed);
6696 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006697}
6698
6699/* Expand all variable references in given string, adding words to list[]
6700 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6701 * to be filled). This routine is extremely tricky: has to deal with
6702 * variables/parameters with whitespace, $* and $@, and constructs like
6703 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006704static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006705{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006706 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006707 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006708 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006709 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006710 char *p;
6711
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006712 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6713 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 debug_print_list("expand_vars_to_list[0]", output, n);
6715
6716 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6717 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006718#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006719 char arith_buf[sizeof(arith_t)*3 + 2];
6720#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006721
Denys Vlasenko168579a2018-07-19 13:45:54 +02006722 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006723 o_addchr(output, '\0');
6724 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006725 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006726 }
6727
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006728 o_addblock(output, arg, p - arg);
6729 debug_print_list("expand_vars_to_list[1]", output, n);
6730 arg = ++p;
6731 p = strchr(p, SPECIAL_VAR_SYMBOL);
6732
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006733 /* Fetch special var name (if it is indeed one of them)
6734 * and quote bit, force the bit on if singleword expansion -
6735 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006736 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006737
6738 /* Is this variable quoted and thus expansion can't be null?
6739 * "$@" is special. Even if quoted, it can still
6740 * expand to nothing (not even an empty string),
6741 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006743 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744
6745 switch (first_ch & 0x7f) {
6746 /* Highest bit in first_ch indicates that var is double-quoted */
6747 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006748 case '@': {
6749 int i;
6750 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006751 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006752 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006753 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006755 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006756 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006757 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6758 if (G.global_argv[i++][0] && G.global_argv[i]) {
6759 /* this argv[] is not empty and not last:
6760 * put terminating NUL, start new word */
6761 o_addchr(output, '\0');
6762 debug_print_list("expand_vars_to_list[2]", output, n);
6763 n = o_save_ptr(output, n);
6764 debug_print_list("expand_vars_to_list[3]", output, n);
6765 }
6766 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006767 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006768 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006770 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006771 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006772 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006773 while (1) {
6774 o_addQstr(output, G.global_argv[i]);
6775 if (++i >= G.global_argc)
6776 break;
6777 o_addchr(output, '\0');
6778 debug_print_list("expand_vars_to_list[4]", output, n);
6779 n = o_save_ptr(output, n);
6780 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006781 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006782 while (1) {
6783 o_addQstr(output, G.global_argv[i]);
6784 if (!G.global_argv[++i])
6785 break;
6786 if (G.ifs[0])
6787 o_addchr(output, G.ifs[0]);
6788 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006789 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006790 }
6791 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006792 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006793 case SPECIAL_VAR_SYMBOL: {
6794 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006796 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006797 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006798 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006800 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006801 case SPECIAL_VAR_QUOTED_SVS:
6802 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006803 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006804 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006805 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006806 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006807#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006808 case '`': {
6809 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006810 o_string subst_result = NULL_O_STRING;
6811
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006812 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006813 arg++;
6814 /* Can't just stuff it into output o_string,
6815 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006816 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006817 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6818 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006819 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006820 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006821 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006822 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006823 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006824 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006825#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006826#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006827 case '+': {
6828 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006829 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006830
6831 arg++; /* skip '+' */
6832 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6833 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006834 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006835 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6836 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006837 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006838 break;
6839 }
6840#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006841 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006842 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006843 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006844 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006845 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6846
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006847 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6848 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006849 if (*p != SPECIAL_VAR_SYMBOL)
6850 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006851 arg = ++p;
6852 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6853
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006854 if (*arg) {
6855 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006856 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006857 o_addchr(output, '\0');
6858 n = o_save_ptr(output, n);
6859 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006860 debug_print_list("expand_vars_to_list[a]", output, n);
6861 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006862 * if needed (much earlier), do not use o_addQstr here!
6863 */
6864 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006865 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006866 } else
6867 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006868 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6869 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006870 ) {
6871 n--;
6872 /* allow to reuse list[n] later without re-growth */
6873 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006874 }
6875
6876 return n;
6877}
6878
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006879static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006880{
6881 int n;
6882 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006883 o_string output = NULL_O_STRING;
6884
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006885 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006886
6887 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006888 for (;;) {
6889 /* go to next list[n] */
6890 output.ended_in_ifs = 0;
6891 n = o_save_ptr(&output, n);
6892
6893 if (!*argv)
6894 break;
6895
6896 /* expand argv[i] */
6897 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006898 /* if (!output->has_empty_slot) -- need this?? */
6899 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006900 }
6901 debug_print_list("expand_variables", &output, n);
6902
6903 /* output.data (malloced in one block) gets returned in "list" */
6904 list = o_finalize_list(&output, n);
6905 debug_print_strings("expand_variables[1]", list);
6906 return list;
6907}
6908
6909static char **expand_strvec_to_strvec(char **argv)
6910{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006911 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006912}
6913
Denys Vlasenko11752d42018-04-03 08:20:58 +02006914#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6916{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006917 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006918}
6919#endif
6920
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006921/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006922 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006923 *
6924 * NB: should NOT do globbing!
6925 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6926 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006927static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006928{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006929#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006930 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006931 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006932#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006933 char *argv[2], **list;
6934
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006935 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006936 /* This is generally an optimization, but it also
6937 * handles "", which otherwise trips over !list[0] check below.
6938 * (is this ever happens that we actually get str="" here?)
6939 */
6940 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6941 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006942 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006943 return xstrdup(str);
6944 }
6945
6946 argv[0] = (char*)str;
6947 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006948 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006949 if (!list[0]) {
6950 /* Example where it happens:
6951 * x=; echo ${x:-"$@"}
6952 */
6953 ((char*)list)[0] = '\0';
6954 } else {
6955 if (HUSH_DEBUG)
6956 if (list[1])
6957 bb_error_msg_and_die("BUG in varexp2");
6958 /* actually, just move string 2*sizeof(char*) bytes back */
6959 overlapping_strcpy((char*)list, list[0]);
6960 if (do_unbackslash)
6961 unbackslash((char*)list);
6962 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006963 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006964 return (char*)list;
6965}
6966
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006967#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006968static char* expand_strvec_to_string(char **argv)
6969{
6970 char **list;
6971
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006972 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006973 /* Convert all NULs to spaces */
6974 if (list[0]) {
6975 int n = 1;
6976 while (list[n]) {
6977 if (HUSH_DEBUG)
6978 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6979 bb_error_msg_and_die("BUG in varexp3");
6980 /* bash uses ' ' regardless of $IFS contents */
6981 list[n][-1] = ' ';
6982 n++;
6983 }
6984 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006985 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006986 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6987 return (char*)list;
6988}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006989#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006990
6991static char **expand_assignments(char **argv, int count)
6992{
6993 int i;
6994 char **p;
6995
6996 G.expanded_assignments = p = NULL;
6997 /* Expand assignments into one string each */
6998 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006999 p = add_string_to_strings(p,
7000 expand_string_to_string(argv[i],
7001 EXP_FLAG_ESC_GLOB_CHARS,
7002 /*unbackslash:*/ 1
7003 )
7004 );
7005 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007006 }
7007 G.expanded_assignments = NULL;
7008 return p;
7009}
7010
7011
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007012static void switch_off_special_sigs(unsigned mask)
7013{
7014 unsigned sig = 0;
7015 while ((mask >>= 1) != 0) {
7016 sig++;
7017 if (!(mask & 1))
7018 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007019#if ENABLE_HUSH_TRAP
7020 if (G_traps) {
7021 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007022 /* trap is '', has to remain SIG_IGN */
7023 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007024 free(G_traps[sig]);
7025 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007026 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007027#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007028 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007029 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007030 }
7031}
7032
Denys Vlasenkob347df92011-08-09 22:49:15 +02007033#if BB_MMU
7034/* never called */
7035void re_execute_shell(char ***to_free, const char *s,
7036 char *g_argv0, char **g_argv,
7037 char **builtin_argv) NORETURN;
7038
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007039static void reset_traps_to_defaults(void)
7040{
7041 /* This function is always called in a child shell
7042 * after fork (not vfork, NOMMU doesn't use this function).
7043 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007044 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007045 unsigned mask;
7046
7047 /* Child shells are not interactive.
7048 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7049 * Testcase: (while :; do :; done) + ^Z should background.
7050 * Same goes for SIGTERM, SIGHUP, SIGINT.
7051 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007052 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007053 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007054 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007055
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007056 /* Switch off special sigs */
7057 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007058# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007059 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007060# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007061 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007062 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7063 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007064
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007065# if ENABLE_HUSH_TRAP
7066 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007067 return;
7068
7069 /* Reset all sigs to default except ones with empty traps */
7070 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007071 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007072 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007073 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007074 continue; /* empty trap: has to remain SIG_IGN */
7075 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007076 free(G_traps[sig]);
7077 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007078 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079 if (sig == 0)
7080 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007081 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007082 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007083# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007084}
7085
7086#else /* !BB_MMU */
7087
7088static void re_execute_shell(char ***to_free, const char *s,
7089 char *g_argv0, char **g_argv,
7090 char **builtin_argv) NORETURN;
7091static void re_execute_shell(char ***to_free, const char *s,
7092 char *g_argv0, char **g_argv,
7093 char **builtin_argv)
7094{
7095# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7096 /* delims + 2 * (number of bytes in printed hex numbers) */
7097 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7098 char *heredoc_argv[4];
7099 struct variable *cur;
7100# if ENABLE_HUSH_FUNCTIONS
7101 struct function *funcp;
7102# endif
7103 char **argv, **pp;
7104 unsigned cnt;
7105 unsigned long long empty_trap_mask;
7106
7107 if (!g_argv0) { /* heredoc */
7108 argv = heredoc_argv;
7109 argv[0] = (char *) G.argv0_for_re_execing;
7110 argv[1] = (char *) "-<";
7111 argv[2] = (char *) s;
7112 argv[3] = NULL;
7113 pp = &argv[3]; /* used as pointer to empty environment */
7114 goto do_exec;
7115 }
7116
7117 cnt = 0;
7118 pp = builtin_argv;
7119 if (pp) while (*pp++)
7120 cnt++;
7121
7122 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007123 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007124 int sig;
7125 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007126 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007127 empty_trap_mask |= 1LL << sig;
7128 }
7129 }
7130
7131 sprintf(param_buf, NOMMU_HACK_FMT
7132 , (unsigned) G.root_pid
7133 , (unsigned) G.root_ppid
7134 , (unsigned) G.last_bg_pid
7135 , (unsigned) G.last_exitcode
7136 , cnt
7137 , empty_trap_mask
7138 IF_HUSH_LOOPS(, G.depth_of_loop)
7139 );
7140# undef NOMMU_HACK_FMT
7141 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7142 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7143 */
7144 cnt += 6;
7145 for (cur = G.top_var; cur; cur = cur->next) {
7146 if (!cur->flg_export || cur->flg_read_only)
7147 cnt += 2;
7148 }
7149# if ENABLE_HUSH_FUNCTIONS
7150 for (funcp = G.top_func; funcp; funcp = funcp->next)
7151 cnt += 3;
7152# endif
7153 pp = g_argv;
7154 while (*pp++)
7155 cnt++;
7156 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7157 *pp++ = (char *) G.argv0_for_re_execing;
7158 *pp++ = param_buf;
7159 for (cur = G.top_var; cur; cur = cur->next) {
7160 if (strcmp(cur->varstr, hush_version_str) == 0)
7161 continue;
7162 if (cur->flg_read_only) {
7163 *pp++ = (char *) "-R";
7164 *pp++ = cur->varstr;
7165 } else if (!cur->flg_export) {
7166 *pp++ = (char *) "-V";
7167 *pp++ = cur->varstr;
7168 }
7169 }
7170# if ENABLE_HUSH_FUNCTIONS
7171 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7172 *pp++ = (char *) "-F";
7173 *pp++ = funcp->name;
7174 *pp++ = funcp->body_as_string;
7175 }
7176# endif
7177 /* We can pass activated traps here. Say, -Tnn:trap_string
7178 *
7179 * However, POSIX says that subshells reset signals with traps
7180 * to SIG_DFL.
7181 * I tested bash-3.2 and it not only does that with true subshells
7182 * of the form ( list ), but with any forked children shells.
7183 * I set trap "echo W" WINCH; and then tried:
7184 *
7185 * { echo 1; sleep 20; echo 2; } &
7186 * while true; do echo 1; sleep 20; echo 2; break; done &
7187 * true | { echo 1; sleep 20; echo 2; } | cat
7188 *
7189 * In all these cases sending SIGWINCH to the child shell
7190 * did not run the trap. If I add trap "echo V" WINCH;
7191 * _inside_ group (just before echo 1), it works.
7192 *
7193 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007194 */
7195 *pp++ = (char *) "-c";
7196 *pp++ = (char *) s;
7197 if (builtin_argv) {
7198 while (*++builtin_argv)
7199 *pp++ = *builtin_argv;
7200 *pp++ = (char *) "";
7201 }
7202 *pp++ = g_argv0;
7203 while (*g_argv)
7204 *pp++ = *g_argv++;
7205 /* *pp = NULL; - is already there */
7206 pp = environ;
7207
7208 do_exec:
7209 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007210 /* Don't propagate SIG_IGN to the child */
7211 if (SPECIAL_JOBSTOP_SIGS != 0)
7212 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007213 execve(bb_busybox_exec_path, argv, pp);
7214 /* Fallback. Useful for init=/bin/hush usage etc */
7215 if (argv[0][0] == '/')
7216 execve(argv[0], argv, pp);
7217 xfunc_error_retval = 127;
7218 bb_error_msg_and_die("can't re-execute the shell");
7219}
7220#endif /* !BB_MMU */
7221
7222
7223static int run_and_free_list(struct pipe *pi);
7224
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007225/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007226 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7227 * end_trigger controls how often we stop parsing
7228 * NUL: parse all, execute, return
7229 * ';': parse till ';' or newline, execute, repeat till EOF
7230 */
7231static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007232{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007233 /* Why we need empty flag?
7234 * An obscure corner case "false; ``; echo $?":
7235 * empty command in `` should still set $? to 0.
7236 * But we can't just set $? to 0 at the start,
7237 * this breaks "false; echo `echo $?`" case.
7238 */
7239 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007240 while (1) {
7241 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007242
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007243#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007244 if (end_trigger == ';') {
7245 G.promptmode = 0; /* PS1 */
7246 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7247 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007248#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007249 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007250 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7251 /* If we are in "big" script
7252 * (not in `cmd` or something similar)...
7253 */
7254 if (pipe_list == ERR_PTR && end_trigger == ';') {
7255 /* Discard cached input (rest of line) */
7256 int ch = inp->last_char;
7257 while (ch != EOF && ch != '\n') {
7258 //bb_error_msg("Discarded:'%c'", ch);
7259 ch = i_getch(inp);
7260 }
7261 /* Force prompt */
7262 inp->p = NULL;
7263 /* This stream isn't empty */
7264 empty = 0;
7265 continue;
7266 }
7267 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007268 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007269 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007270 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007271 debug_print_tree(pipe_list, 0);
7272 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7273 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007274 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007275 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007276 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007277 }
Eric Andersen25f27032001-04-26 23:22:31 +00007278}
7279
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007280static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007281{
7282 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007283 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007284
Eric Andersen25f27032001-04-26 23:22:31 +00007285 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007286 parse_and_run_stream(&input, '\0');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007287 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007288}
7289
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007290static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007291{
Eric Andersen25f27032001-04-26 23:22:31 +00007292 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007293 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007294
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007295 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007296 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007297 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007298 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007299}
7300
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007301#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007302static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007303{
7304 pid_t pid;
7305 int channel[2];
7306# if !BB_MMU
7307 char **to_free = NULL;
7308# endif
7309
7310 xpipe(channel);
7311 pid = BB_MMU ? xfork() : xvfork();
7312 if (pid == 0) { /* child */
7313 disable_restore_tty_pgrp_on_exit();
7314 /* Process substitution is not considered to be usual
7315 * 'command execution'.
7316 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7317 */
7318 bb_signals(0
7319 + (1 << SIGTSTP)
7320 + (1 << SIGTTIN)
7321 + (1 << SIGTTOU)
7322 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007323 close(channel[0]); /* NB: close _first_, then move fd! */
7324 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007325# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007326 /* Awful hack for `trap` or $(trap).
7327 *
7328 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7329 * contains an example where "trap" is executed in a subshell:
7330 *
7331 * save_traps=$(trap)
7332 * ...
7333 * eval "$save_traps"
7334 *
7335 * Standard does not say that "trap" in subshell shall print
7336 * parent shell's traps. It only says that its output
7337 * must have suitable form, but then, in the above example
7338 * (which is not supposed to be normative), it implies that.
7339 *
7340 * bash (and probably other shell) does implement it
7341 * (traps are reset to defaults, but "trap" still shows them),
7342 * but as a result, "trap" logic is hopelessly messed up:
7343 *
7344 * # trap
7345 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7346 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7347 * # true | trap <--- trap is in subshell - no output (ditto)
7348 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7349 * trap -- 'echo Ho' SIGWINCH
7350 * # echo `(trap)` <--- in subshell in subshell - output
7351 * trap -- 'echo Ho' SIGWINCH
7352 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7353 * trap -- 'echo Ho' SIGWINCH
7354 *
7355 * The rules when to forget and when to not forget traps
7356 * get really complex and nonsensical.
7357 *
7358 * Our solution: ONLY bare $(trap) or `trap` is special.
7359 */
7360 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007361 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007362 && skip_whitespace(s + 4)[0] == '\0'
7363 ) {
7364 static const char *const argv[] = { NULL, NULL };
7365 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007366 fflush_all(); /* important */
7367 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007368 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007369# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007370# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007371 /* Prevent it from trying to handle ctrl-z etc */
7372 IF_HUSH_JOB(G.run_list_level = 1;)
7373 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007374 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007375 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007376 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007377 parse_and_run_string(s);
7378 _exit(G.last_exitcode);
7379# else
7380 /* We re-execute after vfork on NOMMU. This makes this script safe:
7381 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7382 * huge=`cat BIG` # was blocking here forever
7383 * echo OK
7384 */
7385 re_execute_shell(&to_free,
7386 s,
7387 G.global_argv[0],
7388 G.global_argv + 1,
7389 NULL);
7390# endif
7391 }
7392
7393 /* parent */
7394 *pid_p = pid;
7395# if ENABLE_HUSH_FAST
7396 G.count_SIGCHLD++;
7397//bb_error_msg("[%d] fork in generate_stream_from_string:"
7398// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7399// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7400# endif
7401 enable_restore_tty_pgrp_on_exit();
7402# if !BB_MMU
7403 free(to_free);
7404# endif
7405 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007406 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007407}
7408
7409/* Return code is exit status of the process that is run. */
7410static int process_command_subs(o_string *dest, const char *s)
7411{
7412 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007413 pid_t pid;
7414 int status, ch, eol_cnt;
7415
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007416 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007417
7418 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007419 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007420 while ((ch = getc(fp)) != EOF) {
7421 if (ch == '\0')
7422 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007423 if (ch == '\n') {
7424 eol_cnt++;
7425 continue;
7426 }
7427 while (eol_cnt) {
7428 o_addchr(dest, '\n');
7429 eol_cnt--;
7430 }
7431 o_addQchr(dest, ch);
7432 }
7433
7434 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007435 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007436 /* We need to extract exitcode. Test case
7437 * "true; echo `sleep 1; false` $?"
7438 * should print 1 */
7439 safe_waitpid(pid, &status, 0);
7440 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7441 return WEXITSTATUS(status);
7442}
7443#endif /* ENABLE_HUSH_TICK */
7444
7445
7446static void setup_heredoc(struct redir_struct *redir)
7447{
7448 struct fd_pair pair;
7449 pid_t pid;
7450 int len, written;
7451 /* the _body_ of heredoc (misleading field name) */
7452 const char *heredoc = redir->rd_filename;
7453 char *expanded;
7454#if !BB_MMU
7455 char **to_free;
7456#endif
7457
7458 expanded = NULL;
7459 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007460 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007461 if (expanded)
7462 heredoc = expanded;
7463 }
7464 len = strlen(heredoc);
7465
7466 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7467 xpiped_pair(pair);
7468 xmove_fd(pair.rd, redir->rd_fd);
7469
7470 /* Try writing without forking. Newer kernels have
7471 * dynamically growing pipes. Must use non-blocking write! */
7472 ndelay_on(pair.wr);
7473 while (1) {
7474 written = write(pair.wr, heredoc, len);
7475 if (written <= 0)
7476 break;
7477 len -= written;
7478 if (len == 0) {
7479 close(pair.wr);
7480 free(expanded);
7481 return;
7482 }
7483 heredoc += written;
7484 }
7485 ndelay_off(pair.wr);
7486
7487 /* Okay, pipe buffer was not big enough */
7488 /* Note: we must not create a stray child (bastard? :)
7489 * for the unsuspecting parent process. Child creates a grandchild
7490 * and exits before parent execs the process which consumes heredoc
7491 * (that exec happens after we return from this function) */
7492#if !BB_MMU
7493 to_free = NULL;
7494#endif
7495 pid = xvfork();
7496 if (pid == 0) {
7497 /* child */
7498 disable_restore_tty_pgrp_on_exit();
7499 pid = BB_MMU ? xfork() : xvfork();
7500 if (pid != 0)
7501 _exit(0);
7502 /* grandchild */
7503 close(redir->rd_fd); /* read side of the pipe */
7504#if BB_MMU
7505 full_write(pair.wr, heredoc, len); /* may loop or block */
7506 _exit(0);
7507#else
7508 /* Delegate blocking writes to another process */
7509 xmove_fd(pair.wr, STDOUT_FILENO);
7510 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7511#endif
7512 }
7513 /* parent */
7514#if ENABLE_HUSH_FAST
7515 G.count_SIGCHLD++;
7516//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7517#endif
7518 enable_restore_tty_pgrp_on_exit();
7519#if !BB_MMU
7520 free(to_free);
7521#endif
7522 close(pair.wr);
7523 free(expanded);
7524 wait(NULL); /* wait till child has died */
7525}
7526
Denys Vlasenko2db74612017-07-07 22:07:28 +02007527struct squirrel {
7528 int orig_fd;
7529 int moved_to;
7530 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7531 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7532};
7533
Denys Vlasenko621fc502017-07-24 12:42:17 +02007534static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7535{
7536 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7537 sq[i].orig_fd = orig;
7538 sq[i].moved_to = moved;
7539 sq[i+1].orig_fd = -1; /* end marker */
7540 return sq;
7541}
7542
Denys Vlasenko2db74612017-07-07 22:07:28 +02007543static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7544{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007545 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007546 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007547
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007548 i = 0;
7549 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007550 /* If we collide with an already moved fd... */
7551 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007552 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007553 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7554 if (sq[i].moved_to < 0) /* what? */
7555 xfunc_die();
7556 return sq;
7557 }
7558 if (fd == sq[i].orig_fd) {
7559 /* Example: echo Hello >/dev/null 1>&2 */
7560 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7561 return sq;
7562 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007563 }
7564
Denys Vlasenko2db74612017-07-07 22:07:28 +02007565 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007566 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007567 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7568 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007569 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007570 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007571}
7572
Denys Vlasenko657e9002017-07-30 23:34:04 +02007573static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7574{
7575 int i;
7576
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007577 i = 0;
7578 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007579 /* If we collide with an already moved fd... */
7580 if (fd == sq[i].orig_fd) {
7581 /* Examples:
7582 * "echo 3>FILE 3>&- 3>FILE"
7583 * "echo 3>&- 3>FILE"
7584 * No need for last redirect to insert
7585 * another "need to close 3" indicator.
7586 */
7587 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7588 return sq;
7589 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007590 }
7591
7592 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7593 return append_squirrel(sq, i, fd, -1);
7594}
7595
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007596/* fd: redirect wants this fd to be used (e.g. 3>file).
7597 * Move all conflicting internally used fds,
7598 * and remember them so that we can restore them later.
7599 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007600static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007601{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007602 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7603 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007604
7605#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007606 if (fd == G_interactive_fd) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007607 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007608 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7609 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 +02007610 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007611 }
7612#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007613 /* Are we called from setup_redirects(squirrel==NULL)
7614 * in redirect in a [v]forked child?
7615 */
7616 if (sqp == NULL) {
7617 /* No need to move script fds.
7618 * For NOMMU case, it's actively wrong: we'd change ->fd
7619 * fields in memory for the parent, but parent's fds
7620 * aren't be moved, it would use wrong fd!
7621 * Reproducer: "cmd 3>FILE" in script.
7622 * If we would call move_HFILEs_on_redirect(), child would:
7623 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7624 * close(3) = 0
7625 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7626 */
7627 //bb_error_msg("sqp == NULL: [v]forked child");
7628 return 0;
7629 }
7630
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007631 /* If this one of script's fds? */
7632 if (move_HFILEs_on_redirect(fd, avoid_fd))
7633 return 1; /* yes. "we closed fd" (actually moved it) */
7634
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007635 /* Are we called for "exec 3>FILE"? Came through
7636 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7637 * This case used to fail for this script:
7638 * exec 3>FILE
7639 * echo Ok
7640 * ...100000 more lines...
7641 * echo Ok
7642 * as follows:
7643 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7644 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7645 * dup2(4, 3) = 3
7646 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7647 * close(4) = 0
7648 * write(1, "Ok\n", 3) = 3
7649 * ... = 3
7650 * write(1, "Ok\n", 3) = 3
7651 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7652 * ^^^^^^^^ oops, wrong fd!!!
7653 * With this case separate from sqp == NULL and *after* move_HFILEs,
7654 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007655 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007656 if (sqp == ERR_PTR) {
7657 /* Don't preserve redirected fds: exec is _meant_ to change these */
7658 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007659 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007660 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007661
Denys Vlasenko2db74612017-07-07 22:07:28 +02007662 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7663 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7664 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007665}
7666
Denys Vlasenko2db74612017-07-07 22:07:28 +02007667static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007668{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007669 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007670 int i;
7671 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007672 if (sq[i].moved_to >= 0) {
7673 /* We simply die on error */
7674 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7675 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7676 } else {
7677 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7678 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7679 close(sq[i].orig_fd);
7680 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007681 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007682 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007683 }
7684
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007685 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007686}
7687
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007688#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007689static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007690{
7691 if (G_interactive_fd)
7692 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007693 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007694}
7695#endif
7696
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007697static int internally_opened_fd(int fd, struct squirrel *sq)
7698{
7699 int i;
7700
7701#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007702 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007703 return 1;
7704#endif
7705 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007706 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007707 return 1;
7708
7709 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7710 if (fd == sq[i].moved_to)
7711 return 1;
7712 }
7713 return 0;
7714}
7715
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007716/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7717 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007718static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007719{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007720 struct redir_struct *redir;
7721
7722 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007723 int newfd;
7724 int closed;
7725
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007726 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007727 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007728 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007729 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7730 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007731 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007732 redir->rd_filename);
7733 setup_heredoc(redir);
7734 continue;
7735 }
7736
7737 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007738 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007739 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007740 int mode;
7741
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007743 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007744 * "cmd >" (no filename)
7745 * "cmd > <file" (2nd redirect starts too early)
7746 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007747 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007748 continue;
7749 }
7750 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007751 p = expand_string_to_string(redir->rd_filename,
7752 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007753 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007754 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007755 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007756 /* Error message from open_or_warn can be lost
7757 * if stderr has been redirected, but bash
7758 * and ash both lose it as well
7759 * (though zsh doesn't!)
7760 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007761 return 1;
7762 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007763 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007764 /* open() gave us precisely the fd we wanted.
7765 * This means that this fd was not busy
7766 * (not opened to anywhere).
7767 * Remember to close it on restore:
7768 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007769 *sqp = add_squirrel_closed(*sqp, newfd);
7770 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007771 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007772 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007773 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7774 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007775 }
7776
Denys Vlasenko657e9002017-07-30 23:34:04 +02007777 if (newfd == redir->rd_fd)
7778 continue;
7779
7780 /* if "N>FILE": move newfd to redir->rd_fd */
7781 /* if "N>&M": dup newfd to redir->rd_fd */
7782 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7783
7784 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7785 if (newfd == REDIRFD_CLOSE) {
7786 /* "N>&-" means "close me" */
7787 if (!closed) {
7788 /* ^^^ optimization: saving may already
7789 * have closed it. If not... */
7790 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007791 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007792 /* Sometimes we do another close on restore, getting EBADF.
7793 * Consider "echo 3>FILE 3>&-"
7794 * first redirect remembers "need to close 3",
7795 * and second redirect closes 3! Restore code then closes 3 again.
7796 */
7797 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007798 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007799 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007800 //errno = EBADF;
7801 //bb_perror_msg_and_die("can't duplicate file descriptor");
7802 newfd = -1; /* same effect as code above */
7803 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007804 xdup2(newfd, redir->rd_fd);
7805 if (redir->rd_dup == REDIRFD_TO_FILE)
7806 /* "rd_fd > FILE" */
7807 close(newfd);
7808 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007809 }
7810 }
7811 return 0;
7812}
7813
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007814static char *find_in_path(const char *arg)
7815{
7816 char *ret = NULL;
7817 const char *PATH = get_local_var_value("PATH");
7818
7819 if (!PATH)
7820 return NULL;
7821
7822 while (1) {
7823 const char *end = strchrnul(PATH, ':');
7824 int sz = end - PATH; /* must be int! */
7825
7826 free(ret);
7827 if (sz != 0) {
7828 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7829 } else {
7830 /* We have xxx::yyyy in $PATH,
7831 * it means "use current dir" */
7832 ret = xstrdup(arg);
7833 }
7834 if (access(ret, F_OK) == 0)
7835 break;
7836
7837 if (*end == '\0') {
7838 free(ret);
7839 return NULL;
7840 }
7841 PATH = end + 1;
7842 }
7843
7844 return ret;
7845}
7846
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007847static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007848 const struct built_in_command *x,
7849 const struct built_in_command *end)
7850{
7851 while (x != end) {
7852 if (strcmp(name, x->b_cmd) != 0) {
7853 x++;
7854 continue;
7855 }
7856 debug_printf_exec("found builtin '%s'\n", name);
7857 return x;
7858 }
7859 return NULL;
7860}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007861static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007862{
7863 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7864}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007865static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007866{
7867 const struct built_in_command *x = find_builtin1(name);
7868 if (x)
7869 return x;
7870 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7871}
7872
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007873static void remove_nested_vars(void)
7874{
7875 struct variable *cur;
7876 struct variable **cur_pp;
7877
7878 cur_pp = &G.top_var;
7879 while ((cur = *cur_pp) != NULL) {
7880 if (cur->var_nest_level <= G.var_nest_level) {
7881 cur_pp = &cur->next;
7882 continue;
7883 }
7884 /* Unexport */
7885 if (cur->flg_export) {
7886 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7887 bb_unsetenv(cur->varstr);
7888 }
7889 /* Remove from global list */
7890 *cur_pp = cur->next;
7891 /* Free */
7892 if (!cur->max_len) {
7893 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7894 free(cur->varstr);
7895 }
7896 free(cur);
7897 }
7898}
7899
7900static void enter_var_nest_level(void)
7901{
7902 G.var_nest_level++;
7903 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7904
7905 /* Try: f() { echo -n .; f; }; f
7906 * struct variable::var_nest_level is uint16_t,
7907 * thus limiting recursion to < 2^16.
7908 * In any case, with 8 Mbyte stack SEGV happens
7909 * not too long after 2^16 recursions anyway.
7910 */
7911 if (G.var_nest_level > 0xff00)
7912 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7913}
7914
7915static void leave_var_nest_level(void)
7916{
7917 G.var_nest_level--;
7918 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7919 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7920 bb_error_msg_and_die("BUG: nesting underflow");
7921
7922 remove_nested_vars();
7923}
7924
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007925#if ENABLE_HUSH_FUNCTIONS
7926static struct function **find_function_slot(const char *name)
7927{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007928 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007929 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007930
7931 while ((funcp = *funcpp) != NULL) {
7932 if (strcmp(name, funcp->name) == 0) {
7933 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007934 break;
7935 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007936 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007937 }
7938 return funcpp;
7939}
7940
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007941static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007942{
7943 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007944 return funcp;
7945}
7946
7947/* Note: takes ownership on name ptr */
7948static struct function *new_function(char *name)
7949{
7950 struct function **funcpp = find_function_slot(name);
7951 struct function *funcp = *funcpp;
7952
7953 if (funcp != NULL) {
7954 struct command *cmd = funcp->parent_cmd;
7955 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7956 if (!cmd) {
7957 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7958 free(funcp->name);
7959 /* Note: if !funcp->body, do not free body_as_string!
7960 * This is a special case of "-F name body" function:
7961 * body_as_string was not malloced! */
7962 if (funcp->body) {
7963 free_pipe_list(funcp->body);
7964# if !BB_MMU
7965 free(funcp->body_as_string);
7966# endif
7967 }
7968 } else {
7969 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7970 cmd->argv[0] = funcp->name;
7971 cmd->group = funcp->body;
7972# if !BB_MMU
7973 cmd->group_as_string = funcp->body_as_string;
7974# endif
7975 }
7976 } else {
7977 debug_printf_exec("remembering new function '%s'\n", name);
7978 funcp = *funcpp = xzalloc(sizeof(*funcp));
7979 /*funcp->next = NULL;*/
7980 }
7981
7982 funcp->name = name;
7983 return funcp;
7984}
7985
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007986# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007987static void unset_func(const char *name)
7988{
7989 struct function **funcpp = find_function_slot(name);
7990 struct function *funcp = *funcpp;
7991
7992 if (funcp != NULL) {
7993 debug_printf_exec("freeing function '%s'\n", funcp->name);
7994 *funcpp = funcp->next;
7995 /* funcp is unlinked now, deleting it.
7996 * Note: if !funcp->body, the function was created by
7997 * "-F name body", do not free ->body_as_string
7998 * and ->name as they were not malloced. */
7999 if (funcp->body) {
8000 free_pipe_list(funcp->body);
8001 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008002# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008003 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008004# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008005 }
8006 free(funcp);
8007 }
8008}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008009# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008010
8011# if BB_MMU
8012#define exec_function(to_free, funcp, argv) \
8013 exec_function(funcp, argv)
8014# endif
8015static void exec_function(char ***to_free,
8016 const struct function *funcp,
8017 char **argv) NORETURN;
8018static void exec_function(char ***to_free,
8019 const struct function *funcp,
8020 char **argv)
8021{
8022# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008023 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008024
8025 argv[0] = G.global_argv[0];
8026 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008027 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008028
8029// Example when we are here: "cmd | func"
8030// func will run with saved-redirect fds open.
8031// $ f() { echo /proc/self/fd/*; }
8032// $ true | f
8033// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8034// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8035// Same in script:
8036// $ . ./SCRIPT
8037// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8038// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8039// They are CLOEXEC so external programs won't see them, but
8040// for "more correctness" we might want to close those extra fds here:
8041//? close_saved_fds_and_FILE_fds();
8042
Denys Vlasenko332e4112018-04-04 22:32:59 +02008043 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008044 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008045 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008046 IF_HUSH_LOCAL(G.func_nest_level++;)
8047
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008048 /* On MMU, funcp->body is always non-NULL */
8049 n = run_list(funcp->body);
8050 fflush_all();
8051 _exit(n);
8052# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008053//? close_saved_fds_and_FILE_fds();
8054
8055//TODO: check whether "true | func_with_return" works
8056
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008057 re_execute_shell(to_free,
8058 funcp->body_as_string,
8059 G.global_argv[0],
8060 argv + 1,
8061 NULL);
8062# endif
8063}
8064
8065static int run_function(const struct function *funcp, char **argv)
8066{
8067 int rc;
8068 save_arg_t sv;
8069 smallint sv_flg;
8070
8071 save_and_replace_G_args(&sv, argv);
8072
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008073 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008074 sv_flg = G_flag_return_in_progress;
8075 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008076
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008077 /* Make "local" variables properly shadow previous ones */
8078 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008079 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008080
8081 /* On MMU, funcp->body is always non-NULL */
8082# if !BB_MMU
8083 if (!funcp->body) {
8084 /* Function defined by -F */
8085 parse_and_run_string(funcp->body_as_string);
8086 rc = G.last_exitcode;
8087 } else
8088# endif
8089 {
8090 rc = run_list(funcp->body);
8091 }
8092
Denys Vlasenko332e4112018-04-04 22:32:59 +02008093 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008094 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008095
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008096 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008097
8098 restore_G_args(&sv, argv);
8099
8100 return rc;
8101}
8102#endif /* ENABLE_HUSH_FUNCTIONS */
8103
8104
8105#if BB_MMU
8106#define exec_builtin(to_free, x, argv) \
8107 exec_builtin(x, argv)
8108#else
8109#define exec_builtin(to_free, x, argv) \
8110 exec_builtin(to_free, argv)
8111#endif
8112static void exec_builtin(char ***to_free,
8113 const struct built_in_command *x,
8114 char **argv) NORETURN;
8115static void exec_builtin(char ***to_free,
8116 const struct built_in_command *x,
8117 char **argv)
8118{
8119#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008120 int rcode;
8121 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008122//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008123 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008124 fflush_all();
8125 _exit(rcode);
8126#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008127 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008128 /* On NOMMU, we must never block!
8129 * Example: { sleep 99 | read line; } & echo Ok
8130 */
8131 re_execute_shell(to_free,
8132 argv[0],
8133 G.global_argv[0],
8134 G.global_argv + 1,
8135 argv);
8136#endif
8137}
8138
8139
8140static void execvp_or_die(char **argv) NORETURN;
8141static void execvp_or_die(char **argv)
8142{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008143 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008144 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008145 /* Don't propagate SIG_IGN to the child */
8146 if (SPECIAL_JOBSTOP_SIGS != 0)
8147 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008148 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008149 e = 2;
8150 if (errno == EACCES) e = 126;
8151 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008152 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008153 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008154}
8155
8156#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008157static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008158{
8159 unsigned len;
8160 const char *cp;
8161
8162 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008163
8164 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8165 /* test a char with: bash -c 'set -x; echo "CH"' */
8166 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8167 " " "\001\002\003\004\005\006\007"
8168 "\010\011\012\013\014\015\016\017"
8169 "\020\021\022\023\024\025\026\027"
8170 "\030\031\032\033\034\035\036\037"
8171 )
8172 ] == '\0'
8173 ) {
8174 /* string has no special chars */
8175 x_mode_addstr(str);
8176 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008177 }
8178
8179 cp = str;
8180 for (;;) {
8181 /* print '....' up to EOL or first squote */
8182 len = (int)(strchrnul(cp, '\'') - cp);
8183 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008184 x_mode_addchr('\'');
8185 x_mode_addblock(cp, len);
8186 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008187 cp += len;
8188 }
8189 if (*cp == '\0')
8190 break;
8191 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008192 x_mode_addchr('\\');
8193 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008194 cp++;
8195 }
8196}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008197static void dump_cmd_in_x_mode(char **argv)
8198{
8199 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008200 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008201
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008202 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008203 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008204 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008205 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008206 x_mode_addchr(' ');
8207 if (argv[n][0] == '\0') {
8208 x_mode_addchr('\'');
8209 x_mode_addchr('\'');
8210 } else {
8211 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008212 }
8213 n++;
8214 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008215 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008216 }
8217}
8218#else
8219# define dump_cmd_in_x_mode(argv) ((void)0)
8220#endif
8221
Denys Vlasenko57000292018-01-12 14:41:45 +01008222#if ENABLE_HUSH_COMMAND
8223static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8224{
8225 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008226
Denys Vlasenko57000292018-01-12 14:41:45 +01008227 if (!opt_vV)
8228 return;
8229
8230 to_free = NULL;
8231 if (!explanation) {
8232 char *path = getenv("PATH");
8233 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008234 if (!explanation)
8235 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008236 if (opt_vV != 'V')
8237 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8238 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008239 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008240 free(to_free);
8241 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008242 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008243}
8244#else
8245# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8246#endif
8247
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008248#if BB_MMU
8249#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8250 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8251#define pseudo_exec(nommu_save, command, argv_expanded) \
8252 pseudo_exec(command, argv_expanded)
8253#endif
8254
8255/* Called after [v]fork() in run_pipe, or from builtin_exec.
8256 * Never returns.
8257 * Don't exit() here. If you don't exec, use _exit instead.
8258 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008259 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008260 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008261static void pseudo_exec_argv(nommu_save_t *nommu_save,
8262 char **argv, int assignment_cnt,
8263 char **argv_expanded) NORETURN;
8264static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8265 char **argv, int assignment_cnt,
8266 char **argv_expanded)
8267{
Denys Vlasenko57000292018-01-12 14:41:45 +01008268 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008269 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008270 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008271 IF_HUSH_COMMAND(char opt_vV = 0;)
8272 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008273
8274 new_env = expand_assignments(argv, assignment_cnt);
8275 dump_cmd_in_x_mode(new_env);
8276
8277 if (!argv[assignment_cnt]) {
8278 /* Case when we are here: ... | var=val | ...
8279 * (note that we do not exit early, i.e., do not optimize out
8280 * expand_assignments(): think about ... | var=`sleep 1` | ...
8281 */
8282 free_strings(new_env);
8283 _exit(EXIT_SUCCESS);
8284 }
8285
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008286 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008287#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008288 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008289#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008290 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008291 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008292#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008293 set_vars_and_save_old(new_env);
8294 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008295
8296 if (argv_expanded) {
8297 argv = argv_expanded;
8298 } else {
8299 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8300#if !BB_MMU
8301 nommu_save->argv = argv;
8302#endif
8303 }
8304 dump_cmd_in_x_mode(argv);
8305
8306#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8307 if (strchr(argv[0], '/') != NULL)
8308 goto skip;
8309#endif
8310
Denys Vlasenko75481d32017-07-31 05:27:09 +02008311#if ENABLE_HUSH_FUNCTIONS
8312 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008313 funcp = find_function(argv[0]);
8314 if (funcp)
8315 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008316#endif
8317
Denys Vlasenko57000292018-01-12 14:41:45 +01008318#if ENABLE_HUSH_COMMAND
8319 /* "command BAR": run BAR without looking it up among functions
8320 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8321 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8322 */
8323 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8324 char *p;
8325
8326 argv++;
8327 p = *argv;
8328 if (p[0] != '-' || !p[1])
8329 continue; /* bash allows "command command command [-OPT] BAR" */
8330
8331 for (;;) {
8332 p++;
8333 switch (*p) {
8334 case '\0':
8335 argv++;
8336 p = *argv;
8337 if (p[0] != '-' || !p[1])
8338 goto after_opts;
8339 continue; /* next arg is also -opts, process it too */
8340 case 'v':
8341 case 'V':
8342 opt_vV = *p;
8343 continue;
8344 default:
8345 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8346 }
8347 }
8348 }
8349 after_opts:
8350# if ENABLE_HUSH_FUNCTIONS
8351 if (opt_vV && find_function(argv[0]))
8352 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8353# endif
8354#endif
8355
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356 /* Check if the command matches any of the builtins.
8357 * Depending on context, this might be redundant. But it's
8358 * easier to waste a few CPU cycles than it is to figure out
8359 * if this is one of those cases.
8360 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008361 /* Why "BB_MMU ? :" difference in logic? -
8362 * On NOMMU, it is more expensive to re-execute shell
8363 * just in order to run echo or test builtin.
8364 * It's better to skip it here and run corresponding
8365 * non-builtin later. */
8366 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8367 if (x) {
8368 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8369 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008370 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008371
8372#if ENABLE_FEATURE_SH_STANDALONE
8373 /* Check if the command matches any busybox applets */
8374 {
8375 int a = find_applet_by_name(argv[0]);
8376 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008377 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008378# if BB_MMU /* see above why on NOMMU it is not allowed */
8379 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008380 /* Do not leak open fds from opened script files etc.
8381 * Testcase: interactive "ls -l /proc/self/fd"
8382 * should not show tty fd open.
8383 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008384 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008385//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008386//This casuses test failures in
8387//redir_children_should_not_see_saved_fd_2.tests
8388//redir_children_should_not_see_saved_fd_3.tests
8389//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008390 /* Without this, "rm -i FILE" can't be ^C'ed: */
8391 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008392 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008393 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008394 }
8395# endif
8396 /* Re-exec ourselves */
8397 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008398 /* Don't propagate SIG_IGN to the child */
8399 if (SPECIAL_JOBSTOP_SIGS != 0)
8400 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008401 execv(bb_busybox_exec_path, argv);
8402 /* If they called chroot or otherwise made the binary no longer
8403 * executable, fall through */
8404 }
8405 }
8406#endif
8407
8408#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8409 skip:
8410#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008411 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008412 execvp_or_die(argv);
8413}
8414
8415/* Called after [v]fork() in run_pipe
8416 */
8417static void pseudo_exec(nommu_save_t *nommu_save,
8418 struct command *command,
8419 char **argv_expanded) NORETURN;
8420static void pseudo_exec(nommu_save_t *nommu_save,
8421 struct command *command,
8422 char **argv_expanded)
8423{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008424#if ENABLE_HUSH_FUNCTIONS
8425 if (command->cmd_type == CMD_FUNCDEF) {
8426 /* Ignore funcdefs in pipes:
8427 * true | f() { cmd }
8428 */
8429 _exit(0);
8430 }
8431#endif
8432
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008433 if (command->argv) {
8434 pseudo_exec_argv(nommu_save, command->argv,
8435 command->assignment_cnt, argv_expanded);
8436 }
8437
8438 if (command->group) {
8439 /* Cases when we are here:
8440 * ( list )
8441 * { list } &
8442 * ... | ( list ) | ...
8443 * ... | { list } | ...
8444 */
8445#if BB_MMU
8446 int rcode;
8447 debug_printf_exec("pseudo_exec: run_list\n");
8448 reset_traps_to_defaults();
8449 rcode = run_list(command->group);
8450 /* OK to leak memory by not calling free_pipe_list,
8451 * since this process is about to exit */
8452 _exit(rcode);
8453#else
8454 re_execute_shell(&nommu_save->argv_from_re_execing,
8455 command->group_as_string,
8456 G.global_argv[0],
8457 G.global_argv + 1,
8458 NULL);
8459#endif
8460 }
8461
8462 /* Case when we are here: ... | >file */
8463 debug_printf_exec("pseudo_exec'ed null command\n");
8464 _exit(EXIT_SUCCESS);
8465}
8466
8467#if ENABLE_HUSH_JOB
8468static const char *get_cmdtext(struct pipe *pi)
8469{
8470 char **argv;
8471 char *p;
8472 int len;
8473
8474 /* This is subtle. ->cmdtext is created only on first backgrounding.
8475 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8476 * On subsequent bg argv is trashed, but we won't use it */
8477 if (pi->cmdtext)
8478 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008479
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008480 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008481 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008482 pi->cmdtext = xzalloc(1);
8483 return pi->cmdtext;
8484 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008485 len = 0;
8486 do {
8487 len += strlen(*argv) + 1;
8488 } while (*++argv);
8489 p = xmalloc(len);
8490 pi->cmdtext = p;
8491 argv = pi->cmds[0].argv;
8492 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008493 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008494 *p++ = ' ';
8495 } while (*++argv);
8496 p[-1] = '\0';
8497 return pi->cmdtext;
8498}
8499
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008500static void remove_job_from_table(struct pipe *pi)
8501{
8502 struct pipe *prev_pipe;
8503
8504 if (pi == G.job_list) {
8505 G.job_list = pi->next;
8506 } else {
8507 prev_pipe = G.job_list;
8508 while (prev_pipe->next != pi)
8509 prev_pipe = prev_pipe->next;
8510 prev_pipe->next = pi->next;
8511 }
8512 G.last_jobid = 0;
8513 if (G.job_list)
8514 G.last_jobid = G.job_list->jobid;
8515}
8516
8517static void delete_finished_job(struct pipe *pi)
8518{
8519 remove_job_from_table(pi);
8520 free_pipe(pi);
8521}
8522
8523static void clean_up_last_dead_job(void)
8524{
8525 if (G.job_list && !G.job_list->alive_cmds)
8526 delete_finished_job(G.job_list);
8527}
8528
Denys Vlasenko16096292017-07-10 10:00:28 +02008529static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008530{
8531 struct pipe *job, **jobp;
8532 int i;
8533
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008534 clean_up_last_dead_job();
8535
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008536 /* Find the end of the list, and find next job ID to use */
8537 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008538 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008539 while ((job = *jobp) != NULL) {
8540 if (job->jobid > i)
8541 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008542 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008543 }
8544 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008545
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008546 /* Create a new job struct at the end */
8547 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008548 job->next = NULL;
8549 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8550 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8551 for (i = 0; i < pi->num_cmds; i++) {
8552 job->cmds[i].pid = pi->cmds[i].pid;
8553 /* all other fields are not used and stay zero */
8554 }
8555 job->cmdtext = xstrdup(get_cmdtext(pi));
8556
8557 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008558 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008559 G.last_jobid = job->jobid;
8560}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008561#endif /* JOB */
8562
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008563static int job_exited_or_stopped(struct pipe *pi)
8564{
8565 int rcode, i;
8566
8567 if (pi->alive_cmds != pi->stopped_cmds)
8568 return -1;
8569
8570 /* All processes in fg pipe have exited or stopped */
8571 rcode = 0;
8572 i = pi->num_cmds;
8573 while (--i >= 0) {
8574 rcode = pi->cmds[i].cmd_exitcode;
8575 /* usually last process gives overall exitstatus,
8576 * but with "set -o pipefail", last *failed* process does */
8577 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8578 break;
8579 }
8580 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8581 return rcode;
8582}
8583
Denys Vlasenko7e675362016-10-28 21:57:31 +02008584static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008585{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008586#if ENABLE_HUSH_JOB
8587 struct pipe *pi;
8588#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008589 int i, dead;
8590
8591 dead = WIFEXITED(status) || WIFSIGNALED(status);
8592
8593#if DEBUG_JOBS
8594 if (WIFSTOPPED(status))
8595 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8596 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8597 if (WIFSIGNALED(status))
8598 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8599 childpid, WTERMSIG(status), WEXITSTATUS(status));
8600 if (WIFEXITED(status))
8601 debug_printf_jobs("pid %d exited, exitcode %d\n",
8602 childpid, WEXITSTATUS(status));
8603#endif
8604 /* Were we asked to wait for a fg pipe? */
8605 if (fg_pipe) {
8606 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008607
Denys Vlasenko7e675362016-10-28 21:57:31 +02008608 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008609 int rcode;
8610
Denys Vlasenko7e675362016-10-28 21:57:31 +02008611 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8612 if (fg_pipe->cmds[i].pid != childpid)
8613 continue;
8614 if (dead) {
8615 int ex;
8616 fg_pipe->cmds[i].pid = 0;
8617 fg_pipe->alive_cmds--;
8618 ex = WEXITSTATUS(status);
8619 /* bash prints killer signal's name for *last*
8620 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8621 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8622 */
8623 if (WIFSIGNALED(status)) {
8624 int sig = WTERMSIG(status);
8625 if (i == fg_pipe->num_cmds-1)
8626 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8627 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8628 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8629 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8630 * Maybe we need to use sig | 128? */
8631 ex = sig + 128;
8632 }
8633 fg_pipe->cmds[i].cmd_exitcode = ex;
8634 } else {
8635 fg_pipe->stopped_cmds++;
8636 }
8637 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8638 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008639 rcode = job_exited_or_stopped(fg_pipe);
8640 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008641/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8642 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8643 * and "killall -STOP cat" */
8644 if (G_interactive_fd) {
8645#if ENABLE_HUSH_JOB
8646 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008647 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008648#endif
8649 return rcode;
8650 }
8651 if (fg_pipe->alive_cmds == 0)
8652 return rcode;
8653 }
8654 /* There are still running processes in the fg_pipe */
8655 return -1;
8656 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008657 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008658 }
8659
8660#if ENABLE_HUSH_JOB
8661 /* We were asked to wait for bg or orphaned children */
8662 /* No need to remember exitcode in this case */
8663 for (pi = G.job_list; pi; pi = pi->next) {
8664 for (i = 0; i < pi->num_cmds; i++) {
8665 if (pi->cmds[i].pid == childpid)
8666 goto found_pi_and_prognum;
8667 }
8668 }
8669 /* Happens when shell is used as init process (init=/bin/sh) */
8670 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8671 return -1; /* this wasn't a process from fg_pipe */
8672
8673 found_pi_and_prognum:
8674 if (dead) {
8675 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008676 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008677 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008678 rcode = 128 + WTERMSIG(status);
8679 pi->cmds[i].cmd_exitcode = rcode;
8680 if (G.last_bg_pid == pi->cmds[i].pid)
8681 G.last_bg_pid_exitcode = rcode;
8682 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008683 pi->alive_cmds--;
8684 if (!pi->alive_cmds) {
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008685#if ENABLE_HUSH_BASH_COMPAT
8686 G.dead_job_exitcode = job_exited_or_stopped(pi);
8687#endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008688 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008689 printf(JOB_STATUS_FORMAT, pi->jobid,
8690 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008691 delete_finished_job(pi);
8692 } else {
8693/*
8694 * bash deletes finished jobs from job table only in interactive mode,
8695 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8696 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8697 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8698 * We only retain one "dead" job, if it's the single job on the list.
8699 * This covers most of real-world scenarios where this is useful.
8700 */
8701 if (pi != G.job_list)
8702 delete_finished_job(pi);
8703 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008704 }
8705 } else {
8706 /* child stopped */
8707 pi->stopped_cmds++;
8708 }
8709#endif
8710 return -1; /* this wasn't a process from fg_pipe */
8711}
8712
8713/* Check to see if any processes have exited -- if they have,
8714 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008715 *
8716 * If non-NULL fg_pipe: wait for its completion or stop.
8717 * Return its exitcode or zero if stopped.
8718 *
8719 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8720 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8721 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8722 * or 0 if no children changed status.
8723 *
8724 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8725 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8726 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008727 */
8728static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8729{
8730 int attributes;
8731 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008732 int rcode = 0;
8733
8734 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8735
8736 attributes = WUNTRACED;
8737 if (fg_pipe == NULL)
8738 attributes |= WNOHANG;
8739
8740 errno = 0;
8741#if ENABLE_HUSH_FAST
8742 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8743//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8744//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8745 /* There was neither fork nor SIGCHLD since last waitpid */
8746 /* Avoid doing waitpid syscall if possible */
8747 if (!G.we_have_children) {
8748 errno = ECHILD;
8749 return -1;
8750 }
8751 if (fg_pipe == NULL) { /* is WNOHANG set? */
8752 /* We have children, but they did not exit
8753 * or stop yet (we saw no SIGCHLD) */
8754 return 0;
8755 }
8756 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8757 }
8758#endif
8759
8760/* Do we do this right?
8761 * bash-3.00# sleep 20 | false
8762 * <ctrl-Z pressed>
8763 * [3]+ Stopped sleep 20 | false
8764 * bash-3.00# echo $?
8765 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8766 * [hush 1.14.0: yes we do it right]
8767 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008768 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008769 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008770#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008771 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008772 i = G.count_SIGCHLD;
8773#endif
8774 childpid = waitpid(-1, &status, attributes);
8775 if (childpid <= 0) {
8776 if (childpid && errno != ECHILD)
8777 bb_perror_msg("waitpid");
8778#if ENABLE_HUSH_FAST
8779 else { /* Until next SIGCHLD, waitpid's are useless */
8780 G.we_have_children = (childpid == 0);
8781 G.handled_SIGCHLD = i;
8782//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8783 }
8784#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008785 /* ECHILD (no children), or 0 (no change in children status) */
8786 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008787 break;
8788 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008789 rcode = process_wait_result(fg_pipe, childpid, status);
8790 if (rcode >= 0) {
8791 /* fg_pipe exited or stopped */
8792 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008793 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008794 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008795 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008796 rcode = WEXITSTATUS(status);
8797 if (WIFSIGNALED(status))
8798 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008799 if (WIFSTOPPED(status))
8800 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8801 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008802 rcode++;
8803 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008804 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008805#if ENABLE_HUSH_BASH_COMPAT
8806 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8807 && G.dead_job_exitcode >= 0 /* some job did finish */
8808 ) {
8809 debug_printf_exec("waitfor_pid:-1\n");
8810 rcode = G.dead_job_exitcode + 1;
8811 break;
8812 }
8813#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008814 /* This wasn't one of our processes, or */
8815 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008816 } /* while (waitpid succeeds)... */
8817
8818 return rcode;
8819}
8820
8821#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008822static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008823{
8824 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008825 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008826 if (G_saved_tty_pgrp) {
8827 /* Job finished, move the shell to the foreground */
8828 p = getpgrp(); /* our process group id */
8829 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8830 tcsetpgrp(G_interactive_fd, p);
8831 }
8832 return rcode;
8833}
8834#endif
8835
8836/* Start all the jobs, but don't wait for anything to finish.
8837 * See checkjobs().
8838 *
8839 * Return code is normally -1, when the caller has to wait for children
8840 * to finish to determine the exit status of the pipe. If the pipe
8841 * is a simple builtin command, however, the action is done by the
8842 * time run_pipe returns, and the exit code is provided as the
8843 * return value.
8844 *
8845 * Returns -1 only if started some children. IOW: we have to
8846 * mask out retvals of builtins etc with 0xff!
8847 *
8848 * The only case when we do not need to [v]fork is when the pipe
8849 * is single, non-backgrounded, non-subshell command. Examples:
8850 * cmd ; ... { list } ; ...
8851 * cmd && ... { list } && ...
8852 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008853 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008854 * or (if SH_STANDALONE) an applet, and we can run the { list }
8855 * with run_list. If it isn't one of these, we fork and exec cmd.
8856 *
8857 * Cases when we must fork:
8858 * non-single: cmd | cmd
8859 * backgrounded: cmd & { list } &
8860 * subshell: ( list ) [&]
8861 */
8862#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008863#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8864 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008865#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008866static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008867 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008868 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008869 char **argv_expanded)
8870{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008871 /* Assignments occur before redirects. Try:
8872 * a=`sleep 1` sleep 2 3>/qwe/rty
8873 */
8874
8875 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8876 dump_cmd_in_x_mode(new_env);
8877 dump_cmd_in_x_mode(argv_expanded);
8878 /* this takes ownership of new_env[i] elements, and frees new_env: */
8879 set_vars_and_save_old(new_env);
8880
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008881 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008882}
8883static NOINLINE int run_pipe(struct pipe *pi)
8884{
8885 static const char *const null_ptr = NULL;
8886
8887 int cmd_no;
8888 int next_infd;
8889 struct command *command;
8890 char **argv_expanded;
8891 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008892 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008893 int rcode;
8894
8895 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8896 debug_enter();
8897
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008898 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8899 * Result should be 3 lines: q w e, qwe, q w e
8900 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008901 if (G.ifs_whitespace != G.ifs)
8902 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008903 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008904 if (G.ifs) {
8905 char *p;
8906 G.ifs_whitespace = (char*)G.ifs;
8907 p = skip_whitespace(G.ifs);
8908 if (*p) {
8909 /* Not all $IFS is whitespace */
8910 char *d;
8911 int len = p - G.ifs;
8912 p = skip_non_whitespace(p);
8913 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8914 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8915 while (*p) {
8916 if (isspace(*p))
8917 *d++ = *p;
8918 p++;
8919 }
8920 *d = '\0';
8921 }
8922 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008923 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008924 G.ifs_whitespace = (char*)G.ifs;
8925 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008926
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008927 IF_HUSH_JOB(pi->pgrp = -1;)
8928 pi->stopped_cmds = 0;
8929 command = &pi->cmds[0];
8930 argv_expanded = NULL;
8931
8932 if (pi->num_cmds != 1
8933 || pi->followup == PIPE_BG
8934 || command->cmd_type == CMD_SUBSHELL
8935 ) {
8936 goto must_fork;
8937 }
8938
8939 pi->alive_cmds = 1;
8940
8941 debug_printf_exec(": group:%p argv:'%s'\n",
8942 command->group, command->argv ? command->argv[0] : "NONE");
8943
8944 if (command->group) {
8945#if ENABLE_HUSH_FUNCTIONS
8946 if (command->cmd_type == CMD_FUNCDEF) {
8947 /* "executing" func () { list } */
8948 struct function *funcp;
8949
8950 funcp = new_function(command->argv[0]);
8951 /* funcp->name is already set to argv[0] */
8952 funcp->body = command->group;
8953# if !BB_MMU
8954 funcp->body_as_string = command->group_as_string;
8955 command->group_as_string = NULL;
8956# endif
8957 command->group = NULL;
8958 command->argv[0] = NULL;
8959 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8960 funcp->parent_cmd = command;
8961 command->child_func = funcp;
8962
8963 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8964 debug_leave();
8965 return EXIT_SUCCESS;
8966 }
8967#endif
8968 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008969 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008970 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008971 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008972 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008973//FIXME: we need to pass squirrel down into run_list()
8974//for SH_STANDALONE case, or else this construct:
8975// { find /proc/self/fd; true; } >FILE; cmd2
8976//has no way of closing saved fd#1 for "find",
8977//and in SH_STANDALONE mode, "find" is not execed,
8978//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008979 rcode = run_list(command->group) & 0xff;
8980 }
8981 restore_redirects(squirrel);
8982 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8983 debug_leave();
8984 debug_printf_exec("run_pipe: return %d\n", rcode);
8985 return rcode;
8986 }
8987
8988 argv = command->argv ? command->argv : (char **) &null_ptr;
8989 {
8990 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008991 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8992 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008993 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008994 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008995
Denys Vlasenko5807e182018-02-08 19:19:04 +01008996#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02008997 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008998#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008999
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009000 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009001 /* Assignments, but no command.
9002 * Ensure redirects take effect (that is, create files).
9003 * Try "a=t >file"
9004 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009005 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009006 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009007 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009008 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009009 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009010
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009011 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009012 i = 0;
9013 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009014 char *p = expand_string_to_string(argv[i],
9015 EXP_FLAG_ESC_GLOB_CHARS,
9016 /*unbackslash:*/ 1
9017 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009018#if ENABLE_HUSH_MODE_X
9019 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009020 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009021 if (i == 0)
9022 x_mode_prefix();
9023 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009024 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009025 if (*eq) eq++;
9026 x_mode_addblock(p, (eq - p));
9027 x_mode_print_optionally_squoted(eq);
9028 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009029 }
9030#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009031 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009032 if (set_local_var(p, /*flag:*/ 0)) {
9033 /* assignment to readonly var / putenv error? */
9034 rcode = 1;
9035 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009036 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009037 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009038 /* Redirect error sets $? to 1. Otherwise,
9039 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009040 * Else, clear $?:
9041 * false; q=`exit 2`; echo $? - should print 2
9042 * false; x=1; echo $? - should print 0
9043 * Because of the 2nd case, we can't just use G.last_exitcode.
9044 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009045 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009046 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009047 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9048 debug_leave();
9049 debug_printf_exec("run_pipe: return %d\n", rcode);
9050 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009051 }
9052
9053 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02009054#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009055 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009056 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009057 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009058#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009059 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009060
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009061 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009062 if (!argv_expanded[0]) {
9063 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009064 /* `false` still has to set exitcode 1 */
9065 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009066 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009067 }
9068
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009069 old_vars = NULL;
9070 sv_shadowed = G.shadowed_vars_pp;
9071
Denys Vlasenko75481d32017-07-31 05:27:09 +02009072 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009073 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9074 IF_HUSH_FUNCTIONS(x = NULL;)
9075 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009076 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009077 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009078 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9079 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009080 /*
9081 * Variable assignments are executed, but then "forgotten":
9082 * a=`sleep 1;echo A` exec 3>&-; echo $a
9083 * sleeps, but prints nothing.
9084 */
9085 enter_var_nest_level();
9086 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009087 rcode = redirect_and_varexp_helper(command,
9088 /*squirrel:*/ ERR_PTR,
9089 argv_expanded
9090 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009091 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009092 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009093
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009094 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009095 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009096
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009097 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009098 * a=b true; env | grep ^a=
9099 */
9100 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009101 /* Collect all variables "shadowed" by helper
9102 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9103 * into old_vars list:
9104 */
9105 G.shadowed_vars_pp = &old_vars;
9106 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009107 if (rcode == 0) {
9108 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009109 /* Do not collect *to old_vars list* vars shadowed
9110 * by e.g. "local VAR" builtin (collect them
9111 * in the previously nested list instead):
9112 * don't want them to be restored immediately
9113 * after "local" completes.
9114 */
9115 G.shadowed_vars_pp = sv_shadowed;
9116
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009117 debug_printf_exec(": builtin '%s' '%s'...\n",
9118 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009119 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009120 rcode = x->b_function(argv_expanded) & 0xff;
9121 fflush_all();
9122 }
9123#if ENABLE_HUSH_FUNCTIONS
9124 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009125 debug_printf_exec(": function '%s' '%s'...\n",
9126 funcp->name, argv_expanded[1]);
9127 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009128 /*
9129 * But do collect *to old_vars list* vars shadowed
9130 * within function execution. To that end, restore
9131 * this pointer _after_ function run:
9132 */
9133 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009134 }
9135#endif
9136 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009137 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009138 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009139 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009140 if (n < 0 || !APPLET_IS_NOFORK(n))
9141 goto must_fork;
9142
9143 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009144 /* Collect all variables "shadowed" by helper into old_vars list */
9145 G.shadowed_vars_pp = &old_vars;
9146 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9147 G.shadowed_vars_pp = sv_shadowed;
9148
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009149 if (rcode == 0) {
9150 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9151 argv_expanded[0], argv_expanded[1]);
9152 /*
9153 * Note: signals (^C) can't interrupt here.
9154 * We remember them and they will be acted upon
9155 * after applet returns.
9156 * This makes applets which can run for a long time
9157 * and/or wait for user input ineligible for NOFORK:
9158 * for example, "yes" or "rm" (rm -i waits for input).
9159 */
9160 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009161 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009162 } else
9163 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009164
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009165 restore_redirects(squirrel);
9166 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009167 leave_var_nest_level();
9168 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009169
9170 /*
9171 * Try "usleep 99999999" + ^C + "echo $?"
9172 * with FEATURE_SH_NOFORK=y.
9173 */
9174 if (!funcp) {
9175 /* It was builtin or nofork.
9176 * if this would be a real fork/execed program,
9177 * it should have died if a fatal sig was received.
9178 * But OTOH, there was no separate process,
9179 * the sig was sent to _shell_, not to non-existing
9180 * child.
9181 * Let's just handle ^C only, this one is obvious:
9182 * we aren't ok with exitcode 0 when ^C was pressed
9183 * during builtin/nofork.
9184 */
9185 if (sigismember(&G.pending_set, SIGINT))
9186 rcode = 128 + SIGINT;
9187 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009188 free(argv_expanded);
9189 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9190 debug_leave();
9191 debug_printf_exec("run_pipe return %d\n", rcode);
9192 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009193 }
9194
9195 must_fork:
9196 /* NB: argv_expanded may already be created, and that
9197 * might include `cmd` runs! Do not rerun it! We *must*
9198 * use argv_expanded if it's non-NULL */
9199
9200 /* Going to fork a child per each pipe member */
9201 pi->alive_cmds = 0;
9202 next_infd = 0;
9203
9204 cmd_no = 0;
9205 while (cmd_no < pi->num_cmds) {
9206 struct fd_pair pipefds;
9207#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009208 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009209 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009210 nommu_save.old_vars = NULL;
9211 nommu_save.argv = NULL;
9212 nommu_save.argv_from_re_execing = NULL;
9213#endif
9214 command = &pi->cmds[cmd_no];
9215 cmd_no++;
9216 if (command->argv) {
9217 debug_printf_exec(": pipe member '%s' '%s'...\n",
9218 command->argv[0], command->argv[1]);
9219 } else {
9220 debug_printf_exec(": pipe member with no argv\n");
9221 }
9222
9223 /* pipes are inserted between pairs of commands */
9224 pipefds.rd = 0;
9225 pipefds.wr = 1;
9226 if (cmd_no < pi->num_cmds)
9227 xpiped_pair(pipefds);
9228
Denys Vlasenko5807e182018-02-08 19:19:04 +01009229#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009230 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009231#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009232
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009233 command->pid = BB_MMU ? fork() : vfork();
9234 if (!command->pid) { /* child */
9235#if ENABLE_HUSH_JOB
9236 disable_restore_tty_pgrp_on_exit();
9237 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9238
9239 /* Every child adds itself to new process group
9240 * with pgid == pid_of_first_child_in_pipe */
9241 if (G.run_list_level == 1 && G_interactive_fd) {
9242 pid_t pgrp;
9243 pgrp = pi->pgrp;
9244 if (pgrp < 0) /* true for 1st process only */
9245 pgrp = getpid();
9246 if (setpgid(0, pgrp) == 0
9247 && pi->followup != PIPE_BG
9248 && G_saved_tty_pgrp /* we have ctty */
9249 ) {
9250 /* We do it in *every* child, not just first,
9251 * to avoid races */
9252 tcsetpgrp(G_interactive_fd, pgrp);
9253 }
9254 }
9255#endif
9256 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9257 /* 1st cmd in backgrounded pipe
9258 * should have its stdin /dev/null'ed */
9259 close(0);
9260 if (open(bb_dev_null, O_RDONLY))
9261 xopen("/", O_RDONLY);
9262 } else {
9263 xmove_fd(next_infd, 0);
9264 }
9265 xmove_fd(pipefds.wr, 1);
9266 if (pipefds.rd > 1)
9267 close(pipefds.rd);
9268 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009269 * and the pipe fd (fd#1) is available for dup'ing:
9270 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9271 * of cmd1 goes into pipe.
9272 */
9273 if (setup_redirects(command, NULL)) {
9274 /* Happens when redir file can't be opened:
9275 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9276 * FOO
9277 * hush: can't open '/qwe/rty': No such file or directory
9278 * BAZ
9279 * (echo BAR is not executed, it hits _exit(1) below)
9280 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009281 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009282 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009283
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009284 /* Stores to nommu_save list of env vars putenv'ed
9285 * (NOMMU, on MMU we don't need that) */
9286 /* cast away volatility... */
9287 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9288 /* pseudo_exec() does not return */
9289 }
9290
9291 /* parent or error */
9292#if ENABLE_HUSH_FAST
9293 G.count_SIGCHLD++;
9294//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9295#endif
9296 enable_restore_tty_pgrp_on_exit();
9297#if !BB_MMU
9298 /* Clean up after vforked child */
9299 free(nommu_save.argv);
9300 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009301 G.var_nest_level = sv_var_nest_level;
9302 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009303 add_vars(nommu_save.old_vars);
9304#endif
9305 free(argv_expanded);
9306 argv_expanded = NULL;
9307 if (command->pid < 0) { /* [v]fork failed */
9308 /* Clearly indicate, was it fork or vfork */
9309 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9310 } else {
9311 pi->alive_cmds++;
9312#if ENABLE_HUSH_JOB
9313 /* Second and next children need to know pid of first one */
9314 if (pi->pgrp < 0)
9315 pi->pgrp = command->pid;
9316#endif
9317 }
9318
9319 if (cmd_no > 1)
9320 close(next_infd);
9321 if (cmd_no < pi->num_cmds)
9322 close(pipefds.wr);
9323 /* Pass read (output) pipe end to next iteration */
9324 next_infd = pipefds.rd;
9325 }
9326
9327 if (!pi->alive_cmds) {
9328 debug_leave();
9329 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9330 return 1;
9331 }
9332
9333 debug_leave();
9334 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9335 return -1;
9336}
9337
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009338/* NB: called by pseudo_exec, and therefore must not modify any
9339 * global data until exec/_exit (we can be a child after vfork!) */
9340static int run_list(struct pipe *pi)
9341{
9342#if ENABLE_HUSH_CASE
9343 char *case_word = NULL;
9344#endif
9345#if ENABLE_HUSH_LOOPS
9346 struct pipe *loop_top = NULL;
9347 char **for_lcur = NULL;
9348 char **for_list = NULL;
9349#endif
9350 smallint last_followup;
9351 smalluint rcode;
9352#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9353 smalluint cond_code = 0;
9354#else
9355 enum { cond_code = 0 };
9356#endif
9357#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009358 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009359 smallint last_rword; /* ditto */
9360#endif
9361
9362 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9363 debug_enter();
9364
9365#if ENABLE_HUSH_LOOPS
9366 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009367 {
9368 struct pipe *cpipe;
9369 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9370 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9371 continue;
9372 /* current word is FOR or IN (BOLD in comments below) */
9373 if (cpipe->next == NULL) {
9374 syntax_error("malformed for");
9375 debug_leave();
9376 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9377 return 1;
9378 }
9379 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9380 if (cpipe->next->res_word == RES_DO)
9381 continue;
9382 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9383 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9384 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9385 ) {
9386 syntax_error("malformed for");
9387 debug_leave();
9388 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9389 return 1;
9390 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009391 }
9392 }
9393#endif
9394
9395 /* Past this point, all code paths should jump to ret: label
9396 * in order to return, no direct "return" statements please.
9397 * This helps to ensure that no memory is leaked. */
9398
9399#if ENABLE_HUSH_JOB
9400 G.run_list_level++;
9401#endif
9402
9403#if HAS_KEYWORDS
9404 rword = RES_NONE;
9405 last_rword = RES_XXXX;
9406#endif
9407 last_followup = PIPE_SEQ;
9408 rcode = G.last_exitcode;
9409
9410 /* Go through list of pipes, (maybe) executing them. */
9411 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009412 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009413 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009414
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009415 if (G.flag_SIGINT)
9416 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009417 if (G_flag_return_in_progress == 1)
9418 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009419
9420 IF_HAS_KEYWORDS(rword = pi->res_word;)
9421 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9422 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009423
9424 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009425 if (
9426#if ENABLE_HUSH_IF
9427 rword == RES_IF || rword == RES_ELIF ||
9428#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009429 pi->followup != PIPE_SEQ
9430 ) {
9431 G.errexit_depth++;
9432 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009433#if ENABLE_HUSH_LOOPS
9434 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9435 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9436 ) {
9437 /* start of a loop: remember where loop starts */
9438 loop_top = pi;
9439 G.depth_of_loop++;
9440 }
9441#endif
9442 /* Still in the same "if...", "then..." or "do..." branch? */
9443 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9444 if ((rcode == 0 && last_followup == PIPE_OR)
9445 || (rcode != 0 && last_followup == PIPE_AND)
9446 ) {
9447 /* It is "<true> || CMD" or "<false> && CMD"
9448 * and we should not execute CMD */
9449 debug_printf_exec("skipped cmd because of || or &&\n");
9450 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009451 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009452 }
9453 }
9454 last_followup = pi->followup;
9455 IF_HAS_KEYWORDS(last_rword = rword;)
9456#if ENABLE_HUSH_IF
9457 if (cond_code) {
9458 if (rword == RES_THEN) {
9459 /* if false; then ... fi has exitcode 0! */
9460 G.last_exitcode = rcode = EXIT_SUCCESS;
9461 /* "if <false> THEN cmd": skip cmd */
9462 continue;
9463 }
9464 } else {
9465 if (rword == RES_ELSE || rword == RES_ELIF) {
9466 /* "if <true> then ... ELSE/ELIF cmd":
9467 * skip cmd and all following ones */
9468 break;
9469 }
9470 }
9471#endif
9472#if ENABLE_HUSH_LOOPS
9473 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9474 if (!for_lcur) {
9475 /* first loop through for */
9476
9477 static const char encoded_dollar_at[] ALIGN1 = {
9478 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9479 }; /* encoded representation of "$@" */
9480 static const char *const encoded_dollar_at_argv[] = {
9481 encoded_dollar_at, NULL
9482 }; /* argv list with one element: "$@" */
9483 char **vals;
9484
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009485 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009486 vals = (char**)encoded_dollar_at_argv;
9487 if (pi->next->res_word == RES_IN) {
9488 /* if no variable values after "in" we skip "for" */
9489 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009490 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9491 break;
9492 }
9493 vals = pi->next->cmds[0].argv;
9494 } /* else: "for var; do..." -> assume "$@" list */
9495 /* create list of variable values */
9496 debug_print_strings("for_list made from", vals);
9497 for_list = expand_strvec_to_strvec(vals);
9498 for_lcur = for_list;
9499 debug_print_strings("for_list", for_list);
9500 }
9501 if (!*for_lcur) {
9502 /* "for" loop is over, clean up */
9503 free(for_list);
9504 for_list = NULL;
9505 for_lcur = NULL;
9506 break;
9507 }
9508 /* Insert next value from for_lcur */
9509 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009510 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009511 continue;
9512 }
9513 if (rword == RES_IN) {
9514 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9515 }
9516 if (rword == RES_DONE) {
9517 continue; /* "done" has no cmds too */
9518 }
9519#endif
9520#if ENABLE_HUSH_CASE
9521 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009522 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009523 case_word = expand_string_to_string(pi->cmds->argv[0],
9524 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009525 debug_printf_exec("CASE word1:'%s'\n", case_word);
9526 //unbackslash(case_word);
9527 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009528 continue;
9529 }
9530 if (rword == RES_MATCH) {
9531 char **argv;
9532
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009533 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009534 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9535 break;
9536 /* all prev words didn't match, does this one match? */
9537 argv = pi->cmds->argv;
9538 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009539 char *pattern;
9540 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9541 pattern = expand_string_to_string(*argv,
9542 EXP_FLAG_ESC_GLOB_CHARS,
9543 /*unbackslash:*/ 0
9544 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009545 /* TODO: which FNM_xxx flags to use? */
9546 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009547 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9548 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009549 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009550 if (cond_code == 0) {
9551 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009552 free(case_word);
9553 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009554 break;
9555 }
9556 argv++;
9557 }
9558 continue;
9559 }
9560 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009561 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009562 if (cond_code != 0)
9563 continue; /* not matched yet, skip this pipe */
9564 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009565 if (rword == RES_ESAC) {
9566 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9567 if (case_word) {
9568 /* "case" did not match anything: still set $? (to 0) */
9569 G.last_exitcode = rcode = EXIT_SUCCESS;
9570 }
9571 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009572#endif
9573 /* Just pressing <enter> in shell should check for jobs.
9574 * OTOH, in non-interactive shell this is useless
9575 * and only leads to extra job checks */
9576 if (pi->num_cmds == 0) {
9577 if (G_interactive_fd)
9578 goto check_jobs_and_continue;
9579 continue;
9580 }
9581
9582 /* After analyzing all keywords and conditions, we decided
9583 * to execute this pipe. NB: have to do checkjobs(NULL)
9584 * after run_pipe to collect any background children,
9585 * even if list execution is to be stopped. */
9586 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009587#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009588 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009589#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009590 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9591 if (r != -1) {
9592 /* We ran a builtin, function, or group.
9593 * rcode is already known
9594 * and we don't need to wait for anything. */
9595 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9596 G.last_exitcode = rcode;
9597 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009598#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009599 /* Was it "break" or "continue"? */
9600 if (G.flag_break_continue) {
9601 smallint fbc = G.flag_break_continue;
9602 /* We might fall into outer *loop*,
9603 * don't want to break it too */
9604 if (loop_top) {
9605 G.depth_break_continue--;
9606 if (G.depth_break_continue == 0)
9607 G.flag_break_continue = 0;
9608 /* else: e.g. "continue 2" should *break* once, *then* continue */
9609 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9610 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009611 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009612 break;
9613 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009614 /* "continue": simulate end of loop */
9615 rword = RES_DONE;
9616 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009617 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009618#endif
9619 if (G_flag_return_in_progress == 1) {
9620 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9621 break;
9622 }
9623 } else if (pi->followup == PIPE_BG) {
9624 /* What does bash do with attempts to background builtins? */
9625 /* even bash 3.2 doesn't do that well with nested bg:
9626 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9627 * I'm NOT treating inner &'s as jobs */
9628#if ENABLE_HUSH_JOB
9629 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009630 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009631#endif
9632 /* Last command's pid goes to $! */
9633 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009634 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009635 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009636/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009637 rcode = EXIT_SUCCESS;
9638 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009639 } else {
9640#if ENABLE_HUSH_JOB
9641 if (G.run_list_level == 1 && G_interactive_fd) {
9642 /* Waits for completion, then fg's main shell */
9643 rcode = checkjobs_and_fg_shell(pi);
9644 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009645 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009646 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009647#endif
9648 /* This one just waits for completion */
9649 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9650 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9651 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009652 G.last_exitcode = rcode;
9653 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009654 }
9655
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009656 /* Handle "set -e" */
9657 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9658 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9659 if (G.errexit_depth == 0)
9660 hush_exit(rcode);
9661 }
9662 G.errexit_depth = sv_errexit_depth;
9663
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009664 /* Analyze how result affects subsequent commands */
9665#if ENABLE_HUSH_IF
9666 if (rword == RES_IF || rword == RES_ELIF)
9667 cond_code = rcode;
9668#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009669 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009670 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009671 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009672#if ENABLE_HUSH_LOOPS
9673 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009674 if (pi->next
9675 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009676 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009677 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009678 if (rword == RES_WHILE) {
9679 if (rcode) {
9680 /* "while false; do...done" - exitcode 0 */
9681 G.last_exitcode = rcode = EXIT_SUCCESS;
9682 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009683 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009684 }
9685 }
9686 if (rword == RES_UNTIL) {
9687 if (!rcode) {
9688 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009689 break;
9690 }
9691 }
9692 }
9693#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009694 } /* for (pi) */
9695
9696#if ENABLE_HUSH_JOB
9697 G.run_list_level--;
9698#endif
9699#if ENABLE_HUSH_LOOPS
9700 if (loop_top)
9701 G.depth_of_loop--;
9702 free(for_list);
9703#endif
9704#if ENABLE_HUSH_CASE
9705 free(case_word);
9706#endif
9707 debug_leave();
9708 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9709 return rcode;
9710}
9711
9712/* Select which version we will use */
9713static int run_and_free_list(struct pipe *pi)
9714{
9715 int rcode = 0;
9716 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009717 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009718 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9719 rcode = run_list(pi);
9720 }
9721 /* free_pipe_list has the side effect of clearing memory.
9722 * In the long run that function can be merged with run_list,
9723 * but doing that now would hobble the debugging effort. */
9724 free_pipe_list(pi);
9725 debug_printf_exec("run_and_free_list return %d\n", rcode);
9726 return rcode;
9727}
9728
9729
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009730static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009731{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009732 sighandler_t old_handler;
9733 unsigned sig = 0;
9734 while ((mask >>= 1) != 0) {
9735 sig++;
9736 if (!(mask & 1))
9737 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009738 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009739 /* POSIX allows shell to re-enable SIGCHLD
9740 * even if it was SIG_IGN on entry.
9741 * Therefore we skip IGN check for it:
9742 */
9743 if (sig == SIGCHLD)
9744 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009745 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9746 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9747 */
9748 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009749 if (old_handler == SIG_IGN) {
9750 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009751 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009752#if ENABLE_HUSH_TRAP
9753 if (!G_traps)
9754 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9755 free(G_traps[sig]);
9756 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9757#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009758 }
9759 }
9760}
9761
9762/* Called a few times only (or even once if "sh -c") */
9763static void install_special_sighandlers(void)
9764{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009765 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009766
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009767 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009768 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009769 if (G_interactive_fd) {
9770 mask |= SPECIAL_INTERACTIVE_SIGS;
9771 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009772 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009773 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009774 /* Careful, do not re-install handlers we already installed */
9775 if (G.special_sig_mask != mask) {
9776 unsigned diff = mask & ~G.special_sig_mask;
9777 G.special_sig_mask = mask;
9778 install_sighandlers(diff);
9779 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009780}
9781
9782#if ENABLE_HUSH_JOB
9783/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009784/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009785static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009786{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009787 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009788
9789 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009790 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009791 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9792 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009793 + (1 << SIGBUS ) * HUSH_DEBUG
9794 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009795 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009796 + (1 << SIGABRT)
9797 /* bash 3.2 seems to handle these just like 'fatal' ones */
9798 + (1 << SIGPIPE)
9799 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009800 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009801 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009802 * we never want to restore pgrp on exit, and this fn is not called
9803 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009804 /*+ (1 << SIGHUP )*/
9805 /*+ (1 << SIGTERM)*/
9806 /*+ (1 << SIGINT )*/
9807 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009808 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009809
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009810 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009811}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009812#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009813
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009814static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009815{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009816 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009817 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009818 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009819 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009820 break;
9821 case 'x':
9822 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009823 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 +01009824 break;
9825 case 'o':
9826 if (!o_opt) {
9827 /* "set -+o" without parameter.
9828 * in bash, set -o produces this output:
9829 * pipefail off
9830 * and set +o:
9831 * set +o pipefail
9832 * We always use the second form.
9833 */
9834 const char *p = o_opt_strings;
9835 idx = 0;
9836 while (*p) {
9837 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9838 idx++;
9839 p += strlen(p) + 1;
9840 }
9841 break;
9842 }
9843 idx = index_in_strings(o_opt_strings, o_opt);
9844 if (idx >= 0) {
9845 G.o_opt[idx] = state;
9846 break;
9847 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009848 case 'e':
9849 G.o_opt[OPT_O_ERREXIT] = state;
9850 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009851 default:
9852 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009853 }
9854 return EXIT_SUCCESS;
9855}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009856
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009857int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009858int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009859{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009860 enum {
9861 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009862 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009863 };
9864 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009865 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009866 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009867 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009868 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009869
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009870 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009871 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009872 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009873
Denys Vlasenko10c01312011-05-11 11:49:21 +02009874#if ENABLE_HUSH_FAST
9875 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9876#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009877#if !BB_MMU
9878 G.argv0_for_re_execing = argv[0];
9879#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009880
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009881 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009882 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9883 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009884 shell_ver = xzalloc(sizeof(*shell_ver));
9885 shell_ver->flg_export = 1;
9886 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009887 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009888 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009889 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009890
Denys Vlasenko605067b2010-09-06 12:10:51 +02009891 /* Create shell local variables from the values
9892 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009893 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009894 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009895 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009896 if (e) while (*e) {
9897 char *value = strchr(*e, '=');
9898 if (value) { /* paranoia */
9899 cur_var->next = xzalloc(sizeof(*cur_var));
9900 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009901 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009902 cur_var->max_len = strlen(*e);
9903 cur_var->flg_export = 1;
9904 }
9905 e++;
9906 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009907 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009908 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9909 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009910
9911 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009912 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009913
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009914#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009915 /* Set (but not export) HOSTNAME unless already set */
9916 if (!get_local_var_value("HOSTNAME")) {
9917 struct utsname uts;
9918 uname(&uts);
9919 set_local_var_from_halves("HOSTNAME", uts.nodename);
9920 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02009921#endif
9922 /* IFS is not inherited from the parent environment */
9923 set_local_var_from_halves("IFS", defifs);
9924
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02009925 if (!get_local_var_value("PATH"))
9926 set_local_var_from_halves("PATH", bb_default_root_path);
9927
Denys Vlasenko0c360192019-05-19 15:37:50 +02009928 /* PS1/PS2 are set later, if we determine that we are interactive */
9929
Denys Vlasenko6db47842009-09-05 20:15:17 +02009930 /* bash also exports SHLVL and _,
9931 * and sets (but doesn't export) the following variables:
9932 * BASH=/bin/bash
9933 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9934 * BASH_VERSION='3.2.0(1)-release'
9935 * HOSTTYPE=i386
9936 * MACHTYPE=i386-pc-linux-gnu
9937 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009938 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009939 * EUID=<NNNNN>
9940 * UID=<NNNNN>
9941 * GROUPS=()
9942 * LINES=<NNN>
9943 * COLUMNS=<NNN>
9944 * BASH_ARGC=()
9945 * BASH_ARGV=()
9946 * BASH_LINENO=()
9947 * BASH_SOURCE=()
9948 * DIRSTACK=()
9949 * PIPESTATUS=([0]="0")
9950 * HISTFILE=/<xxx>/.bash_history
9951 * HISTFILESIZE=500
9952 * HISTSIZE=500
9953 * MAILCHECK=60
9954 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9955 * SHELL=/bin/bash
9956 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9957 * TERM=dumb
9958 * OPTERR=1
9959 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +02009960 * PS4='+ '
9961 */
9962
Eric Andersen94ac2442001-05-22 19:05:18 +00009963 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009964 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009965
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009966 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009967 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009968 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009969 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009970 * in order to intercept (more) signals.
9971 */
9972
9973 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009974 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009975 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009976 builtin_argc = 0;
Ron Yorston71df2d32018-11-27 14:34:25 +00009977#if NUM_SCRIPTS > 0
9978 if (argc < 0) {
9979 optarg = get_script_content(-argc - 1);
9980 optind = 0;
9981 argc = string_array_len(argv);
9982 goto run_script;
9983 }
9984#endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009985 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009986 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009987#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009988 "<:$:R:V:"
9989# if ENABLE_HUSH_FUNCTIONS
9990 "F:"
9991# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009992#endif
9993 );
9994 if (opt <= 0)
9995 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009996 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009997 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009998 /* Possibilities:
9999 * sh ... -c 'script'
10000 * sh ... -c 'script' ARG0 [ARG1...]
10001 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +010010002 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010003 * "" needs to be replaced with NULL
10004 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +010010005 * Note: the form without ARG0 never happens:
10006 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010007 */
Ron Yorston71df2d32018-11-27 14:34:25 +000010008#if NUM_SCRIPTS > 0
10009 run_script:
10010#endif
Denys Vlasenkodea47882009-10-09 15:40:49 +020010011 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010012 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010013 G.root_ppid = getppid();
10014 }
Denis Vlasenko87a86552008-07-29 19:43:10 +000010015 G.global_argv = argv + optind;
10016 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010017 if (builtin_argc) {
10018 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10019 const struct built_in_command *x;
10020
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010021 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010022 x = find_builtin(optarg);
10023 if (x) { /* paranoia */
10024 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10025 G.global_argv += builtin_argc;
10026 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +010010027 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +010010028 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010029 }
10030 goto final_return;
10031 }
10032 if (!G.global_argv[0]) {
10033 /* -c 'script' (no params): prevent empty $0 */
10034 G.global_argv--; /* points to argv[i] of 'script' */
10035 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +020010036 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010037 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010038 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010039 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010040 goto final_return;
10041 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010042 /* Well, we cannot just declare interactiveness,
10043 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010044 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010045 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010046 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010047 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010048 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010049 case 'l':
10050 flags |= OPT_login;
10051 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010052#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010053 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010054 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010055 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010056 case '$': {
10057 unsigned long long empty_trap_mask;
10058
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010059 G.root_pid = bb_strtou(optarg, &optarg, 16);
10060 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010061 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10062 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010063 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10064 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010065 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010066 optarg++;
10067 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010068 optarg++;
10069 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10070 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010071 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010072 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010073# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010074 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010075 for (sig = 1; sig < NSIG; sig++) {
10076 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010077 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010078 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010079 }
10080 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010081# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010082 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010083# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010084 optarg++;
10085 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010086# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010087# if ENABLE_HUSH_FUNCTIONS
10088 /* nommu uses re-exec trick for "... | func | ...",
10089 * should allow "return".
10090 * This accidentally allows returns in subshells.
10091 */
10092 G_flag_return_in_progress = -1;
10093# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010094 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010095 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010096 case 'R':
10097 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010098 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010099 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010100# if ENABLE_HUSH_FUNCTIONS
10101 case 'F': {
10102 struct function *funcp = new_function(optarg);
10103 /* funcp->name is already set to optarg */
10104 /* funcp->body is set to NULL. It's a special case. */
10105 funcp->body_as_string = argv[optind];
10106 optind++;
10107 break;
10108 }
10109# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010110#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010111 case 'n':
10112 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010113 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010114 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010115 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010116 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010117#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010118 fprintf(stderr, "Usage: sh [FILE]...\n"
10119 " or: sh -c command [args]...\n\n");
10120 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010121#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010122 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010123#endif
Eric Andersen25f27032001-04-26 23:22:31 +000010124 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010125 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010126
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010127 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10128 G.global_argc = argc - (optind - 1);
10129 G.global_argv = argv + (optind - 1);
10130 G.global_argv[0] = argv[0];
10131
Denys Vlasenkodea47882009-10-09 15:40:49 +020010132 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010133 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010134 G.root_ppid = getppid();
10135 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010136
10137 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010138 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010139 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010140 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010141 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010142 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010143 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010144 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010145 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010146 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010147 /* bash: after sourcing /etc/profile,
10148 * tries to source (in the given order):
10149 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010150 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010151 * bash also sources ~/.bash_logout on exit.
10152 * If called as sh, skips .bash_XXX files.
10153 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010154 }
10155
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010156 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10157 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010158 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010159 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010160 * "bash <script>" (which is never interactive (unless -i?))
10161 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010162 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010163 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010164 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010165 G.global_argc--;
10166 G.global_argv++;
10167 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010168 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010169 input = hfopen(G.global_argv[0]);
10170 if (!input) {
10171 bb_simple_perror_msg_and_die(G.global_argv[0]);
10172 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010173 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010174 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010175 parse_and_run_file(input);
10176#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010177 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010178#endif
10179 goto final_return;
10180 }
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010181 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010182
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010183 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010184 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010185 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010186
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010187 /* A shell is interactive if the '-i' flag was given,
10188 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010189 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010190 * no arguments remaining or the -s flag given
10191 * standard input is a terminal
10192 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010193 * Refer to Posix.2, the description of the 'sh' utility.
10194 */
10195#if ENABLE_HUSH_JOB
10196 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010197 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10198 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10199 if (G_saved_tty_pgrp < 0)
10200 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010201
10202 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010203 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010204 if (G_interactive_fd < 0) {
10205 /* try to dup to any fd */
10206 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010207 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010208 /* give up */
10209 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010210 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010211 }
10212 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010213// TODO: track & disallow any attempts of user
10214// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010215 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010216 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010217 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010218 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010219
Mike Frysinger38478a62009-05-20 04:48:06 -040010220 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010221 /* If we were run as 'hush &', sleep until we are
10222 * in the foreground (tty pgrp == our pgrp).
10223 * If we get started under a job aware app (like bash),
10224 * make sure we are now in charge so we don't fight over
10225 * who gets the foreground */
10226 while (1) {
10227 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010228 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10229 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010230 break;
10231 /* send TTIN to ourself (should stop us) */
10232 kill(- shell_pgrp, SIGTTIN);
10233 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010234 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010235
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010236 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010237 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010238
Mike Frysinger38478a62009-05-20 04:48:06 -040010239 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010240 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010241 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010242 /* Put ourselves in our own process group
10243 * (bash, too, does this only if ctty is available) */
10244 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10245 /* Grab control of the terminal */
10246 tcsetpgrp(G_interactive_fd, getpid());
10247 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010248 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010249
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010250# if ENABLE_FEATURE_EDITING
10251 G.line_input_state = new_line_input_t(FOR_SHELL);
10252# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010253# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10254 {
10255 const char *hp = get_local_var_value("HISTFILE");
10256 if (!hp) {
10257 hp = get_local_var_value("HOME");
10258 if (hp)
10259 hp = concat_path_file(hp, ".hush_history");
10260 } else {
10261 hp = xstrdup(hp);
10262 }
10263 if (hp) {
10264 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010265 //set_local_var(xasprintf("HISTFILE=%s", ...));
10266 }
10267# if ENABLE_FEATURE_SH_HISTFILESIZE
10268 hp = get_local_var_value("HISTFILESIZE");
10269 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10270# endif
10271 }
10272# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010273 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010274 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010275 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010276#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010277 /* No job control compiled in, only prompt/line editing */
10278 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010279 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010280 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010281 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010282 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010283 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010284 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010285 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010286 }
10287 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010288 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010289 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010290 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010291 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010292#else
10293 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010294 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010295#endif
10296 /* bash:
10297 * if interactive but not a login shell, sources ~/.bashrc
10298 * (--norc turns this off, --rcfile <file> overrides)
10299 */
10300
Denys Vlasenko0c360192019-05-19 15:37:50 +020010301 if (G_interactive_fd) {
10302#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10303 /* Set (but not export) PS1/2 unless already set */
10304 if (!get_local_var_value("PS1"))
10305 set_local_var_from_halves("PS1", "\\w \\$ ");
10306 if (!get_local_var_value("PS2"))
10307 set_local_var_from_halves("PS2", "> ");
10308#endif
10309 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10310 /* note: ash and hush share this string */
10311 printf("\n\n%s %s\n"
10312 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10313 "\n",
10314 bb_banner,
10315 "hush - the humble shell"
10316 );
10317 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010318 }
10319
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010320 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010321
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010322 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010323 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010324}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010325
10326
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010327/*
10328 * Built-ins
10329 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010330static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010331{
10332 return 0;
10333}
10334
Denys Vlasenko265062d2017-01-10 15:13:30 +010010335#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010336static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010337{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010338 int argc = string_array_len(argv);
10339 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010340}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010341#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010342#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010343static int FAST_FUNC builtin_test(char **argv)
10344{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010345 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010346}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010347#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010348#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010349static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010350{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010351 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010352}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010353#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010354#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010355static int FAST_FUNC builtin_printf(char **argv)
10356{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010357 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010358}
10359#endif
10360
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010361#if ENABLE_HUSH_HELP
10362static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10363{
10364 const struct built_in_command *x;
10365
10366 printf(
10367 "Built-in commands:\n"
10368 "------------------\n");
10369 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10370 if (x->b_descr)
10371 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10372 }
10373 return EXIT_SUCCESS;
10374}
10375#endif
10376
10377#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10378static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10379{
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010380 if (G.line_input_state)
10381 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010382 return EXIT_SUCCESS;
10383}
10384#endif
10385
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010386static char **skip_dash_dash(char **argv)
10387{
10388 argv++;
10389 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10390 argv++;
10391 return argv;
10392}
10393
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010394static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010395{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010396 const char *newdir;
10397
10398 argv = skip_dash_dash(argv);
10399 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010400 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010401 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010402 * bash says "bash: cd: HOME not set" and does nothing
10403 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010404 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010405 const char *home = get_local_var_value("HOME");
10406 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010407 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010408 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010409 /* Mimic bash message exactly */
10410 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010411 return EXIT_FAILURE;
10412 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010413 /* Read current dir (get_cwd(1) is inside) and set PWD.
10414 * Note: do not enforce exporting. If PWD was unset or unexported,
10415 * set it again, but do not export. bash does the same.
10416 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010417 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010418 return EXIT_SUCCESS;
10419}
10420
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010421static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10422{
10423 puts(get_cwd(0));
10424 return EXIT_SUCCESS;
10425}
10426
10427static int FAST_FUNC builtin_eval(char **argv)
10428{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010429 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010430
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010431 if (!argv[0])
10432 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010433
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010434 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010435 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010436 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010437 /* bash:
10438 * eval "echo Hi; done" ("done" is syntax error):
10439 * "echo Hi" will not execute too.
10440 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010441 parse_and_run_string(argv[0]);
10442 } else {
10443 /* "The eval utility shall construct a command by
10444 * concatenating arguments together, separating
10445 * each with a <space> character."
10446 */
10447 char *str, *p;
10448 unsigned len = 0;
10449 char **pp = argv;
10450 do
10451 len += strlen(*pp) + 1;
10452 while (*++pp);
10453 str = p = xmalloc(len);
10454 pp = argv;
10455 for (;;) {
10456 p = stpcpy(p, *pp);
10457 pp++;
10458 if (!*pp)
10459 break;
10460 *p++ = ' ';
10461 }
10462 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010463 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010464 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010465 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010466 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010467 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010468}
10469
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010470static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010471{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010472 argv = skip_dash_dash(argv);
10473 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010474 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010475
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010476 /* Careful: we can end up here after [v]fork. Do not restore
10477 * tty pgrp then, only top-level shell process does that */
10478 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10479 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10480
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010481 /* Saved-redirect fds, script fds and G_interactive_fd are still
10482 * open here. However, they are all CLOEXEC, and execv below
10483 * closes them. Try interactive "exec ls -l /proc/self/fd",
10484 * it should show no extra open fds in the "ls" process.
10485 * If we'd try to run builtins/NOEXECs, this would need improving.
10486 */
10487 //close_saved_fds_and_FILE_fds();
10488
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010489 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010490 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010491 * and tcsetpgrp, and this is inherently racy.
10492 */
10493 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010494}
10495
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010496static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010498 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010499
10500 /* interactive bash:
10501 * # trap "echo EEE" EXIT
10502 * # exit
10503 * exit
10504 * There are stopped jobs.
10505 * (if there are _stopped_ jobs, running ones don't count)
10506 * # exit
10507 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010508 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010509 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010510 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010511 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010512
10513 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010514 argv = skip_dash_dash(argv);
10515 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010516 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010517 /* mimic bash: exit 123abc == exit 255 + error msg */
10518 xfunc_error_retval = 255;
10519 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010520 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010521}
10522
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010523#if ENABLE_HUSH_TYPE
10524/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10525static int FAST_FUNC builtin_type(char **argv)
10526{
10527 int ret = EXIT_SUCCESS;
10528
10529 while (*++argv) {
10530 const char *type;
10531 char *path = NULL;
10532
10533 if (0) {} /* make conditional compile easier below */
10534 /*else if (find_alias(*argv))
10535 type = "an alias";*/
10536#if ENABLE_HUSH_FUNCTIONS
10537 else if (find_function(*argv))
10538 type = "a function";
10539#endif
10540 else if (find_builtin(*argv))
10541 type = "a shell builtin";
10542 else if ((path = find_in_path(*argv)) != NULL)
10543 type = path;
10544 else {
10545 bb_error_msg("type: %s: not found", *argv);
10546 ret = EXIT_FAILURE;
10547 continue;
10548 }
10549
10550 printf("%s is %s\n", *argv, type);
10551 free(path);
10552 }
10553
10554 return ret;
10555}
10556#endif
10557
10558#if ENABLE_HUSH_READ
10559/* Interruptibility of read builtin in bash
10560 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10561 *
10562 * Empty trap makes read ignore corresponding signal, for any signal.
10563 *
10564 * SIGINT:
10565 * - terminates non-interactive shell;
10566 * - interrupts read in interactive shell;
10567 * if it has non-empty trap:
10568 * - executes trap and returns to command prompt in interactive shell;
10569 * - executes trap and returns to read in non-interactive shell;
10570 * SIGTERM:
10571 * - is ignored (does not interrupt) read in interactive shell;
10572 * - terminates non-interactive shell;
10573 * if it has non-empty trap:
10574 * - executes trap and returns to read;
10575 * SIGHUP:
10576 * - terminates shell (regardless of interactivity);
10577 * if it has non-empty trap:
10578 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010579 * SIGCHLD from children:
10580 * - does not interrupt read regardless of interactivity:
10581 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010582 */
10583static int FAST_FUNC builtin_read(char **argv)
10584{
10585 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010586 struct builtin_read_params params;
10587
10588 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010589
10590 /* "!": do not abort on errors.
10591 * Option string must start with "sr" to match BUILTIN_READ_xxx
10592 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010593 params.read_flags = getopt32(argv,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010594#if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010595 "!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 +020010596#else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010597 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010598#endif
10599 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010600 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010601 return EXIT_FAILURE;
10602 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010603 params.argv = argv;
10604 params.setvar = set_local_var_from_halves;
10605 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010606
10607 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010608 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010609
10610 if ((uintptr_t)r == 1 && errno == EINTR) {
10611 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010612 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010613 goto again;
10614 }
10615
10616 if ((uintptr_t)r > 1) {
10617 bb_error_msg("%s", r);
10618 r = (char*)(uintptr_t)1;
10619 }
10620
10621 return (uintptr_t)r;
10622}
10623#endif
10624
10625#if ENABLE_HUSH_UMASK
10626static int FAST_FUNC builtin_umask(char **argv)
10627{
10628 int rc;
10629 mode_t mask;
10630
10631 rc = 1;
10632 mask = umask(0);
10633 argv = skip_dash_dash(argv);
10634 if (argv[0]) {
10635 mode_t old_mask = mask;
10636
10637 /* numeric umasks are taken as-is */
10638 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10639 if (!isdigit(argv[0][0]))
10640 mask ^= 0777;
10641 mask = bb_parse_mode(argv[0], mask);
10642 if (!isdigit(argv[0][0]))
10643 mask ^= 0777;
10644 if ((unsigned)mask > 0777) {
10645 mask = old_mask;
10646 /* bash messages:
10647 * bash: umask: 'q': invalid symbolic mode operator
10648 * bash: umask: 999: octal number out of range
10649 */
10650 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10651 rc = 0;
10652 }
10653 } else {
10654 /* Mimic bash */
10655 printf("%04o\n", (unsigned) mask);
10656 /* fall through and restore mask which we set to 0 */
10657 }
10658 umask(mask);
10659
10660 return !rc; /* rc != 0 - success */
10661}
10662#endif
10663
Denys Vlasenko41ade052017-01-08 18:56:24 +010010664#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010665static void print_escaped(const char *s)
10666{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010667 if (*s == '\'')
10668 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010669 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010670 const char *p = strchrnul(s, '\'');
10671 /* print 'xxxx', possibly just '' */
10672 printf("'%.*s'", (int)(p - s), s);
10673 if (*p == '\0')
10674 break;
10675 s = p;
10676 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010677 /* s points to '; print "'''...'''" */
10678 putchar('"');
10679 do putchar('\''); while (*++s == '\'');
10680 putchar('"');
10681 } while (*s);
10682}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010683#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010684
Denys Vlasenko1e660422017-07-17 21:10:50 +020010685#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010686static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010687{
10688 do {
10689 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010690 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010691
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010692 if (*name_end == '\0') {
10693 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010694
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010695 vpp = get_ptr_to_local_var(name, name_end - name);
10696 var = vpp ? *vpp : NULL;
10697
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010698 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010699 /* export -n NAME (without =VALUE) */
10700 if (var) {
10701 var->flg_export = 0;
10702 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10703 unsetenv(name);
10704 } /* else: export -n NOT_EXISTING_VAR: no-op */
10705 continue;
10706 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010707 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010708 /* export NAME (without =VALUE) */
10709 if (var) {
10710 var->flg_export = 1;
10711 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10712 putenv(var->varstr);
10713 continue;
10714 }
10715 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010716 if (flags & SETFLAG_MAKE_RO) {
10717 /* readonly NAME (without =VALUE) */
10718 if (var) {
10719 var->flg_read_only = 1;
10720 continue;
10721 }
10722 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010723# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010724 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010725 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010726 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10727 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010728 /* "local x=abc; ...; local x" - ignore second local decl */
10729 continue;
10730 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010731 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010732# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010733 /* Exporting non-existing variable.
10734 * bash does not put it in environment,
10735 * but remembers that it is exported,
10736 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010737 * We just set it to "" and export.
10738 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010739 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010740 * bash sets the value to "".
10741 */
10742 /* Or, it's "readonly NAME" (without =VALUE).
10743 * bash remembers NAME and disallows its creation
10744 * in the future.
10745 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010746 name = xasprintf("%s=", name);
10747 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010748 if (*name_end != '=') {
10749 bb_error_msg("'%s': bad variable name", name);
10750 /* do not parse following argv[]s: */
10751 return 1;
10752 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020010753 /* (Un)exporting/making local NAME=VALUE */
10754 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010755 /* Testcase: export PS1='\w \$ ' */
10756 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010757 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010758 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010759 if (set_local_var(name, flags))
10760 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010761 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010762 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010763}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010764#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010765
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010766#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010767static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010768{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010769 unsigned opt_unexport;
10770
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010771#if ENABLE_HUSH_EXPORT_N
10772 /* "!": do not abort on errors */
10773 opt_unexport = getopt32(argv, "!n");
10774 if (opt_unexport == (uint32_t)-1)
10775 return EXIT_FAILURE;
10776 argv += optind;
10777#else
10778 opt_unexport = 0;
10779 argv++;
10780#endif
10781
10782 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010783 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010784 if (e) {
10785 while (*e) {
10786#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010787 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010788#else
10789 /* ash emits: export VAR='VAL'
10790 * bash: declare -x VAR="VAL"
10791 * we follow ash example */
10792 const char *s = *e++;
10793 const char *p = strchr(s, '=');
10794
10795 if (!p) /* wtf? take next variable */
10796 continue;
10797 /* export var= */
10798 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010799 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010800 putchar('\n');
10801#endif
10802 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010803 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010804 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010805 return EXIT_SUCCESS;
10806 }
10807
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010808 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010809}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010810#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010811
Denys Vlasenko295fef82009-06-03 12:47:26 +020010812#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010813static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010814{
10815 if (G.func_nest_level == 0) {
10816 bb_error_msg("%s: not in a function", argv[0]);
10817 return EXIT_FAILURE; /* bash compat */
10818 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010819 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010820 /* Since all builtins run in a nested variable level,
10821 * need to use level - 1 here. Or else the variable will be removed at once
10822 * after builtin returns.
10823 */
10824 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010825}
10826#endif
10827
Denys Vlasenko1e660422017-07-17 21:10:50 +020010828#if ENABLE_HUSH_READONLY
10829static int FAST_FUNC builtin_readonly(char **argv)
10830{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010831 argv++;
10832 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010833 /* bash: readonly [-p]: list all readonly VARs
10834 * (-p has no effect in bash)
10835 */
10836 struct variable *e;
10837 for (e = G.top_var; e; e = e->next) {
10838 if (e->flg_read_only) {
10839//TODO: quote value: readonly VAR='VAL'
10840 printf("readonly %s\n", e->varstr);
10841 }
10842 }
10843 return EXIT_SUCCESS;
10844 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010845 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010846}
10847#endif
10848
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010849#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010850/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10851static int FAST_FUNC builtin_unset(char **argv)
10852{
10853 int ret;
10854 unsigned opts;
10855
10856 /* "!": do not abort on errors */
10857 /* "+": stop at 1st non-option */
10858 opts = getopt32(argv, "!+vf");
10859 if (opts == (unsigned)-1)
10860 return EXIT_FAILURE;
10861 if (opts == 3) {
10862 bb_error_msg("unset: -v and -f are exclusive");
10863 return EXIT_FAILURE;
10864 }
10865 argv += optind;
10866
10867 ret = EXIT_SUCCESS;
10868 while (*argv) {
10869 if (!(opts & 2)) { /* not -f */
10870 if (unset_local_var(*argv)) {
10871 /* unset <nonexistent_var> doesn't fail.
10872 * Error is when one tries to unset RO var.
10873 * Message was printed by unset_local_var. */
10874 ret = EXIT_FAILURE;
10875 }
10876 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010877# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010878 else {
10879 unset_func(*argv);
10880 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010881# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010882 argv++;
10883 }
10884 return ret;
10885}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010886#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010887
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010888#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010889/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10890 * built-in 'set' handler
10891 * SUSv3 says:
10892 * set [-abCefhmnuvx] [-o option] [argument...]
10893 * set [+abCefhmnuvx] [+o option] [argument...]
10894 * set -- [argument...]
10895 * set -o
10896 * set +o
10897 * Implementations shall support the options in both their hyphen and
10898 * plus-sign forms. These options can also be specified as options to sh.
10899 * Examples:
10900 * Write out all variables and their values: set
10901 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10902 * Turn on the -x and -v options: set -xv
10903 * Unset all positional parameters: set --
10904 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10905 * Set the positional parameters to the expansion of x, even if x expands
10906 * with a leading '-' or '+': set -- $x
10907 *
10908 * So far, we only support "set -- [argument...]" and some of the short names.
10909 */
10910static int FAST_FUNC builtin_set(char **argv)
10911{
10912 int n;
10913 char **pp, **g_argv;
10914 char *arg = *++argv;
10915
10916 if (arg == NULL) {
10917 struct variable *e;
10918 for (e = G.top_var; e; e = e->next)
10919 puts(e->varstr);
10920 return EXIT_SUCCESS;
10921 }
10922
10923 do {
10924 if (strcmp(arg, "--") == 0) {
10925 ++argv;
10926 goto set_argv;
10927 }
10928 if (arg[0] != '+' && arg[0] != '-')
10929 break;
10930 for (n = 1; arg[n]; ++n) {
10931 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10932 goto error;
10933 if (arg[n] == 'o' && argv[1])
10934 argv++;
10935 }
10936 } while ((arg = *++argv) != NULL);
10937 /* Now argv[0] is 1st argument */
10938
10939 if (arg == NULL)
10940 return EXIT_SUCCESS;
10941 set_argv:
10942
10943 /* NB: G.global_argv[0] ($0) is never freed/changed */
10944 g_argv = G.global_argv;
10945 if (G.global_args_malloced) {
10946 pp = g_argv;
10947 while (*++pp)
10948 free(*pp);
10949 g_argv[1] = NULL;
10950 } else {
10951 G.global_args_malloced = 1;
10952 pp = xzalloc(sizeof(pp[0]) * 2);
10953 pp[0] = g_argv[0]; /* retain $0 */
10954 g_argv = pp;
10955 }
10956 /* This realloc's G.global_argv */
10957 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10958
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010959 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010960
10961 return EXIT_SUCCESS;
10962
10963 /* Nothing known, so abort */
10964 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010965 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010966 return EXIT_FAILURE;
10967}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010968#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010969
10970static int FAST_FUNC builtin_shift(char **argv)
10971{
10972 int n = 1;
10973 argv = skip_dash_dash(argv);
10974 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010975 n = bb_strtou(argv[0], NULL, 10);
10976 if (errno || n < 0) {
10977 /* shared string with ash.c */
10978 bb_error_msg("Illegal number: %s", argv[0]);
10979 /*
10980 * ash aborts in this case.
10981 * bash prints error message and set $? to 1.
10982 * Interestingly, for "shift 99999" bash does not
10983 * print error message, but does set $? to 1
10984 * (and does no shifting at all).
10985 */
10986 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010987 }
10988 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010989 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010990 int m = 1;
10991 while (m <= n)
10992 free(G.global_argv[m++]);
10993 }
10994 G.global_argc -= n;
10995 memmove(&G.global_argv[1], &G.global_argv[n+1],
10996 G.global_argc * sizeof(G.global_argv[0]));
10997 return EXIT_SUCCESS;
10998 }
10999 return EXIT_FAILURE;
11000}
11001
Denys Vlasenko74d40582017-08-11 01:32:46 +020011002#if ENABLE_HUSH_GETOPTS
11003static int FAST_FUNC builtin_getopts(char **argv)
11004{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011005/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11006
Denys Vlasenko74d40582017-08-11 01:32:46 +020011007TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011008If a required argument is not found, and getopts is not silent,
11009a question mark (?) is placed in VAR, OPTARG is unset, and a
11010diagnostic message is printed. If getopts is silent, then a
11011colon (:) is placed in VAR and OPTARG is set to the option
11012character found.
11013
11014Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011015
11016"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011017*/
11018 char cbuf[2];
11019 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011020 int c, n, exitcode, my_opterr;
11021 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011022
11023 optstring = *++argv;
11024 if (!optstring || !(var = *++argv)) {
11025 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
11026 return EXIT_FAILURE;
11027 }
11028
Denys Vlasenko238ff982017-08-29 13:38:30 +020011029 if (argv[1])
11030 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11031 else
11032 argv = G.global_argv;
11033 cbuf[1] = '\0';
11034
11035 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011036 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011037 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011038 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011039 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011040 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011041
11042 /* getopts stops on first non-option. Add "+" to force that */
11043 /*if (optstring[0] != '+')*/ {
11044 char *s = alloca(strlen(optstring) + 2);
11045 sprintf(s, "+%s", optstring);
11046 optstring = s;
11047 }
11048
Denys Vlasenko238ff982017-08-29 13:38:30 +020011049 /* Naively, now we should just
11050 * cp = get_local_var_value("OPTIND");
11051 * optind = cp ? atoi(cp) : 0;
11052 * optarg = NULL;
11053 * opterr = my_opterr;
11054 * c = getopt(string_array_len(argv), argv, optstring);
11055 * and be done? Not so fast...
11056 * Unlike normal getopt() usage in C programs, here
11057 * each successive call will (usually) have the same argv[] CONTENTS,
11058 * but not the ADDRESSES. Worse yet, it's possible that between
11059 * invocations of "getopts", there will be calls to shell builtins
11060 * which use getopt() internally. Example:
11061 * while getopts "abc" RES -a -bc -abc de; do
11062 * unset -ff func
11063 * done
11064 * This would not work correctly: getopt() call inside "unset"
11065 * modifies internal libc state which is tracking position in
11066 * multi-option strings ("-abc"). At best, it can skip options
11067 * or return the same option infinitely. With glibc implementation
11068 * of getopt(), it would use outright invalid pointers and return
11069 * garbage even _without_ "unset" mangling internal state.
11070 *
11071 * We resort to resetting getopt() state and calling it N times,
11072 * until we get Nth result (or failure).
11073 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11074 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011075 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011076 count = 0;
11077 n = string_array_len(argv);
11078 do {
11079 optarg = NULL;
11080 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11081 c = getopt(n, argv, optstring);
11082 if (c < 0)
11083 break;
11084 count++;
11085 } while (count <= G.getopt_count);
11086
11087 /* Set OPTIND. Prevent resetting of the magic counter! */
11088 set_local_var_from_halves("OPTIND", utoa(optind));
11089 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011090 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011091
11092 /* Set OPTARG */
11093 /* Always set or unset, never left as-is, even on exit/error:
11094 * "If no option was found, or if the option that was found
11095 * does not have an option-argument, OPTARG shall be unset."
11096 */
11097 cp = optarg;
11098 if (c == '?') {
11099 /* If ":optstring" and unknown option is seen,
11100 * it is stored to OPTARG.
11101 */
11102 if (optstring[1] == ':') {
11103 cbuf[0] = optopt;
11104 cp = cbuf;
11105 }
11106 }
11107 if (cp)
11108 set_local_var_from_halves("OPTARG", cp);
11109 else
11110 unset_local_var("OPTARG");
11111
11112 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011113 exitcode = EXIT_SUCCESS;
11114 if (c < 0) { /* -1: end of options */
11115 exitcode = EXIT_FAILURE;
11116 c = '?';
11117 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011118
Denys Vlasenko238ff982017-08-29 13:38:30 +020011119 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011120 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011121 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011122
Denys Vlasenko74d40582017-08-11 01:32:46 +020011123 return exitcode;
11124}
11125#endif
11126
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011127static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011128{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011129 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011130 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011131 save_arg_t sv;
11132 char *args_need_save;
11133#if ENABLE_HUSH_FUNCTIONS
11134 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011135#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011136
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011137 argv = skip_dash_dash(argv);
11138 filename = argv[0];
11139 if (!filename) {
11140 /* bash says: "bash: .: filename argument required" */
11141 return 2; /* bash compat */
11142 }
11143 arg_path = NULL;
11144 if (!strchr(filename, '/')) {
11145 arg_path = find_in_path(filename);
11146 if (arg_path)
11147 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011148 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011149 errno = ENOENT;
11150 bb_simple_perror_msg(filename);
11151 return EXIT_FAILURE;
11152 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011153 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011154 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011155 free(arg_path);
11156 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011157 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011158 /* POSIX: non-interactive shell should abort here,
11159 * not merely fail. So far no one complained :)
11160 */
11161 return EXIT_FAILURE;
11162 }
11163
11164#if ENABLE_HUSH_FUNCTIONS
11165 sv_flg = G_flag_return_in_progress;
11166 /* "we are inside sourced file, ok to use return" */
11167 G_flag_return_in_progress = -1;
11168#endif
11169 args_need_save = argv[1]; /* used as a boolean variable */
11170 if (args_need_save)
11171 save_and_replace_G_args(&sv, argv);
11172
11173 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11174 G.last_exitcode = 0;
11175 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011176 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011177
11178 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11179 restore_G_args(&sv, argv);
11180#if ENABLE_HUSH_FUNCTIONS
11181 G_flag_return_in_progress = sv_flg;
11182#endif
11183
11184 return G.last_exitcode;
11185}
11186
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011187#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011188static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011189{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011190 int sig;
11191 char *new_cmd;
11192
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011193 if (!G_traps)
11194 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011195
11196 argv++;
11197 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011198 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011199 /* No args: print all trapped */
11200 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011201 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011202 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011203 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011204 /* note: bash adds "SIG", but only if invoked
11205 * as "bash". If called as "sh", or if set -o posix,
11206 * then it prints short signal names.
11207 * We are printing short names: */
11208 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011209 }
11210 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011211 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011212 return EXIT_SUCCESS;
11213 }
11214
11215 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011216 /* If first arg is a number: reset all specified signals */
11217 sig = bb_strtou(*argv, NULL, 10);
11218 if (errno == 0) {
11219 int ret;
11220 process_sig_list:
11221 ret = EXIT_SUCCESS;
11222 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011223 sighandler_t handler;
11224
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011225 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011226 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011227 ret = EXIT_FAILURE;
11228 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011229 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011230 continue;
11231 }
11232
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011233 free(G_traps[sig]);
11234 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011235
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011236 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011237 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011238
11239 /* There is no signal for 0 (EXIT) */
11240 if (sig == 0)
11241 continue;
11242
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011243 if (new_cmd)
11244 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11245 else
11246 /* We are removing trap handler */
11247 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011248 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011249 }
11250 return ret;
11251 }
11252
11253 if (!argv[1]) { /* no second arg */
11254 bb_error_msg("trap: invalid arguments");
11255 return EXIT_FAILURE;
11256 }
11257
11258 /* First arg is "-": reset all specified to default */
11259 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11260 /* Everything else: set arg as signal handler
11261 * (includes "" case, which ignores signal) */
11262 if (argv[0][0] == '-') {
11263 if (argv[0][1] == '\0') { /* "-" */
11264 /* new_cmd remains NULL: "reset these sigs" */
11265 goto reset_traps;
11266 }
11267 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11268 argv++;
11269 }
11270 /* else: "-something", no special meaning */
11271 }
11272 new_cmd = *argv;
11273 reset_traps:
11274 argv++;
11275 goto process_sig_list;
11276}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011277#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011278
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011279#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011280static struct pipe *parse_jobspec(const char *str)
11281{
11282 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011283 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011284
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011285 if (sscanf(str, "%%%u", &jobnum) != 1) {
11286 if (str[0] != '%'
11287 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11288 ) {
11289 bb_error_msg("bad argument '%s'", str);
11290 return NULL;
11291 }
11292 /* It is "%%", "%+" or "%" - current job */
11293 jobnum = G.last_jobid;
11294 if (jobnum == 0) {
11295 bb_error_msg("no current job");
11296 return NULL;
11297 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011298 }
11299 for (pi = G.job_list; pi; pi = pi->next) {
11300 if (pi->jobid == jobnum) {
11301 return pi;
11302 }
11303 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011304 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011305 return NULL;
11306}
11307
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011308static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11309{
11310 struct pipe *job;
11311 const char *status_string;
11312
11313 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11314 for (job = G.job_list; job; job = job->next) {
11315 if (job->alive_cmds == job->stopped_cmds)
11316 status_string = "Stopped";
11317 else
11318 status_string = "Running";
11319
11320 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11321 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011322
11323 clean_up_last_dead_job();
11324
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011325 return EXIT_SUCCESS;
11326}
11327
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011328/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011329static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011330{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011331 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011332 struct pipe *pi;
11333
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011334 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011335 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011336
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011337 /* If they gave us no args, assume they want the last backgrounded task */
11338 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011339 for (pi = G.job_list; pi; pi = pi->next) {
11340 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011341 goto found;
11342 }
11343 }
11344 bb_error_msg("%s: no current job", argv[0]);
11345 return EXIT_FAILURE;
11346 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011347
11348 pi = parse_jobspec(argv[1]);
11349 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011350 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011351 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011352 /* TODO: bash prints a string representation
11353 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011354 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011355 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011356 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011357 }
11358
11359 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011360 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11361 for (i = 0; i < pi->num_cmds; i++) {
11362 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011363 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011364 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011365
11366 i = kill(- pi->pgrp, SIGCONT);
11367 if (i < 0) {
11368 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011369 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011370 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011371 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011372 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011373 }
11374
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011375 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011376 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011377 return checkjobs_and_fg_shell(pi);
11378 }
11379 return EXIT_SUCCESS;
11380}
11381#endif
11382
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011383#if ENABLE_HUSH_KILL
11384static int FAST_FUNC builtin_kill(char **argv)
11385{
11386 int ret = 0;
11387
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011388# if ENABLE_HUSH_JOB
11389 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11390 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011391
11392 do {
11393 struct pipe *pi;
11394 char *dst;
11395 int j, n;
11396
11397 if (argv[i][0] != '%')
11398 continue;
11399 /*
11400 * "kill %N" - job kill
11401 * Converting to pgrp / pid kill
11402 */
11403 pi = parse_jobspec(argv[i]);
11404 if (!pi) {
11405 /* Eat bad jobspec */
11406 j = i;
11407 do {
11408 j++;
11409 argv[j - 1] = argv[j];
11410 } while (argv[j]);
11411 ret = 1;
11412 i--;
11413 continue;
11414 }
11415 /*
11416 * In jobs started under job control, we signal
11417 * entire process group by kill -PGRP_ID.
11418 * This happens, f.e., in interactive shell.
11419 *
11420 * Otherwise, we signal each child via
11421 * kill PID1 PID2 PID3.
11422 * Testcases:
11423 * sh -c 'sleep 1|sleep 1 & kill %1'
11424 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11425 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11426 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011427 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011428 dst = alloca(n * sizeof(int)*4);
11429 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011430 if (G_interactive_fd)
11431 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011432 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011433 struct command *cmd = &pi->cmds[j];
11434 /* Skip exited members of the job */
11435 if (cmd->pid == 0)
11436 continue;
11437 /*
11438 * kill_main has matching code to expect
11439 * leading space. Needed to not confuse
11440 * negative pids with "kill -SIGNAL_NO" syntax
11441 */
11442 dst += sprintf(dst, " %u", (int)cmd->pid);
11443 }
11444 *dst = '\0';
11445 } while (argv[++i]);
11446 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011447# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011448
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011449 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011450 ret = run_applet_main(argv, kill_main);
11451 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011452 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011453 return ret;
11454}
11455#endif
11456
11457#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011458/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011459#if !ENABLE_HUSH_JOB
11460# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11461#endif
11462static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011463{
11464 int ret = 0;
11465 for (;;) {
11466 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011467 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011468
Denys Vlasenko830ea352016-11-08 04:59:11 +010011469 if (!sigisemptyset(&G.pending_set))
11470 goto check_sig;
11471
Denys Vlasenko7e675362016-10-28 21:57:31 +020011472 /* waitpid is not interruptible by SA_RESTARTed
11473 * signals which we use. Thus, this ugly dance:
11474 */
11475
11476 /* Make sure possible SIGCHLD is stored in kernel's
11477 * pending signal mask before we call waitpid.
11478 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011479 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011480 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011481 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011482 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011483
11484 if (!sigisemptyset(&G.pending_set)) {
11485 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011486 goto restore;
11487 }
11488
11489 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011490/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011491 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011492 debug_printf_exec("checkjobs:%d\n", ret);
11493#if ENABLE_HUSH_JOB
11494 if (waitfor_pipe) {
11495 int rcode = job_exited_or_stopped(waitfor_pipe);
11496 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11497 if (rcode >= 0) {
11498 ret = rcode;
11499 sigprocmask(SIG_SETMASK, &oldset, NULL);
11500 break;
11501 }
11502 }
11503#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011504 /* if ECHILD, there are no children (ret is -1 or 0) */
11505 /* if ret == 0, no children changed state */
11506 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011507 if (errno == ECHILD || ret) {
11508 ret--;
11509 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011510 ret = 0;
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011511#if ENABLE_HUSH_BASH_COMPAT
11512 if (waitfor_pid == -1 && errno == ECHILD) {
11513 /* exitcode of "wait -n" with no children is 127, not 0 */
11514 ret = 127;
11515 }
11516#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011517 sigprocmask(SIG_SETMASK, &oldset, NULL);
11518 break;
11519 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011520 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011521 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11522 /* Note: sigsuspend invokes signal handler */
11523 sigsuspend(&oldset);
11524 restore:
11525 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011526 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011527 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011528 sig = check_and_run_traps();
11529 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011530 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011531 ret = 128 + sig;
11532 break;
11533 }
11534 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11535 }
11536 return ret;
11537}
11538
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011539static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011540{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011541 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011542 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011543
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011544 argv = skip_dash_dash(argv);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011545#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011546 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011547 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011548 /* (bash accepts "wait -n PID" too and ignores PID) */
11549 G.dead_job_exitcode = -1;
11550 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011551 }
11552#endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011553 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011554 /* Don't care about wait results */
11555 /* Note 1: must wait until there are no more children */
11556 /* Note 2: must be interruptible */
11557 /* Examples:
11558 * $ sleep 3 & sleep 6 & wait
11559 * [1] 30934 sleep 3
11560 * [2] 30935 sleep 6
11561 * [1] Done sleep 3
11562 * [2] Done sleep 6
11563 * $ sleep 3 & sleep 6 & wait
11564 * [1] 30936 sleep 3
11565 * [2] 30937 sleep 6
11566 * [1] Done sleep 3
11567 * ^C <-- after ~4 sec from keyboard
11568 * $
11569 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011570 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011571 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011572
Denys Vlasenko7e675362016-10-28 21:57:31 +020011573 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011574 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011575 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011576#if ENABLE_HUSH_JOB
11577 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011578 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011579 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011580 wait_pipe = parse_jobspec(*argv);
11581 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011582 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011583 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011584 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011585 } else {
11586 /* waiting on "last dead job" removes it */
11587 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011588 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011589 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011590 /* else: parse_jobspec() already emitted error msg */
11591 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011592 }
11593#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011594 /* mimic bash message */
11595 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011596 ret = EXIT_FAILURE;
11597 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011598 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011599
Denys Vlasenko7e675362016-10-28 21:57:31 +020011600 /* Do we have such child? */
11601 ret = waitpid(pid, &status, WNOHANG);
11602 if (ret < 0) {
11603 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011604 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011605 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011606 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011607 /* "wait $!" but last bg task has already exited. Try:
11608 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11609 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011610 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011611 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011612 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011613 } else {
11614 /* Example: "wait 1". mimic bash message */
11615 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011616 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011617 } else {
11618 /* ??? */
11619 bb_perror_msg("wait %s", *argv);
11620 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011621 continue; /* bash checks all argv[] */
11622 }
11623 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011624 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011625 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011626 } else {
11627 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011628 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011629 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011630 if (WIFSIGNALED(status))
11631 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011632 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011633 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011634
11635 return ret;
11636}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011637#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011638
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011639#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11640static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11641{
11642 if (argv[1]) {
11643 def = bb_strtou(argv[1], NULL, 10);
11644 if (errno || def < def_min || argv[2]) {
11645 bb_error_msg("%s: bad arguments", argv[0]);
11646 def = UINT_MAX;
11647 }
11648 }
11649 return def;
11650}
11651#endif
11652
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011653#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011654static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011655{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011656 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011657 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011658 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011659 /* if we came from builtin_continue(), need to undo "= 1" */
11660 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011661 return EXIT_SUCCESS; /* bash compat */
11662 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011663 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011664
11665 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11666 if (depth == UINT_MAX)
11667 G.flag_break_continue = BC_BREAK;
11668 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011669 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011670
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011671 return EXIT_SUCCESS;
11672}
11673
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011674static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011675{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011676 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11677 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011678}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011679#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011680
11681#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011682static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011683{
11684 int rc;
11685
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011686 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011687 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11688 return EXIT_FAILURE; /* bash compat */
11689 }
11690
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011691 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011692
11693 /* bash:
11694 * out of range: wraps around at 256, does not error out
11695 * non-numeric param:
11696 * f() { false; return qwe; }; f; echo $?
11697 * bash: return: qwe: numeric argument required <== we do this
11698 * 255 <== we also do this
11699 */
11700 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11701 return rc;
11702}
11703#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011704
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011705#if ENABLE_HUSH_TIMES
11706static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11707{
11708 static const uint8_t times_tbl[] ALIGN1 = {
11709 ' ', offsetof(struct tms, tms_utime),
11710 '\n', offsetof(struct tms, tms_stime),
11711 ' ', offsetof(struct tms, tms_cutime),
11712 '\n', offsetof(struct tms, tms_cstime),
11713 0
11714 };
11715 const uint8_t *p;
11716 unsigned clk_tck;
11717 struct tms buf;
11718
11719 clk_tck = bb_clk_tck();
11720
11721 times(&buf);
11722 p = times_tbl;
11723 do {
11724 unsigned sec, frac;
11725 unsigned long t;
11726 t = *(clock_t *)(((char *) &buf) + p[1]);
11727 sec = t / clk_tck;
11728 frac = t % clk_tck;
11729 printf("%um%u.%03us%c",
11730 sec / 60, sec % 60,
11731 (frac * 1000) / clk_tck,
11732 p[0]);
11733 p += 2;
11734 } while (*p);
11735
11736 return EXIT_SUCCESS;
11737}
11738#endif
11739
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011740#if ENABLE_HUSH_MEMLEAK
11741static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11742{
11743 void *p;
11744 unsigned long l;
11745
11746# ifdef M_TRIM_THRESHOLD
11747 /* Optional. Reduces probability of false positives */
11748 malloc_trim(0);
11749# endif
11750 /* Crude attempt to find where "free memory" starts,
11751 * sans fragmentation. */
11752 p = malloc(240);
11753 l = (unsigned long)p;
11754 free(p);
11755 p = malloc(3400);
11756 if (l < (unsigned long)p) l = (unsigned long)p;
11757 free(p);
11758
11759
11760# if 0 /* debug */
11761 {
11762 struct mallinfo mi = mallinfo();
11763 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11764 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11765 }
11766# endif
11767
11768 if (!G.memleak_value)
11769 G.memleak_value = l;
11770
11771 l -= G.memleak_value;
11772 if ((long)l < 0)
11773 l = 0;
11774 l /= 1024;
11775 if (l > 127)
11776 l = 127;
11777
11778 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11779 return l;
11780}
11781#endif