blob: d745148f4a3ec8b568884996ca87bc107d0f7344 [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
366#ifndef PIPE_BUF
367# define PIPE_BUF 4096 /* amount of buffering in a pipe */
368#endif
369
Ron Yorston71df2d32018-11-27 14:34:25 +0000370#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
371# include "embedded_scripts.h"
372#else
373# define NUM_SCRIPTS 0
374#endif
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000375
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376/* So far, all bash compat is controlled by one config option */
377/* Separate defines document which part of code implements what */
378#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
379#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100380#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
381#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100382#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200383#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200384#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100385
386
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200387/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000388#define LEAK_HUNTING 0
389#define BUILD_AS_NOMMU 0
390/* Enable/disable sanity checks. Ok to enable in production,
391 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
392 * Keeping 1 for now even in released versions.
393 */
394#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200395/* Slightly bigger (+200 bytes), but faster hush.
396 * So far it only enables a trick with counting SIGCHLDs and forks,
397 * which allows us to do fewer waitpid's.
398 * (we can detect a case where neither forks were done nor SIGCHLDs happened
399 * and therefore waitpid will return the same result as last time)
400 */
401#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200402/* TODO: implement simplified code for users which do not need ${var%...} ops
403 * So far ${var%...} ops are always enabled:
404 */
405#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000406
407
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000408#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000409# undef BB_MMU
410# undef USE_FOR_NOMMU
411# undef USE_FOR_MMU
412# define BB_MMU 0
413# define USE_FOR_NOMMU(...) __VA_ARGS__
414# define USE_FOR_MMU(...)
415#endif
416
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200417#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100418#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000419/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000420# undef CONFIG_FEATURE_SH_STANDALONE
421# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000422# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100423# undef IF_NOT_FEATURE_SH_STANDALONE
424# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000425# define IF_FEATURE_SH_STANDALONE(...)
426# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000427#endif
428
Denis Vlasenko05743d72008-02-10 12:10:08 +0000429#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000430# undef ENABLE_FEATURE_EDITING
431# define ENABLE_FEATURE_EDITING 0
432# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
433# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200434# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
435# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000436#endif
437
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438/* Do we support ANY keywords? */
439#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000440# define HAS_KEYWORDS 1
441# define IF_HAS_KEYWORDS(...) __VA_ARGS__
442# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000443#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000444# define HAS_KEYWORDS 0
445# define IF_HAS_KEYWORDS(...)
446# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000447#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000448
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000449/* If you comment out one of these below, it will be #defined later
450 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200451#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000452/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200453#define debug_printf_parse(...) do {} while (0)
454#define debug_printf_heredoc(...) do {} while (0)
455#define debug_print_tree(a, b) do {} while (0)
456#define debug_printf_exec(...) do {} while (0)
457#define debug_printf_env(...) do {} while (0)
458#define debug_printf_jobs(...) do {} while (0)
459#define debug_printf_expand(...) do {} while (0)
460#define debug_printf_varexp(...) do {} while (0)
461#define debug_printf_glob(...) do {} while (0)
462#define debug_printf_redir(...) do {} while (0)
463#define debug_printf_list(...) do {} while (0)
464#define debug_printf_subst(...) do {} while (0)
465#define debug_printf_prompt(...) do {} while (0)
466#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000467
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000468#define ERR_PTR ((void*)(long)1)
469
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100470#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000471
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200472#define _SPECIAL_VARS_STR "_*@$!?#"
473#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
474#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100475#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200476/* Support / and // replace ops */
477/* Note that // is stored as \ in "encoded" string representation */
478# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
479# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
480# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
481#else
482# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
483# define VAR_SUBST_OPS "%#:-=+?"
484# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
485#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200486
Denys Vlasenko932b9972018-01-11 12:39:48 +0100487#define SPECIAL_VAR_SYMBOL_STR "\3"
488#define SPECIAL_VAR_SYMBOL 3
489/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
490#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000491
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200492struct variable;
493
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
495
496/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000497 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000498 */
499#if !BB_MMU
500typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200501 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000502 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000503 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000504} nommu_save_t;
505#endif
506
Denys Vlasenko9b782552010-09-08 13:33:26 +0200507enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000508 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000509#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000510 RES_IF ,
511 RES_THEN ,
512 RES_ELIF ,
513 RES_ELSE ,
514 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#endif
516#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000517 RES_FOR ,
518 RES_WHILE ,
519 RES_UNTIL ,
520 RES_DO ,
521 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000522#endif
523#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000524 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000525#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000526#if ENABLE_HUSH_CASE
527 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200528 /* three pseudo-keywords support contrived "case" syntax: */
529 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
530 RES_MATCH , /* "word)" */
531 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000532 RES_ESAC ,
533#endif
534 RES_XXXX ,
535 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200536};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000537
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538typedef struct o_string {
539 char *data;
540 int length; /* position where data is appended */
541 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200542 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000543 /* At least some part of the string was inside '' or "",
544 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200545 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000546 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200547 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000548} o_string;
549enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200550 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
551 EXP_FLAG_GLOB = 0x2,
552 /* Protect newly added chars against globbing
553 * by prepending \ to *, ?, [, \ */
554 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
555};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000556/* Used for initialization: o_string foo = NULL_O_STRING; */
557#define NULL_O_STRING { NULL }
558
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200559#ifndef debug_printf_parse
560static const char *const assignment_flag[] = {
561 "MAYBE_ASSIGNMENT",
562 "DEFINITELY_ASSIGNMENT",
563 "NOT_ASSIGNMENT",
564 "WORD_IS_KEYWORD",
565};
566#endif
567
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200568/* We almost can use standard FILE api, but we need an ability to move
569 * its fd when redirects coincide with it. No api exists for that
570 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
571 * HFILE is our internal alternative. Only supports reading.
572 * Since we now can, we incorporate linked list of all opened HFILEs
573 * into the struct (used to be a separate mini-list).
574 */
575typedef struct HFILE {
576 char *cur;
577 char *end;
578 struct HFILE *next_hfile;
579 int is_stdin;
580 int fd;
581 char buf[1024];
582} HFILE;
583
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000584typedef struct in_str {
585 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200586 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200587 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200588 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000589} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000590
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200591/* The descrip member of this structure is only used to make
592 * debugging output pretty */
593static const struct {
594 int mode;
595 signed char default_fd;
596 char descrip[3];
597} redir_table[] = {
598 { O_RDONLY, 0, "<" },
599 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
600 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
601 { O_CREAT|O_RDWR, 1, "<>" },
602 { O_RDONLY, 0, "<<" },
603/* Should not be needed. Bogus default_fd helps in debugging */
604/* { O_RDONLY, 77, "<<" }, */
605};
606
Eric Andersen25f27032001-04-26 23:22:31 +0000607struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000608 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000609 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000610 int rd_fd; /* fd to redirect */
611 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
612 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000613 smallint rd_type; /* (enum redir_type) */
614 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000615 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200616 * bit 0: do we need to trim leading tabs?
617 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000618 */
Eric Andersen25f27032001-04-26 23:22:31 +0000619};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000620typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200621 REDIRECT_INPUT = 0,
622 REDIRECT_OVERWRITE = 1,
623 REDIRECT_APPEND = 2,
624 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000625 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200626 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000627
628 REDIRFD_CLOSE = -3,
629 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000630 REDIRFD_TO_FILE = -1,
631 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000632
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000633 HEREDOC_SKIPTABS = 1,
634 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000635} redir_type;
636
Eric Andersen25f27032001-04-26 23:22:31 +0000637
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000638struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000639 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200640 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100641#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100642 unsigned lineno;
643#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200644 smallint cmd_type; /* CMD_xxx */
645#define CMD_NORMAL 0
646#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200647#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
648/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
649 * "export v=t*"
650 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200651# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000652#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200653#if ENABLE_HUSH_FUNCTIONS
654# define CMD_FUNCDEF 3
655#endif
656
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100657 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200658 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
659 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000660#if !BB_MMU
661 char *group_as_string;
662#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000663#if ENABLE_HUSH_FUNCTIONS
664 struct function *child_func;
665/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200666 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000667 * When we execute "f1() {a;}" cmd, we create new function and clear
668 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200669 * When we execute "f1() {b;}", we notice that f1 exists,
670 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000671 * we put those fields back into cmd->xxx
672 * (struct function has ->parent_cmd ptr to facilitate that).
673 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
674 * Without this trick, loop would execute a;b;b;b;...
675 * instead of correct sequence a;b;a;b;...
676 * When command is freed, it severs the link
677 * (sets ->child_func->parent_cmd to NULL).
678 */
679#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000680 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000681/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
682 * and on execution these are substituted with their values.
683 * Substitution can make _several_ words out of one argv[n]!
684 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000685 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000686 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000687 struct redir_struct *redirects; /* I/O redirections */
688};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000689/* Is there anything in this command at all? */
690#define IS_NULL_CMD(cmd) \
691 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
692
Eric Andersen25f27032001-04-26 23:22:31 +0000693struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000694 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000695 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 int alive_cmds; /* number of commands running (not exited) */
697 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000698#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100699 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000700 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000701 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000702#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000703 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000704 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000705 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
706 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000707};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000708typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100709 PIPE_SEQ = 0,
710 PIPE_AND = 1,
711 PIPE_OR = 2,
712 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000713} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000714/* Is there anything in this pipe at all? */
715#define IS_NULL_PIPE(pi) \
716 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000717
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000718/* This holds pointers to the various results of parsing */
719struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000720 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000721 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000722 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000723 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000724 /* last command in pipe (being constructed right now) */
725 struct command *command;
726 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000727 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200728 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000729#if !BB_MMU
730 o_string as_string;
731#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200732 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000733#if HAS_KEYWORDS
734 smallint ctx_res_w;
735 smallint ctx_inverted; /* "! cmd | cmd" */
736#if ENABLE_HUSH_CASE
737 smallint ctx_dsemicolon; /* ";;" seen */
738#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000739 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
740 int old_flag;
741 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000742 * example: "if pipe1; pipe2; then pipe3; fi"
743 * when we see "if" or "then", we malloc and copy current context,
744 * and make ->stack point to it. then we parse pipeN.
745 * when closing "then" / fi" / whatever is found,
746 * we move list_head into ->stack->command->group,
747 * copy ->stack into current context, and delete ->stack.
748 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000749 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000750 struct parse_context *stack;
751#endif
752};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200753enum {
754 MAYBE_ASSIGNMENT = 0,
755 DEFINITELY_ASSIGNMENT = 1,
756 NOT_ASSIGNMENT = 2,
757 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
758 WORD_IS_KEYWORD = 3,
759};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000760
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000761/* On program start, environ points to initial environment.
762 * putenv adds new pointers into it, unsetenv removes them.
763 * Neither of these (de)allocates the strings.
764 * setenv allocates new strings in malloc space and does putenv,
765 * and thus setenv is unusable (leaky) for shell's purposes */
766#define setenv(...) setenv_is_leaky_dont_use()
767struct variable {
768 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000769 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000770 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200771 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000772 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000773 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000774};
775
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000776enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000777 BC_BREAK = 1,
778 BC_CONTINUE = 2,
779};
780
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000781#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000782struct function {
783 struct function *next;
784 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000785 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200787# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000788 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200789# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000790};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000791#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000792
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000793
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100794/* set -/+o OPT support. (TODO: make it optional)
795 * bash supports the following opts:
796 * allexport off
797 * braceexpand on
798 * emacs on
799 * errexit off
800 * errtrace off
801 * functrace off
802 * hashall on
803 * histexpand off
804 * history on
805 * ignoreeof off
806 * interactive-comments on
807 * keyword off
808 * monitor on
809 * noclobber off
810 * noexec off
811 * noglob off
812 * nolog off
813 * notify off
814 * nounset off
815 * onecmd off
816 * physical off
817 * pipefail off
818 * posix off
819 * privileged off
820 * verbose off
821 * vi off
822 * xtrace off
823 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800824static const char o_opt_strings[] ALIGN1 =
825 "pipefail\0"
826 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200827 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800828#if ENABLE_HUSH_MODE_X
829 "xtrace\0"
830#endif
831 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100832enum {
833 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800834 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200835 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800836#if ENABLE_HUSH_MODE_X
837 OPT_O_XTRACE,
838#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100839 NUM_OPT_O
840};
841
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000842/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000843/* Sorted roughly by size (smaller offsets == smaller code) */
844struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845 /* interactive_fd != 0 means we are an interactive shell.
846 * If we are, then saved_tty_pgrp can also be != 0, meaning
847 * that controlling tty is available. With saved_tty_pgrp == 0,
848 * job control still works, but terminal signals
849 * (^C, ^Z, ^Y, ^\) won't work at all, and background
850 * process groups can only be created with "cmd &".
851 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
852 * to give tty to the foreground process group,
853 * and will take it back when the group is stopped (^Z)
854 * or killed (^C).
855 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000856#if ENABLE_HUSH_INTERACTIVE
857 /* 'interactive_fd' is a fd# open to ctty, if we have one
858 * _AND_ if we decided to act interactively */
859 int interactive_fd;
860 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200861 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000862# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000863#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000864# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000865#endif
866#if ENABLE_FEATURE_EDITING
867 line_input_t *line_input_state;
868#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000869 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200870 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000871 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200872#if ENABLE_HUSH_RANDOM_SUPPORT
873 random_t random_gen;
874#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000875#if ENABLE_HUSH_JOB
876 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100877 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000878 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000879 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400880# define G_saved_tty_pgrp (G.saved_tty_pgrp)
881#else
882# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000883#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200884 /* How deeply are we in context where "set -e" is ignored */
885 int errexit_depth;
886 /* "set -e" rules (do we follow them correctly?):
887 * Exit if pipe, list, or compound command exits with a non-zero status.
888 * Shell does not exit if failed command is part of condition in
889 * if/while, part of && or || list except the last command, any command
890 * in a pipe but the last, or if the command's return value is being
891 * inverted with !. If a compound command other than a subshell returns a
892 * non-zero status because a command failed while -e was being ignored, the
893 * shell does not exit. A trap on ERR, if set, is executed before the shell
894 * exits [ERR is a bashism].
895 *
896 * If a compound command or function executes in a context where -e is
897 * ignored, none of the commands executed within are affected by the -e
898 * setting. If a compound command or function sets -e while executing in a
899 * context where -e is ignored, that setting does not have any effect until
900 * the compound command or the command containing the function call completes.
901 */
902
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100903 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100904#if ENABLE_HUSH_MODE_X
905# define G_x_mode (G.o_opt[OPT_O_XTRACE])
906#else
907# define G_x_mode 0
908#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200909#if ENABLE_HUSH_INTERACTIVE
910 smallint promptmode; /* 0: PS1, 1: PS2 */
911#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000912 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000913#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000914 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000915#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000916#if ENABLE_HUSH_FUNCTIONS
917 /* 0: outside of a function (or sourced file)
918 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000919 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000920 */
921 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200922# define G_flag_return_in_progress (G.flag_return_in_progress)
923#else
924# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000925#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000926 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100927 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000928 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200929 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200930 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100931#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000932 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000933 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100934# define G_global_args_malloced (G.global_args_malloced)
935#else
936# define G_global_args_malloced 0
937#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100938#if ENABLE_HUSH_BASH_COMPAT
939 int dead_job_exitcode; /* for "wait -n" */
940#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000941 /* how many non-NULL argv's we have. NB: $# + 1 */
942 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000943 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000944#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000945 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000946#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000947#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000948 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000949 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000950#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200951#if ENABLE_HUSH_GETOPTS
952 unsigned getopt_count;
953#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000954 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200955 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000956 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200957 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200958 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200959 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200960 unsigned var_nest_level;
961#if ENABLE_HUSH_FUNCTIONS
962# if ENABLE_HUSH_LOCAL
963 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200964# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200965 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000966#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000967 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200968#if ENABLE_HUSH_FAST
969 unsigned count_SIGCHLD;
970 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200971 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200972#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100973#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100974 unsigned lineno;
975 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100976#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200977 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200978 /* Which signals have non-DFL handler (even with no traps set)?
979 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200980 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200981 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200982 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200983 * Other than these two times, never modified.
984 */
985 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200986#if ENABLE_HUSH_JOB
987 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100988# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200989#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200990# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200991#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100992#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000993 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100994# define G_traps G.traps
995#else
996# define G_traps ((char**)NULL)
997#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200998 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100999#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001000 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001001#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001002#if ENABLE_HUSH_MODE_X
1003 unsigned x_mode_depth;
1004 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1005 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1006 * for all subsequent output.
1007 */
1008 int x_mode_fd;
1009 o_string x_mode_buf;
1010#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001011#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001012 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001013#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001014 struct sigaction sa;
Ron Yorstona81700b2019-04-15 10:48:29 +01001015#if BASH_EPOCH_VARS
1016 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1017#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001018#if ENABLE_FEATURE_EDITING
1019 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1020#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001021};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001022#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001023/* Not #defining name to G.name - this quickly gets unwieldy
1024 * (too many defines). Also, I actually prefer to see when a variable
1025 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001026#define INIT_G() do { \
1027 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001028 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1029 sigfillset(&G.sa.sa_mask); \
1030 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001031} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001032
1033
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001034/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001035static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001036#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001038#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001039static int builtin_eval(char **argv) FAST_FUNC;
1040static int builtin_exec(char **argv) FAST_FUNC;
1041static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001042#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001043static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001044#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001045#if ENABLE_HUSH_READONLY
1046static int builtin_readonly(char **argv) FAST_FUNC;
1047#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001048#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001049static int builtin_fg_bg(char **argv) FAST_FUNC;
1050static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001051#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001052#if ENABLE_HUSH_GETOPTS
1053static int builtin_getopts(char **argv) FAST_FUNC;
1054#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001055#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001056static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001057#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001058#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001059static int builtin_history(char **argv) FAST_FUNC;
1060#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001061#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001063#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001064#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001066#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001067#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001068static int builtin_printf(char **argv) FAST_FUNC;
1069#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001071#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001072static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001073#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001074#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001076#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_shift(char **argv) FAST_FUNC;
1078static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001079#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001080static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001081#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001082#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001083static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001084#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001085#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001086static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001087#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001088#if ENABLE_HUSH_TIMES
1089static int builtin_times(char **argv) FAST_FUNC;
1090#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001091static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001092#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001093static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001094#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001095#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001096static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001097#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001098#if ENABLE_HUSH_KILL
1099static int builtin_kill(char **argv) FAST_FUNC;
1100#endif
1101#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001102static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001103#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001105static int builtin_break(char **argv) FAST_FUNC;
1106static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001108#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001109static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001110#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001111
1112/* Table of built-in functions. They can be forked or not, depending on
1113 * context: within pipes, they fork. As simple commands, they do not.
1114 * When used in non-forking context, they can change global variables
1115 * in the parent shell process. If forked, of course they cannot.
1116 * For example, 'unset foo | whatever' will parse and run, but foo will
1117 * still be set at the end. */
1118struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001119 const char *b_cmd;
1120 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001122 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001123# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001125# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001126#endif
1127};
1128
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001129static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001130 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001131 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001132#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001133 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001134#endif
1135#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001136 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001137#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001139#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001140 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001141#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001142 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1143 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001144 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001145#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001146 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001147#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001148#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001149 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001150#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001151#if ENABLE_HUSH_GETOPTS
1152 BLTIN("getopts" , builtin_getopts , NULL),
1153#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001154#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001156#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001157#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001158 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001159#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001160#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001161 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001162#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001163#if ENABLE_HUSH_KILL
1164 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1165#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001166#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001168#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001169#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001171#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001172#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001174#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001175#if ENABLE_HUSH_READONLY
1176 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1177#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001178#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001179 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001180#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001181#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001182 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001183#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001185#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001186 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001187#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001188#if ENABLE_HUSH_TIMES
1189 BLTIN("times" , builtin_times , NULL),
1190#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001191#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001192 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001193#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001194 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001195#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001196 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001197#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001198#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001199 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001200#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001201#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001202 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001203#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001204#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001205 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001206#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001207#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001208 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001209#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001210};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001211/* These builtins won't be used if we are on NOMMU and need to re-exec
1212 * (it's cheaper to run an external program in this case):
1213 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001214static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001215#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001216 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001217#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001218#if BASH_TEST2
1219 BLTIN("[[" , builtin_test , NULL),
1220#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001221#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001222 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001223#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001224#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001225 BLTIN("printf" , builtin_printf , NULL),
1226#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001227 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001228#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001229 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001230#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001231};
1232
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001233
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001234/* Debug printouts.
1235 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001236#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001238# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001239# define debug_enter() (G.debug_indent++)
1240# define debug_leave() (G.debug_indent--)
1241#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001242# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001243# define debug_enter() ((void)0)
1244# define debug_leave() ((void)0)
1245#endif
1246
1247#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001248# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249#endif
1250
1251#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001252# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253#endif
1254
Denys Vlasenko3675c372018-07-23 16:31:21 +02001255#ifndef debug_printf_heredoc
1256# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1257#endif
1258
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001260#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001261#endif
1262
1263#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001265#endif
1266
1267#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001268# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269# define DEBUG_JOBS 1
1270#else
1271# define DEBUG_JOBS 0
1272#endif
1273
1274#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001275# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276# define DEBUG_EXPAND 1
1277#else
1278# define DEBUG_EXPAND 0
1279#endif
1280
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001281#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001282# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001283#endif
1284
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001285#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001286# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001287# define DEBUG_GLOB 1
1288#else
1289# define DEBUG_GLOB 0
1290#endif
1291
Denys Vlasenko2db74612017-07-07 22:07:28 +02001292#ifndef debug_printf_redir
1293# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1294#endif
1295
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001296#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001297# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001298#endif
1299
1300#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001301# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001302#endif
1303
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001304#ifndef debug_printf_prompt
1305# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1306#endif
1307
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001308#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001309# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001310# define DEBUG_CLEAN 1
1311#else
1312# define DEBUG_CLEAN 0
1313#endif
1314
1315#if DEBUG_EXPAND
1316static void debug_print_strings(const char *prefix, char **vv)
1317{
1318 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001319 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001320 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001321 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001322}
1323#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001324# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001325#endif
1326
1327
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001328/* Leak hunting. Use hush_leaktool.sh for post-processing.
1329 */
1330#if LEAK_HUNTING
1331static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001332{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001333 void *ptr = xmalloc((size + 0xff) & ~0xff);
1334 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1335 return ptr;
1336}
1337static void *xxrealloc(int lineno, void *ptr, size_t size)
1338{
1339 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1340 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1341 return ptr;
1342}
1343static char *xxstrdup(int lineno, const char *str)
1344{
1345 char *ptr = xstrdup(str);
1346 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1347 return ptr;
1348}
1349static void xxfree(void *ptr)
1350{
1351 fdprintf(2, "free %p\n", ptr);
1352 free(ptr);
1353}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001354# define xmalloc(s) xxmalloc(__LINE__, s)
1355# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1356# define xstrdup(s) xxstrdup(__LINE__, s)
1357# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001358#endif
1359
1360
1361/* Syntax and runtime errors. They always abort scripts.
1362 * In interactive use they usually discard unparsed and/or unexecuted commands
1363 * and return to the prompt.
1364 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1365 */
1366#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001367# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001368# define syntax_error(lineno, msg) syntax_error(msg)
1369# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1370# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1371# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1372# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373#endif
1374
Denys Vlasenko39701202017-08-02 19:44:05 +02001375static void die_if_script(void)
1376{
1377 if (!G_interactive_fd) {
1378 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1379 xfunc_error_retval = G.last_exitcode;
1380 xfunc_die();
1381 }
1382}
1383
1384static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001385{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001386 va_list p;
1387
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388#if HUSH_DEBUG >= 2
1389 bb_error_msg("hush.c:%u", lineno);
1390#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001391 va_start(p, fmt);
1392 bb_verror_msg(fmt, p, NULL);
1393 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001394 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001395}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001396
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001397static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001398{
1399 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001400 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001401 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001402 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001403 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001404}
1405
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001406static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001407{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001408 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001409 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001410}
1411
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001412static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001413{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001414 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001415//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1416// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001417}
1418
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001419static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001420{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001421 char msg[2] = { ch, '\0' };
1422 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001423}
1424
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001425static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001426{
1427 char msg[2];
1428 msg[0] = ch;
1429 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001430#if HUSH_DEBUG >= 2
1431 bb_error_msg("hush.c:%u", lineno);
1432#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001433 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001434 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001435}
1436
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001437#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001438# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001439# undef syntax_error
1440# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001441# undef syntax_error_unterm_ch
1442# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001443# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001444#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001445# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001446# define syntax_error(msg) syntax_error(__LINE__, msg)
1447# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1448# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1449# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1450# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001451#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001452
Denis Vlasenko552433b2009-04-04 19:29:21 +00001453
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001454#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001455static void cmdedit_update_prompt(void);
1456#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001457# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001458#endif
1459
1460
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001461/* Utility functions
1462 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001463/* Replace each \x with x in place, return ptr past NUL. */
1464static char *unbackslash(char *src)
1465{
Denys Vlasenko71885402009-09-24 01:44:13 +02001466 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001467 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001468 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001469 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001470 if (*src != '\0') {
1471 /* \x -> x */
1472 *dst++ = *src++;
1473 continue;
1474 }
1475 /* else: "\<nul>". Do not delete this backslash.
1476 * Testcase: eval 'echo ok\'
1477 */
1478 *dst++ = '\\';
1479 /* fallthrough */
1480 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001481 if ((*dst++ = *src++) == '\0')
1482 break;
1483 }
1484 return dst;
1485}
1486
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001487static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001488{
1489 int i;
1490 unsigned count1;
1491 unsigned count2;
1492 char **v;
1493
1494 v = strings;
1495 count1 = 0;
1496 if (v) {
1497 while (*v) {
1498 count1++;
1499 v++;
1500 }
1501 }
1502 count2 = 0;
1503 v = add;
1504 while (*v) {
1505 count2++;
1506 v++;
1507 }
1508 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1509 v[count1 + count2] = NULL;
1510 i = count2;
1511 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001512 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001513 return v;
1514}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001515#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001516static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1517{
1518 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1519 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1520 return ptr;
1521}
1522#define add_strings_to_strings(strings, add, need_to_dup) \
1523 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1524#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001525
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001526/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001527static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001528{
1529 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001530 v[0] = add;
1531 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001532 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001533}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001534#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001535static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1536{
1537 char **ptr = add_string_to_strings(strings, add);
1538 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1539 return ptr;
1540}
1541#define add_string_to_strings(strings, add) \
1542 xx_add_string_to_strings(__LINE__, strings, add)
1543#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001544
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001545static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001546{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001547 char **v;
1548
1549 if (!strings)
1550 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001551 v = strings;
1552 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001553 free(*v);
1554 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001555 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001556 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001557}
1558
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001559static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001560{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001561 int newfd;
1562 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001563 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1564 if (newfd >= 0) {
1565 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1566 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1567 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001568 if (errno == EBUSY)
1569 goto repeat;
1570 if (errno == EINTR)
1571 goto repeat;
1572 }
1573 return newfd;
1574}
1575
Denys Vlasenko657e9002017-07-30 23:34:04 +02001576static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001577{
1578 int newfd;
1579 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001580 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001581 if (newfd < 0) {
1582 if (errno == EBUSY)
1583 goto repeat;
1584 if (errno == EINTR)
1585 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001586 /* fd was not open? */
1587 if (errno == EBADF)
1588 return fd;
1589 xfunc_die();
1590 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001591 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1592 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001593 close(fd);
1594 return newfd;
1595}
1596
1597
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001598/* Manipulating HFILEs */
1599static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001600{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001601 HFILE *fp;
1602 int fd;
1603
1604 fd = STDIN_FILENO;
1605 if (name) {
1606 fd = open(name, O_RDONLY | O_CLOEXEC);
1607 if (fd < 0)
1608 return NULL;
1609 if (O_CLOEXEC == 0) /* ancient libc */
1610 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001611 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001612
1613 fp = xmalloc(sizeof(*fp));
1614 fp->is_stdin = (name == NULL);
1615 fp->fd = fd;
1616 fp->cur = fp->end = fp->buf;
1617 fp->next_hfile = G.HFILE_list;
1618 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619 return fp;
1620}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001621static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001622{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001623 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001624 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001625 HFILE *cur = *pp;
1626 if (cur == fp) {
1627 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628 break;
1629 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001630 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001631 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001632 if (fp->fd >= 0)
1633 close(fp->fd);
1634 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001635}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001636static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001637{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001638 int n;
1639
1640 if (fp->fd < 0) {
1641 /* Already saw EOF */
1642 return EOF;
1643 }
1644 /* Try to buffer more input */
1645 fp->cur = fp->buf;
1646 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1647 if (n < 0) {
1648 bb_perror_msg("read error");
1649 n = 0;
1650 }
1651 fp->end = fp->buf + n;
1652 if (n == 0) {
1653 /* EOF/error */
1654 close(fp->fd);
1655 fp->fd = -1;
1656 return EOF;
1657 }
1658 return (unsigned char)(*fp->cur++);
1659}
1660/* Inlined for common case of non-empty buffer.
1661 */
1662static ALWAYS_INLINE int hfgetc(HFILE *fp)
1663{
1664 if (fp->cur < fp->end)
1665 return (unsigned char)(*fp->cur++);
1666 /* Buffer empty */
1667 return refill_HFILE_and_getc(fp);
1668}
1669static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1670{
1671 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001672 while (fl) {
1673 if (fd == fl->fd) {
1674 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001675 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001676 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 +02001677 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001678 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001679 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001680 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001681#if ENABLE_HUSH_MODE_X
1682 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1683 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1684 return 1; /* "found and moved" */
1685 }
1686#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001687 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001688}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001689#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001690static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001691{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001692 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001693 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001694 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001695 * It is disastrous if we share memory with a vforked parent.
1696 * I'm not sure we never come here after vfork.
1697 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001698 *
1699 * ">" instead of ">=": we don't close fd#0,
1700 * interactive shell uses hfopen(NULL) as stdin input
1701 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1702 * If we'd close it here, then e.g. interactive "set | sort"
1703 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001704 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001705 if (fl->fd > 0)
1706 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001707 close(fl->fd);
1708 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001709 }
1710}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001711#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001712static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001713{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001714 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001715 while (fl) {
1716 if (fl->fd == fd)
1717 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001718 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001719 }
1720 return 0;
1721}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001722
1723
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001724/* Helpers for setting new $n and restoring them back
1725 */
1726typedef struct save_arg_t {
1727 char *sv_argv0;
1728 char **sv_g_argv;
1729 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001730 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001731} save_arg_t;
1732
1733static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1734{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001735 sv->sv_argv0 = argv[0];
1736 sv->sv_g_argv = G.global_argv;
1737 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001738 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001739
1740 argv[0] = G.global_argv[0]; /* retain $0 */
1741 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001742 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001743
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001744 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001745}
1746
1747static void restore_G_args(save_arg_t *sv, char **argv)
1748{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001749#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001750 if (G.global_args_malloced) {
1751 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001752 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001753 while (*++pp) /* note: does not free $0 */
1754 free(*pp);
1755 free(G.global_argv);
1756 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001757#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001758 argv[0] = sv->sv_argv0;
1759 G.global_argv = sv->sv_g_argv;
1760 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001761 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001762}
1763
1764
Denis Vlasenkod5762932009-03-31 11:22:57 +00001765/* Basic theory of signal handling in shell
1766 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001767 * This does not describe what hush does, rather, it is current understanding
1768 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001769 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1770 *
1771 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1772 * is finished or backgrounded. It is the same in interactive and
1773 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001774 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001775 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001776 * backgrounds (i.e. stops) or kills all members of currently running
1777 * pipe.
1778 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001779 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001780 * or by SIGINT in interactive shell.
1781 *
1782 * Trap handlers will execute even within trap handlers. (right?)
1783 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001784 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1785 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001786 *
1787 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001788 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001789 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001790 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001791 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001792 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001793 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001794 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001795 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001796 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001797 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001798 *
1799 * SIGQUIT: ignore
1800 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001801 * SIGHUP (interactive):
1802 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001803 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001804 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1805 * that all pipe members are stopped. Try this in bash:
1806 * while :; do :; done - ^Z does not background it
1807 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001808 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001809 * of the command line, show prompt. NB: ^C does not send SIGINT
1810 * to interactive shell while shell is waiting for a pipe,
1811 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001812 * Example 1: this waits 5 sec, but does not execute ls:
1813 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1814 * Example 2: this does not wait and does not execute ls:
1815 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1816 * Example 3: this does not wait 5 sec, but executes ls:
1817 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001818 * Example 4: this does not wait and does not execute ls:
1819 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001820 *
1821 * (What happens to signals which are IGN on shell start?)
1822 * (What happens with signal mask on shell start?)
1823 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001824 * Old implementation
1825 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001826 * We use in-kernel pending signal mask to determine which signals were sent.
1827 * We block all signals which we don't want to take action immediately,
1828 * i.e. we block all signals which need to have special handling as described
1829 * above, and all signals which have traps set.
1830 * After each pipe execution, we extract any pending signals via sigtimedwait()
1831 * and act on them.
1832 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001833 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001834 * sigset_t blocked_set: current blocked signal set
1835 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001836 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001837 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001838 * "trap 'cmd' SIGxxx":
1839 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001840 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001841 * unblock signals with special interactive handling
1842 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001843 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001844 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001845 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001846 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001847 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001848 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001849 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001850 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001851 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001852 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001853 * Standard says "When a subshell is entered, traps that are not being ignored
1854 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001855 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001856 *
1857 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001858 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001859 * masked signals are not visible!
1860 *
1861 * New implementation
1862 * ==================
1863 * We record each signal we are interested in by installing signal handler
1864 * for them - a bit like emulating kernel pending signal mask in userspace.
1865 * We are interested in: signals which need to have special handling
1866 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001867 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001868 * After each pipe execution, we extract any pending signals
1869 * and act on them.
1870 *
1871 * unsigned special_sig_mask: a mask of shell-special signals.
1872 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1873 * char *traps[sig] if trap for sig is set (even if it's '').
1874 * sigset_t pending_set: set of sigs we received.
1875 *
1876 * "trap - SIGxxx":
1877 * if sig is in special_sig_mask, set handler back to:
1878 * record_pending_signo, or to IGN if it's a tty stop signal
1879 * if sig is in fatal_sig_mask, set handler back to sigexit.
1880 * else: set handler back to SIG_DFL
1881 * "trap 'cmd' SIGxxx":
1882 * set handler to record_pending_signo.
1883 * "trap '' SIGxxx":
1884 * set handler to SIG_IGN.
1885 * after [v]fork, if we plan to be a shell:
1886 * set signals with special interactive handling to SIG_DFL
1887 * (because child shell is not interactive),
1888 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1889 * after [v]fork, if we plan to exec:
1890 * POSIX says fork clears pending signal mask in child - no need to clear it.
1891 *
1892 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1893 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1894 *
1895 * Note (compat):
1896 * Standard says "When a subshell is entered, traps that are not being ignored
1897 * are set to the default actions". bash interprets it so that traps which
1898 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001899 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001900enum {
1901 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001902 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001903 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001904 | (1 << SIGHUP)
1905 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001906 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001907#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001908 | (1 << SIGTTIN)
1909 | (1 << SIGTTOU)
1910 | (1 << SIGTSTP)
1911#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001913};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001914
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001915static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001916{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001917 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001918#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001919 if (sig == SIGCHLD) {
1920 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001921//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 +02001922 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001923#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001924}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001925
Denys Vlasenko0806e402011-05-12 23:06:20 +02001926static sighandler_t install_sighandler(int sig, sighandler_t handler)
1927{
1928 struct sigaction old_sa;
1929
1930 /* We could use signal() to install handlers... almost:
1931 * except that we need to mask ALL signals while handlers run.
1932 * I saw signal nesting in strace, race window isn't small.
1933 * SA_RESTART is also needed, but in Linux, signal()
1934 * sets SA_RESTART too.
1935 */
1936 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1937 /* sigfillset(&G.sa.sa_mask); - already done */
1938 /* G.sa.sa_flags = SA_RESTART; - already done */
1939 G.sa.sa_handler = handler;
1940 sigaction(sig, &G.sa, &old_sa);
1941 return old_sa.sa_handler;
1942}
1943
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001944static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001945
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001946static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001947static void restore_ttypgrp_and__exit(void)
1948{
1949 /* xfunc has failed! die die die */
1950 /* no EXIT traps, this is an escape hatch! */
1951 G.exiting = 1;
1952 hush_exit(xfunc_error_retval);
1953}
1954
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001955#if ENABLE_HUSH_JOB
1956
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001957/* Needed only on some libc:
1958 * It was observed that on exit(), fgetc'ed buffered data
1959 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1960 * With the net effect that even after fork(), not vfork(),
1961 * exit() in NOEXECed applet in "sh SCRIPT":
1962 * noexec_applet_here
1963 * echo END_OF_SCRIPT
1964 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1965 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001966 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001967 * and in `cmd` handling.
1968 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1969 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001970static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001971static void fflush_and__exit(void)
1972{
1973 fflush_all();
1974 _exit(xfunc_error_retval);
1975}
1976
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001977/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001978# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001979/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001980# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001981
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001982/* Restores tty foreground process group, and exits.
1983 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001984 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001985 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001986 * We also call it if xfunc is exiting.
1987 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001988static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001989static void sigexit(int sig)
1990{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001991 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001992 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001993 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1994 /* Disable all signals: job control, SIGPIPE, etc.
1995 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1996 */
1997 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001998 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001999 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002000
2001 /* Not a signal, just exit */
2002 if (sig <= 0)
2003 _exit(- sig);
2004
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002005 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002006}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002007#else
2008
Denys Vlasenko8391c482010-05-22 17:50:43 +02002009# define disable_restore_tty_pgrp_on_exit() ((void)0)
2010# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002011
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002012#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002013
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002014static sighandler_t pick_sighandler(unsigned sig)
2015{
2016 sighandler_t handler = SIG_DFL;
2017 if (sig < sizeof(unsigned)*8) {
2018 unsigned sigmask = (1 << sig);
2019
2020#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002021 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002022 if (G_fatal_sig_mask & sigmask)
2023 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002024 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002025#endif
2026 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002027 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002028 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002029 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002030 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002031 * in an endless loop when we try to do some
2032 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002033 */
2034 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2035 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002036 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002037 }
2038 return handler;
2039}
2040
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002041/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002042static void hush_exit(int exitcode)
2043{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002044#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2045 save_history(G.line_input_state);
2046#endif
2047
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002048 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002049 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002050 char *argv[3];
2051 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002052 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002053 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002054 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002055 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002056 * "trap" will still show it, if executed
2057 * in the handler */
2058 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002059 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002060
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002061#if ENABLE_FEATURE_CLEAN_UP
2062 {
2063 struct variable *cur_var;
2064 if (G.cwd != bb_msg_unknown)
2065 free((char*)G.cwd);
2066 cur_var = G.top_var;
2067 while (cur_var) {
2068 struct variable *tmp = cur_var;
2069 if (!cur_var->max_len)
2070 free(cur_var->varstr);
2071 cur_var = cur_var->next;
2072 free(tmp);
2073 }
2074 }
2075#endif
2076
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002077 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002078#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002079 sigexit(- (exitcode & 0xff));
2080#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002081 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002082#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002083}
2084
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002085
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002086//TODO: return a mask of ALL handled sigs?
2087static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002088{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002089 int last_sig = 0;
2090
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002091 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002092 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002093
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002094 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002095 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002096 sig = 0;
2097 do {
2098 sig++;
2099 if (sigismember(&G.pending_set, sig)) {
2100 sigdelset(&G.pending_set, sig);
2101 goto got_sig;
2102 }
2103 } while (sig < NSIG);
2104 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002105 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002106 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002107 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002108 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002109 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002110 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002111 char *argv[3];
2112 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002113 argv[1] = xstrdup(G_traps[sig]);
2114 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002115 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002116 save_rcode = G.last_exitcode;
2117 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002118 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002119//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002120 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002121 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002122 } /* else: "" trap, ignoring signal */
2123 continue;
2124 }
2125 /* not a trap: special action */
2126 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002127 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002128 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002129 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002130 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002131 break;
2132#if ENABLE_HUSH_JOB
2133 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002134//TODO: why are we doing this? ash and dash don't do this,
2135//they have no handler for SIGHUP at all,
2136//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002137 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002138 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002139 /* bash is observed to signal whole process groups,
2140 * not individual processes */
2141 for (job = G.job_list; job; job = job->next) {
2142 if (job->pgrp <= 0)
2143 continue;
2144 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2145 if (kill(- job->pgrp, SIGHUP) == 0)
2146 kill(- job->pgrp, SIGCONT);
2147 }
2148 sigexit(SIGHUP);
2149 }
2150#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002151#if ENABLE_HUSH_FAST
2152 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002153 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002154 G.count_SIGCHLD++;
2155//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2156 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002157 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002158 * This simplifies wait builtin a bit.
2159 */
2160 break;
2161#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002162 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002163 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002164 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002165 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002166 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002167 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002168 * in interactive shell, because TERM is ignored.
2169 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002170 break;
2171 }
2172 }
2173 return last_sig;
2174}
2175
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002176
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002177static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002178{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002179 if (force || G.cwd == NULL) {
2180 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2181 * we must not try to free(bb_msg_unknown) */
2182 if (G.cwd == bb_msg_unknown)
2183 G.cwd = NULL;
2184 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2185 if (!G.cwd)
2186 G.cwd = bb_msg_unknown;
2187 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002188 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002189}
2190
Denis Vlasenko83506862007-11-23 13:11:42 +00002191
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002192/*
2193 * Shell and environment variable support
2194 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002195static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002196{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002197 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002200 pp = &G.top_var;
2201 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002203 return pp;
2204 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205 }
2206 return NULL;
2207}
2208
Denys Vlasenko03dad222010-01-12 23:29:57 +01002209static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002210{
Denys Vlasenko29082232010-07-16 13:52:32 +02002211 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002212 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002213
2214 if (G.expanded_assignments) {
2215 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002216 while (*cpp) {
2217 char *cp = *cpp;
2218 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2219 return cp + len + 1;
2220 cpp++;
2221 }
2222 }
2223
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002224 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002225 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002226 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002227
Denys Vlasenkodea47882009-10-09 15:40:49 +02002228 if (strcmp(name, "PPID") == 0)
2229 return utoa(G.root_ppid);
2230 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002231#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002232 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002233 return utoa(next_random(&G.random_gen));
2234#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002235#if BASH_EPOCH_VARS
2236 {
2237 const char *fmt = NULL;
2238 if (strcmp(name, "EPOCHSECONDS") == 0)
2239 fmt = "%lu";
2240 else if (strcmp(name, "EPOCHREALTIME") == 0)
2241 fmt = "%lu.%06u";
2242 if (fmt) {
2243 struct timeval tv;
2244 gettimeofday(&tv, NULL);
2245 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2246 (unsigned)tv.tv_usec);
2247 return G.epoch_buf;
2248 }
2249 }
2250#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002251 return NULL;
2252}
2253
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002254static void handle_changed_special_names(const char *name, unsigned name_len)
2255{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002256 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2257 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2258 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002259 cmdedit_update_prompt();
2260 return;
2261 }
2262
2263 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2264 && name_len == 6
2265 ) {
2266#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002267 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002268 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002269 return;
2270 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002271#endif
2272#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002273 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002274 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002275 return;
2276 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002277#endif
2278 }
2279}
2280
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002282 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002283 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002284#define SETFLAG_EXPORT (1 << 0)
2285#define SETFLAG_UNEXPORT (1 << 1)
2286#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002287#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002288static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289{
Denys Vlasenko61407802018-04-04 21:14:28 +02002290 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002292 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002293 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002294 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002295 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002296
Denis Vlasenko950bd722009-04-21 11:23:56 +00002297 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002298 if (HUSH_DEBUG && !eq_sign)
2299 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002300
Denis Vlasenko950bd722009-04-21 11:23:56 +00002301 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002302 cur_pp = &G.top_var;
2303 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002304 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002305 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002306 continue;
2307 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002308
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002309 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002311 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002312 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002313//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2314//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 return -1;
2316 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002317 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002318 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2319 *eq_sign = '\0';
2320 unsetenv(str);
2321 *eq_sign = '=';
2322 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002323 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002324 /* bash 3.2.33(1) and exported vars:
2325 * # export z=z
2326 * # f() { local z=a; env | grep ^z; }
2327 * # f
2328 * z=a
2329 * # env | grep ^z
2330 * z=z
2331 */
2332 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002333 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002334 /* New variable is local ("local VAR=VAL" or
2335 * "VAR=VAL cmd")
2336 * and existing one is global, or local
2337 * on a lower level that new one.
2338 * Remove it from global variable list:
2339 */
2340 *cur_pp = cur->next;
2341 if (G.shadowed_vars_pp) {
2342 /* Save in "shadowed" list */
2343 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2344 cur->flg_export ? "exported " : "",
2345 cur->varstr, cur->var_nest_level, str, local_lvl
2346 );
2347 cur->next = *G.shadowed_vars_pp;
2348 *G.shadowed_vars_pp = cur;
2349 } else {
2350 /* Came from pseudo_exec_argv(), no need to save: delete it */
2351 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2352 cur->flg_export ? "exported " : "",
2353 cur->varstr, cur->var_nest_level, str, local_lvl
2354 );
2355 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2356 free_me = cur->varstr; /* then free it later */
2357 free(cur);
2358 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002359 break;
2360 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002361
Denis Vlasenko950bd722009-04-21 11:23:56 +00002362 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002363 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002364 free_and_exp:
2365 free(str);
2366 goto exp;
2367 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002368
2369 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002370 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002371 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002372 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002373 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002374 strcpy(cur->varstr, str);
2375 goto free_and_exp;
2376 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002377 /* Can't reuse */
2378 cur->max_len = 0;
2379 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002380 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002381 /* max_len == 0 signifies "malloced" var, which we can
2382 * (and have to) free. But we can't free(cur->varstr) here:
2383 * if cur->flg_export is 1, it is in the environment.
2384 * We should either unsetenv+free, or wait until putenv,
2385 * then putenv(new)+free(old).
2386 */
2387 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002388 goto set_str_and_exp;
2389 }
2390
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002391 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002392 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002393 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002394 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002395 cur->next = *cur_pp;
2396 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002397
2398 set_str_and_exp:
2399 cur->varstr = str;
2400 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002401#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002402 if (flags & SETFLAG_MAKE_RO) {
2403 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002404 }
2405#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002406 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002407 cur->flg_export = 1;
2408 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002409 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002410 cur->flg_export = 0;
2411 /* unsetenv was already done */
2412 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002413 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002414 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002415 i = putenv(cur->varstr);
2416 /* only now we can free old exported malloced string */
2417 free(free_me);
2418 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002419 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002420 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002421 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002422
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002423 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002424
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002425 return 0;
2426}
2427
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002428static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2429{
2430 char *var = xasprintf("%s=%s", name, val);
2431 set_local_var(var, /*flag:*/ 0);
2432}
2433
Denys Vlasenko6db47842009-09-05 20:15:17 +02002434/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002435static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002436{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002437 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002438}
2439
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002440#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002441static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002442{
2443 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002444 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002445
Denys Vlasenko61407802018-04-04 21:14:28 +02002446 cur_pp = &G.top_var;
2447 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002448 if (strncmp(cur->varstr, name, name_len) == 0
2449 && cur->varstr[name_len] == '='
2450 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451 if (cur->flg_read_only) {
2452 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002453 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002454 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002455
Denys Vlasenko61407802018-04-04 21:14:28 +02002456 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002457 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2458 bb_unsetenv(cur->varstr);
2459 if (!cur->max_len)
2460 free(cur->varstr);
2461 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002462
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002463 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002464 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002465 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002466 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002467
2468 /* Handle "unset PS1" et al even if did not find the variable to unset */
2469 handle_changed_special_names(name, name_len);
2470
Mike Frysingerd690f682009-03-30 06:50:54 +00002471 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002472}
2473
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002474static int unset_local_var(const char *name)
2475{
2476 return unset_local_var_len(name, strlen(name));
2477}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002478#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002479
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002480
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002481/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002482 * Helpers for "var1=val1 var2=val2 cmd" feature
2483 */
2484static void add_vars(struct variable *var)
2485{
2486 struct variable *next;
2487
2488 while (var) {
2489 next = var->next;
2490 var->next = G.top_var;
2491 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002492 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002493 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002494 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002495 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002496 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002497 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002498 var = next;
2499 }
2500}
2501
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002502/* We put strings[i] into variable table and possibly putenv them.
2503 * If variable is read only, we can free the strings[i]
2504 * which attempts to overwrite it.
2505 * The strings[] vector itself is freed.
2506 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002507static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002508{
2509 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002510
2511 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002512 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002513
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002514 s = strings;
2515 while (*s) {
2516 struct variable *var_p;
2517 struct variable **var_pp;
2518 char *eq;
2519
2520 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002521 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002522 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002523 var_pp = get_ptr_to_local_var(*s, eq - *s);
2524 if (var_pp) {
2525 var_p = *var_pp;
2526 if (var_p->flg_read_only) {
2527 char **p;
2528 bb_error_msg("%s: readonly variable", *s);
2529 /*
2530 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2531 * If VAR is readonly, leaving it in the list
2532 * after asssignment error (msg above)
2533 * causes doubled error message later, on unset.
2534 */
2535 debug_printf_env("removing/freeing '%s' element\n", *s);
2536 free(*s);
2537 p = s;
2538 do { *p = p[1]; p++; } while (*p);
2539 goto next;
2540 }
2541 /* below, set_local_var() with nest level will
2542 * "shadow" (remove) this variable from
2543 * global linked list.
2544 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002545 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002546 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2547 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002548 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002549 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002550 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002551 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002552}
2553
2554
2555/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002556 * Unicode helper
2557 */
2558static void reinit_unicode_for_hush(void)
2559{
2560 /* Unicode support should be activated even if LANG is set
2561 * _during_ shell execution, not only if it was set when
2562 * shell was started. Therefore, re-check LANG every time:
2563 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002564 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2565 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002566 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002567 const char *s = get_local_var_value("LC_ALL");
2568 if (!s) s = get_local_var_value("LC_CTYPE");
2569 if (!s) s = get_local_var_value("LANG");
2570 reinit_unicode(s);
2571 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002572}
2573
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002574/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002575 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577
2578#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002579/* To test correct lineedit/interactive behavior, type from command line:
2580 * echo $P\
2581 * \
2582 * AT\
2583 * H\
2584 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002585 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002586 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002587# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002588static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002589{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002590 G.PS1 = get_local_var_value("PS1");
2591 if (G.PS1 == NULL)
2592 G.PS1 = "";
2593 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002594 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002595 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002596}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002597# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002598static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002599{
2600 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002601
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002602 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002603
2604 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2605 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002606 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002607 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2608 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002609 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002610 /* bash uses $PWD value, even if it is set by user.
2611 * It uses current dir only if PWD is unset.
2612 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002613 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002614 }
2615 prompt_str = G.PS1;
2616 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002617 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002618 return prompt_str;
2619}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002620static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002621{
2622 int r;
2623 const char *prompt_str;
2624
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002625 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002626# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002627 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002628 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002629 if (G.flag_SIGINT) {
2630 /* There was ^C'ed, make it look prettier: */
2631 bb_putchar('\n');
2632 G.flag_SIGINT = 0;
2633 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002634 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002635 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002636 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002637 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002638 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002639 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002640 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002641 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002642 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002643 if (r != 0 && !G.flag_SIGINT)
2644 break;
2645 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002646 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2647 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002648 G.last_exitcode = 128 + SIGINT;
2649 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002650 if (r < 0) {
2651 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002652 i->p = NULL;
2653 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002654 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002655 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002656 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002657 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002658# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002659 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002660 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002661 if (i->last_char == '\0' || i->last_char == '\n') {
2662 /* Why check_and_run_traps here? Try this interactively:
2663 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2664 * $ <[enter], repeatedly...>
2665 * Without check_and_run_traps, handler never runs.
2666 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002667 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002668 fputs(prompt_str, stdout);
2669 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002670 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002671//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002672 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002673 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2674 * no ^C masking happens during fgetc, no special code for ^C:
2675 * it generates SIGINT as usual.
2676 */
2677 check_and_run_traps();
2678 if (G.flag_SIGINT)
2679 G.last_exitcode = 128 + SIGINT;
2680 if (r != '\0')
2681 break;
2682 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002683 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002684# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002685}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002686/* This is the magic location that prints prompts
2687 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002688static int fgetc_interactive(struct in_str *i)
2689{
2690 int ch;
2691 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002692 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002693 /* Returns first char (or EOF), the rest is in i->p[] */
2694 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002695 G.promptmode = 1; /* PS2 */
2696 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002697 } else {
2698 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002699 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002700 }
2701 return ch;
2702}
2703#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002704static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002705{
2706 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002707 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002708 return ch;
2709}
2710#endif /* INTERACTIVE */
2711
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002712static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002713{
2714 int ch;
2715
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002716 if (!i->file) {
2717 /* string-based in_str */
2718 ch = (unsigned char)*i->p;
2719 if (ch != '\0') {
2720 i->p++;
2721 i->last_char = ch;
2722 return ch;
2723 }
2724 return EOF;
2725 }
2726
2727 /* FILE-based in_str */
2728
Denys Vlasenko4074d492016-09-30 01:49:53 +02002729#if ENABLE_FEATURE_EDITING
2730 /* This can be stdin, check line editing char[] buffer */
2731 if (i->p && *i->p != '\0') {
2732 ch = (unsigned char)*i->p++;
2733 goto out;
2734 }
2735#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002736 /* peek_buf[] is an int array, not char. Can contain EOF. */
2737 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002738 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002739 int ch2 = i->peek_buf[1];
2740 i->peek_buf[0] = ch2;
2741 if (ch2 == 0) /* very likely, avoid redundant write */
2742 goto out;
2743 i->peek_buf[1] = 0;
2744 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002745 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002746
Denys Vlasenko4074d492016-09-30 01:49:53 +02002747 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002748 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002749 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002750 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002751#if ENABLE_HUSH_LINENO_VAR
2752 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002753 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002754 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2755 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002756#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002757 return ch;
2758}
2759
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002760static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002761{
2762 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002763
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002764 if (!i->file) {
2765 /* string-based in_str */
2766 /* Doesn't report EOF on NUL. None of the callers care. */
2767 return (unsigned char)*i->p;
2768 }
2769
2770 /* FILE-based in_str */
2771
Denys Vlasenko4074d492016-09-30 01:49:53 +02002772#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002773 /* This can be stdin, check line editing char[] buffer */
2774 if (i->p && *i->p != '\0')
2775 return (unsigned char)*i->p;
2776#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002777 /* peek_buf[] is an int array, not char. Can contain EOF. */
2778 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002779 if (ch != 0)
2780 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002781
Denys Vlasenko4074d492016-09-30 01:49:53 +02002782 /* Need to get a new char */
2783 ch = fgetc_interactive(i);
2784 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2785
2786 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2787#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2788 if (i->p) {
2789 i->p -= 1;
2790 return ch;
2791 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002792#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002793 i->peek_buf[0] = ch;
2794 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002795 return ch;
2796}
2797
Denys Vlasenko4074d492016-09-30 01:49:53 +02002798/* Only ever called if i_peek() was called, and did not return EOF.
2799 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2800 * not end-of-line. Therefore we never need to read a new editing line here.
2801 */
2802static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002803{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002804 int ch;
2805
2806 /* There are two cases when i->p[] buffer exists.
2807 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002808 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002809 * In both cases, we know that i->p[0] exists and not NUL, and
2810 * the peek2 result is in i->p[1].
2811 */
2812 if (i->p)
2813 return (unsigned char)i->p[1];
2814
2815 /* Now we know it is a file-based in_str. */
2816
2817 /* peek_buf[] is an int array, not char. Can contain EOF. */
2818 /* Is there 2nd char? */
2819 ch = i->peek_buf[1];
2820 if (ch == 0) {
2821 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002822 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002823 i->peek_buf[1] = ch;
2824 }
2825
2826 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2827 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002828}
2829
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002830static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2831{
2832 for (;;) {
2833 int ch, ch2;
2834
2835 ch = i_getch(input);
2836 if (ch != '\\')
2837 return ch;
2838 ch2 = i_peek(input);
2839 if (ch2 != '\n')
2840 return ch;
2841 /* backslash+newline, skip it */
2842 i_getch(input);
2843 }
2844}
2845
2846/* Note: this function _eats_ \<newline> pairs, safe to use plain
2847 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2848 */
2849static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2850{
2851 for (;;) {
2852 int ch, ch2;
2853
2854 ch = i_peek(input);
2855 if (ch != '\\')
2856 return ch;
2857 ch2 = i_peek2(input);
2858 if (ch2 != '\n')
2859 return ch;
2860 /* backslash+newline, skip it */
2861 i_getch(input);
2862 i_getch(input);
2863 }
2864}
2865
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002866static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002867{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002868 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002869 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002870 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002871}
2872
2873static void setup_string_in_str(struct in_str *i, const char *s)
2874{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002875 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002876 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002877 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002878}
2879
2880
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002881/*
2882 * o_string support
2883 */
2884#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002885
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002886static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002887{
2888 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002889 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002890 if (o->data)
2891 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002892}
2893
Denys Vlasenko18567402018-07-20 17:51:31 +02002894static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002895{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002896 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002897 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002898}
2899
Denys Vlasenko18567402018-07-20 17:51:31 +02002900static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002901{
2902 free(o->data);
2903}
2904
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002905static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002906{
2907 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002908 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002909 o->data = xrealloc(o->data, 1 + o->maxlen);
2910 }
2911}
2912
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002913static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002914{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002915 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002916 if (o->length < o->maxlen) {
2917 /* likely. avoid o_grow_by() call */
2918 add:
2919 o->data[o->length] = ch;
2920 o->length++;
2921 o->data[o->length] = '\0';
2922 return;
2923 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002924 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002925 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002926}
2927
Denys Vlasenko657086a2016-09-29 18:07:42 +02002928#if 0
2929/* Valid only if we know o_string is not empty */
2930static void o_delchr(o_string *o)
2931{
2932 o->length--;
2933 o->data[o->length] = '\0';
2934}
2935#endif
2936
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002937static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002938{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002939 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002940 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002941 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002942}
2943
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002944static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002945{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002946 o_addblock(o, str, strlen(str));
2947}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002948
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002949static void o_addstr_with_NUL(o_string *o, const char *str)
2950{
2951 o_addblock(o, str, strlen(str) + 1);
2952}
2953
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002954#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002955static void nommu_addchr(o_string *o, int ch)
2956{
2957 if (o)
2958 o_addchr(o, ch);
2959}
2960#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002961# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002962#endif
2963
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002964#if ENABLE_HUSH_MODE_X
2965static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002966{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002967 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002968}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002969static void x_mode_addstr(const char *str)
2970{
2971 o_addstr(&G.x_mode_buf, str);
2972}
2973static void x_mode_addblock(const char *str, int len)
2974{
2975 o_addblock(&G.x_mode_buf, str, len);
2976}
2977static void x_mode_prefix(void)
2978{
2979 int n = G.x_mode_depth;
2980 do x_mode_addchr('+'); while (--n >= 0);
2981}
2982static void x_mode_flush(void)
2983{
2984 int len = G.x_mode_buf.length;
2985 if (len <= 0)
2986 return;
2987 if (G.x_mode_fd > 0) {
2988 G.x_mode_buf.data[len] = '\n';
2989 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2990 }
2991 G.x_mode_buf.length = 0;
2992}
2993#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002994
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002995/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002996 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002997 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2998 * Apparently, on unquoted $v bash still does globbing
2999 * ("v='*.txt'; echo $v" prints all .txt files),
3000 * but NOT brace expansion! Thus, there should be TWO independent
3001 * quoting mechanisms on $v expansion side: one protects
3002 * $v from brace expansion, and other additionally protects "$v" against globbing.
3003 * We have only second one.
3004 */
3005
Denys Vlasenko9e800222010-10-03 14:28:04 +02003006#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003007# define MAYBE_BRACES "{}"
3008#else
3009# define MAYBE_BRACES ""
3010#endif
3011
Eric Andersen25f27032001-04-26 23:22:31 +00003012/* My analysis of quoting semantics tells me that state information
3013 * is associated with a destination, not a source.
3014 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003015static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003016{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003017 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003018 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003019 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003020 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003021 o_grow_by(o, sz);
3022 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003023 o->data[o->length] = '\\';
3024 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003025 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003026 o->data[o->length] = ch;
3027 o->length++;
3028 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003029}
3030
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003031static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003032{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003033 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003034 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3035 && strchr("*?[\\" MAYBE_BRACES, ch)
3036 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003037 sz++;
3038 o->data[o->length] = '\\';
3039 o->length++;
3040 }
3041 o_grow_by(o, sz);
3042 o->data[o->length] = ch;
3043 o->length++;
3044 o->data[o->length] = '\0';
3045}
3046
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003047static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003048{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003049 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003050 char ch;
3051 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003052 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003053 if (ordinary_cnt > len) /* paranoia */
3054 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003055 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003056 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003057 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003058 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003059 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003060
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003061 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003062 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003063 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003064 sz++;
3065 o->data[o->length] = '\\';
3066 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003067 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003068 o_grow_by(o, sz);
3069 o->data[o->length] = ch;
3070 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003071 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003072 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003073}
3074
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003075static void o_addQblock(o_string *o, const char *str, int len)
3076{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003077 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003078 o_addblock(o, str, len);
3079 return;
3080 }
3081 o_addqblock(o, str, len);
3082}
3083
Denys Vlasenko38292b62010-09-05 14:49:40 +02003084static void o_addQstr(o_string *o, const char *str)
3085{
3086 o_addQblock(o, str, strlen(str));
3087}
3088
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003089/* A special kind of o_string for $VAR and `cmd` expansion.
3090 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003091 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003092 * list[i] contains an INDEX (int!) into this string data.
3093 * It means that if list[] needs to grow, data needs to be moved higher up
3094 * but list[i]'s need not be modified.
3095 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003096 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003097 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3098 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003099#if DEBUG_EXPAND || DEBUG_GLOB
3100static void debug_print_list(const char *prefix, o_string *o, int n)
3101{
3102 char **list = (char**)o->data;
3103 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3104 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003105
3106 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003107 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 +02003108 prefix, list, n, string_start, o->length, o->maxlen,
3109 !!(o->o_expflags & EXP_FLAG_GLOB),
3110 o->has_quoted_part,
3111 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003112 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003113 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003114 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3115 o->data + (int)(uintptr_t)list[i] + string_start,
3116 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003117 i++;
3118 }
3119 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003120 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003121 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003122 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003123 }
3124}
3125#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003126# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003127#endif
3128
3129/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3130 * in list[n] so that it points past last stored byte so far.
3131 * It returns n+1. */
3132static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003133{
3134 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003135 int string_start;
3136 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003137
3138 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003139 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3140 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003141 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003142 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003143 /* list[n] points to string_start, make space for 16 more pointers */
3144 o->maxlen += 0x10 * sizeof(list[0]);
3145 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003146 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003147 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003148 /*
3149 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3150 * check. (grep for -prev-ifs-check-).
3151 * Ensure that argv[-1][last] is not garbage
3152 * but zero bytes, to save index check there.
3153 */
3154 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003155 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003156 } else {
3157 debug_printf_list("list[%d]=%d string_start=%d\n",
3158 n, string_len, string_start);
3159 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003160 } else {
3161 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003162 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3163 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003164 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3165 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003166 o->has_empty_slot = 0;
3167 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003168 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003169 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003170 return n + 1;
3171}
3172
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003173/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003174static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003175{
3176 char **list = (char**)o->data;
3177 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3178
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003179 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003180}
3181
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003182/*
3183 * Globbing routines.
3184 *
3185 * Most words in commands need to be globbed, even ones which are
3186 * (single or double) quoted. This stems from the possiblity of
3187 * constructs like "abc"* and 'abc'* - these should be globbed.
3188 * Having a different code path for fully-quoted strings ("abc",
3189 * 'abc') would only help performance-wise, but we still need
3190 * code for partially-quoted strings.
3191 *
3192 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003193 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003194 * to a string, then globbed, and if globbing does not match anything,
3195 * it is used verbatim". Here are two examples where it fails:
3196 *
3197 * echo 'b\*'?
3198 *
3199 * The globbing can't be avoided (because of '?' at the end).
3200 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3201 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003202 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003203 * Now, look at this:
3204 *
3205 * v='\\\*'; echo b$v?
3206 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003207 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003208 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003209 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003210 *
3211 * ash implements this by having an encoded representation of the word
3212 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3213 * Glob pattern is derived from it. If glob fails, the decision what result
3214 * should be is made using that encoded representation. Not glob pattern.
3215 */
3216
Denys Vlasenko9e800222010-10-03 14:28:04 +02003217#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003218/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3219 * first, it processes even {a} (no commas), second,
3220 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003221 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003222 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003223
3224/* Helper */
3225static int glob_needed(const char *s)
3226{
3227 while (*s) {
3228 if (*s == '\\') {
3229 if (!s[1])
3230 return 0;
3231 s += 2;
3232 continue;
3233 }
3234 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3235 return 1;
3236 s++;
3237 }
3238 return 0;
3239}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003240/* Return pointer to next closing brace or to comma */
3241static const char *next_brace_sub(const char *cp)
3242{
3243 unsigned depth = 0;
3244 cp++;
3245 while (*cp != '\0') {
3246 if (*cp == '\\') {
3247 if (*++cp == '\0')
3248 break;
3249 cp++;
3250 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003251 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003252 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003253 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003254 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003255 depth++;
3256 }
3257
3258 return *cp != '\0' ? cp : NULL;
3259}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003260/* Recursive brace globber. Note: may garble pattern[]. */
3261static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003262{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003263 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003264 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003265 const char *next;
3266 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003267 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003268 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003269
3270 debug_printf_glob("glob_brace('%s')\n", pattern);
3271
3272 begin = pattern;
3273 while (1) {
3274 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003275 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003276 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003277 /* Find the first sub-pattern and at the same time
3278 * find the rest after the closing brace */
3279 next = next_brace_sub(begin);
3280 if (next == NULL) {
3281 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003282 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003283 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003284 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003285 /* "{abc}" with no commas - illegal
3286 * brace expr, disregard and skip it */
3287 begin = next + 1;
3288 continue;
3289 }
3290 break;
3291 }
3292 if (*begin == '\\' && begin[1] != '\0')
3293 begin++;
3294 begin++;
3295 }
3296 debug_printf_glob("begin:%s\n", begin);
3297 debug_printf_glob("next:%s\n", next);
3298
3299 /* Now find the end of the whole brace expression */
3300 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003301 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003302 rest = next_brace_sub(rest);
3303 if (rest == NULL) {
3304 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003305 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003306 }
3307 debug_printf_glob("rest:%s\n", rest);
3308 }
3309 rest_len = strlen(++rest) + 1;
3310
3311 /* We are sure the brace expression is well-formed */
3312
3313 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003314 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003315
3316 /* We have a brace expression. BEGIN points to the opening {,
3317 * NEXT points past the terminator of the first element, and REST
3318 * points past the final }. We will accumulate result names from
3319 * recursive runs for each brace alternative in the buffer using
3320 * GLOB_APPEND. */
3321
3322 p = begin + 1;
3323 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003324 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003325 memcpy(
3326 mempcpy(
3327 mempcpy(new_pattern_buf,
3328 /* We know the prefix for all sub-patterns */
3329 pattern, begin - pattern),
3330 p, next - p),
3331 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003332
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003333 /* Note: glob_brace() may garble new_pattern_buf[].
3334 * That's why we re-copy prefix every time (1st memcpy above).
3335 */
3336 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003337 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003338 /* We saw the last entry */
3339 break;
3340 }
3341 p = next + 1;
3342 next = next_brace_sub(next);
3343 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003344 free(new_pattern_buf);
3345 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003346
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003347 simple_glob:
3348 {
3349 int gr;
3350 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003351
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003352 memset(&globdata, 0, sizeof(globdata));
3353 gr = glob(pattern, 0, NULL, &globdata);
3354 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3355 if (gr != 0) {
3356 if (gr == GLOB_NOMATCH) {
3357 globfree(&globdata);
3358 /* NB: garbles parameter */
3359 unbackslash(pattern);
3360 o_addstr_with_NUL(o, pattern);
3361 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3362 return o_save_ptr_helper(o, n);
3363 }
3364 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003365 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003366 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3367 * but we didn't specify it. Paranoia again. */
3368 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3369 }
3370 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3371 char **argv = globdata.gl_pathv;
3372 while (1) {
3373 o_addstr_with_NUL(o, *argv);
3374 n = o_save_ptr_helper(o, n);
3375 argv++;
3376 if (!*argv)
3377 break;
3378 }
3379 }
3380 globfree(&globdata);
3381 }
3382 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003383}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003384/* Performs globbing on last list[],
3385 * saving each result as a new list[].
3386 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003387static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003388{
3389 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003390
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003391 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003392 if (!o->data)
3393 return o_save_ptr_helper(o, n);
3394 pattern = o->data + o_get_last_ptr(o, n);
3395 debug_printf_glob("glob pattern '%s'\n", pattern);
3396 if (!glob_needed(pattern)) {
3397 /* unbackslash last string in o in place, fix length */
3398 o->length = unbackslash(pattern) - o->data;
3399 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3400 return o_save_ptr_helper(o, n);
3401 }
3402
3403 copy = xstrdup(pattern);
3404 /* "forget" pattern in o */
3405 o->length = pattern - o->data;
3406 n = glob_brace(copy, o, n);
3407 free(copy);
3408 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003409 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003410 return n;
3411}
3412
Denys Vlasenko238081f2010-10-03 14:26:26 +02003413#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003414
3415/* Helper */
3416static int glob_needed(const char *s)
3417{
3418 while (*s) {
3419 if (*s == '\\') {
3420 if (!s[1])
3421 return 0;
3422 s += 2;
3423 continue;
3424 }
3425 if (*s == '*' || *s == '[' || *s == '?')
3426 return 1;
3427 s++;
3428 }
3429 return 0;
3430}
3431/* Performs globbing on last list[],
3432 * saving each result as a new list[].
3433 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003434static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003435{
3436 glob_t globdata;
3437 int gr;
3438 char *pattern;
3439
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003440 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003441 if (!o->data)
3442 return o_save_ptr_helper(o, n);
3443 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003444 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003445 if (!glob_needed(pattern)) {
3446 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003447 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003448 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003449 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003450 return o_save_ptr_helper(o, n);
3451 }
3452
3453 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003454 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3455 * If we glob "*.\*" and don't find anything, we need
3456 * to fall back to using literal "*.*", but GLOB_NOCHECK
3457 * will return "*.\*"!
3458 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003459 gr = glob(pattern, 0, NULL, &globdata);
3460 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003461 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003462 if (gr == GLOB_NOMATCH) {
3463 globfree(&globdata);
3464 goto literal;
3465 }
3466 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003467 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003468 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3469 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003470 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003471 }
3472 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3473 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003474 /* "forget" pattern in o */
3475 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003476 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003477 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003478 n = o_save_ptr_helper(o, n);
3479 argv++;
3480 if (!*argv)
3481 break;
3482 }
3483 }
3484 globfree(&globdata);
3485 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003486 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003487 return n;
3488}
3489
Denys Vlasenko238081f2010-10-03 14:26:26 +02003490#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003491
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003492/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003493 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003494static int o_save_ptr(o_string *o, int n)
3495{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003496 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003497 /* If o->has_empty_slot, list[n] was already globbed
3498 * (if it was requested back then when it was filled)
3499 * so don't do that again! */
3500 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003501 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003502 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003503 return o_save_ptr_helper(o, n);
3504}
3505
3506/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003507static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003508{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003509 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003510 int string_start;
3511
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003512 if (DEBUG_EXPAND)
3513 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003514 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003515 list = (char**)o->data;
3516 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3517 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003518 while (n) {
3519 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003520 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003521 }
3522 return list;
3523}
3524
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003525static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003526
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003527/* Returns pi->next - next pipe in the list */
3528static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003529{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003530 struct pipe *next;
3531 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003532
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003533 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003534 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003535 struct command *command;
3536 struct redir_struct *r, *rnext;
3537
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003538 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003539 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003540 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003541 if (DEBUG_CLEAN) {
3542 int a;
3543 char **p;
3544 for (a = 0, p = command->argv; *p; a++, p++) {
3545 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3546 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003547 }
3548 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003549 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003550 }
3551 /* not "else if": on syntax error, we may have both! */
3552 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003553 debug_printf_clean(" begin group (cmd_type:%d)\n",
3554 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003555 free_pipe_list(command->group);
3556 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003557 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003558 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003559 /* else is crucial here.
3560 * If group != NULL, child_func is meaningless */
3561#if ENABLE_HUSH_FUNCTIONS
3562 else if (command->child_func) {
3563 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3564 command->child_func->parent_cmd = NULL;
3565 }
3566#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003567#if !BB_MMU
3568 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003569 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003570#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003571 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003572 debug_printf_clean(" redirect %d%s",
3573 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003574 /* guard against the case >$FOO, where foo is unset or blank */
3575 if (r->rd_filename) {
3576 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3577 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003578 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003579 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003580 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003581 rnext = r->next;
3582 free(r);
3583 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003584 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003585 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003586 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003587 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003588#if ENABLE_HUSH_JOB
3589 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003590 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003591#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003592
3593 next = pi->next;
3594 free(pi);
3595 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003596}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003597
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003598static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003599{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003600 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003601#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003602 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003603#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003604 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003605 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003606 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003607}
3608
3609
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003610/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003611
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003612#ifndef debug_print_tree
3613static void debug_print_tree(struct pipe *pi, int lvl)
3614{
3615 static const char *const PIPE[] = {
3616 [PIPE_SEQ] = "SEQ",
3617 [PIPE_AND] = "AND",
3618 [PIPE_OR ] = "OR" ,
3619 [PIPE_BG ] = "BG" ,
3620 };
3621 static const char *RES[] = {
3622 [RES_NONE ] = "NONE" ,
3623# if ENABLE_HUSH_IF
3624 [RES_IF ] = "IF" ,
3625 [RES_THEN ] = "THEN" ,
3626 [RES_ELIF ] = "ELIF" ,
3627 [RES_ELSE ] = "ELSE" ,
3628 [RES_FI ] = "FI" ,
3629# endif
3630# if ENABLE_HUSH_LOOPS
3631 [RES_FOR ] = "FOR" ,
3632 [RES_WHILE] = "WHILE",
3633 [RES_UNTIL] = "UNTIL",
3634 [RES_DO ] = "DO" ,
3635 [RES_DONE ] = "DONE" ,
3636# endif
3637# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3638 [RES_IN ] = "IN" ,
3639# endif
3640# if ENABLE_HUSH_CASE
3641 [RES_CASE ] = "CASE" ,
3642 [RES_CASE_IN ] = "CASE_IN" ,
3643 [RES_MATCH] = "MATCH",
3644 [RES_CASE_BODY] = "CASE_BODY",
3645 [RES_ESAC ] = "ESAC" ,
3646# endif
3647 [RES_XXXX ] = "XXXX" ,
3648 [RES_SNTX ] = "SNTX" ,
3649 };
3650 static const char *const CMDTYPE[] = {
3651 "{}",
3652 "()",
3653 "[noglob]",
3654# if ENABLE_HUSH_FUNCTIONS
3655 "func()",
3656# endif
3657 };
3658
3659 int pin, prn;
3660
3661 pin = 0;
3662 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003663 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3664 lvl*2, "",
3665 pin,
3666 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3667 RES[pi->res_word],
3668 pi->followup, PIPE[pi->followup]
3669 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003670 prn = 0;
3671 while (prn < pi->num_cmds) {
3672 struct command *command = &pi->cmds[prn];
3673 char **argv = command->argv;
3674
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003675 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003676 lvl*2, "", prn,
3677 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003678#if ENABLE_HUSH_LINENO_VAR
3679 fdprintf(2, " LINENO:%u", command->lineno);
3680#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003681 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003682 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003683 CMDTYPE[command->cmd_type],
3684 argv
3685# if !BB_MMU
3686 , " group_as_string:", command->group_as_string
3687# else
3688 , "", ""
3689# endif
3690 );
3691 debug_print_tree(command->group, lvl+1);
3692 prn++;
3693 continue;
3694 }
3695 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003696 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003697 argv++;
3698 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003699 if (command->redirects)
3700 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003701 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003702 prn++;
3703 }
3704 pi = pi->next;
3705 pin++;
3706 }
3707}
3708#endif /* debug_print_tree */
3709
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003710static struct pipe *new_pipe(void)
3711{
Eric Andersen25f27032001-04-26 23:22:31 +00003712 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003713 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003714 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003715 return pi;
3716}
3717
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003718/* Command (member of a pipe) is complete, or we start a new pipe
3719 * if ctx->command is NULL.
3720 * No errors possible here.
3721 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003722static int done_command(struct parse_context *ctx)
3723{
3724 /* The command is really already in the pipe structure, so
3725 * advance the pipe counter and make a new, null command. */
3726 struct pipe *pi = ctx->pipe;
3727 struct command *command = ctx->command;
3728
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003729#if 0 /* Instead we emit error message at run time */
3730 if (ctx->pending_redirect) {
3731 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003732 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003733 ctx->pending_redirect = NULL;
3734 }
3735#endif
3736
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003737 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003738 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003739 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003740 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003741 }
3742 pi->num_cmds++;
3743 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003744 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003745 } else {
3746 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3747 }
3748
3749 /* Only real trickiness here is that the uncommitted
3750 * command structure is not counted in pi->num_cmds. */
3751 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003752 ctx->command = command = &pi->cmds[pi->num_cmds];
3753 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003754 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003755#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003756 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003757 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003758#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003759 return pi->num_cmds; /* used only for 0/nonzero check */
3760}
3761
3762static void done_pipe(struct parse_context *ctx, pipe_style type)
3763{
3764 int not_null;
3765
3766 debug_printf_parse("done_pipe entered, followup %d\n", type);
3767 /* Close previous command */
3768 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003769#if HAS_KEYWORDS
3770 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3771 ctx->ctx_inverted = 0;
3772 ctx->pipe->res_word = ctx->ctx_res_w;
3773#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003774 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3775 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003776 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3777 * in a backgrounded subshell.
3778 */
3779 struct pipe *pi;
3780 struct command *command;
3781
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003782 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003783 pi = ctx->list_head;
3784 while (pi != ctx->pipe) {
3785 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3786 goto no_conv;
3787 pi = pi->next;
3788 }
3789
3790 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3791 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3792 pi = xzalloc(sizeof(*pi));
3793 pi->followup = PIPE_BG;
3794 pi->num_cmds = 1;
3795 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3796 command = &pi->cmds[0];
3797 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3798 command->cmd_type = CMD_NORMAL;
3799 command->group = ctx->list_head;
3800#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003801 command->group_as_string = xstrndup(
3802 ctx->as_string.data,
3803 ctx->as_string.length - 1 /* do not copy last char, "&" */
3804 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003805#endif
3806 /* Replace all pipes in ctx with one newly created */
3807 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003808 } else {
3809 no_conv:
3810 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003811 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003812
3813 /* Without this check, even just <enter> on command line generates
3814 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003815 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003816 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003817#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003818 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003819#endif
3820#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003821 || ctx->ctx_res_w == RES_DONE
3822 || ctx->ctx_res_w == RES_FOR
3823 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003824#endif
3825#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003826 || ctx->ctx_res_w == RES_ESAC
3827#endif
3828 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003829 struct pipe *new_p;
3830 debug_printf_parse("done_pipe: adding new pipe: "
3831 "not_null:%d ctx->ctx_res_w:%d\n",
3832 not_null, ctx->ctx_res_w);
3833 new_p = new_pipe();
3834 ctx->pipe->next = new_p;
3835 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003836 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003837 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003838 * This is used to control execution.
3839 * RES_FOR and RES_IN are NOT sticky (needed to support
3840 * cases where variable or value happens to match a keyword):
3841 */
3842#if ENABLE_HUSH_LOOPS
3843 if (ctx->ctx_res_w == RES_FOR
3844 || ctx->ctx_res_w == RES_IN)
3845 ctx->ctx_res_w = RES_NONE;
3846#endif
3847#if ENABLE_HUSH_CASE
3848 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003849 ctx->ctx_res_w = RES_CASE_BODY;
3850 if (ctx->ctx_res_w == RES_CASE)
3851 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003852#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003853 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003854 /* Create the memory for command, roughly:
3855 * ctx->pipe->cmds = new struct command;
3856 * ctx->command = &ctx->pipe->cmds[0];
3857 */
3858 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003859 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003860 }
3861 debug_printf_parse("done_pipe return\n");
3862}
3863
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003864static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003865{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003866 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003867 if (MAYBE_ASSIGNMENT != 0)
3868 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003869 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003870 /* Create the memory for command, roughly:
3871 * ctx->pipe->cmds = new struct command;
3872 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003873 */
3874 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003875}
3876
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003877/* If a reserved word is found and processed, parse context is modified
3878 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003879 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003880#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003881struct reserved_combo {
3882 char literal[6];
3883 unsigned char res;
3884 unsigned char assignment_flag;
3885 int flag;
3886};
3887enum {
3888 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003889# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003890 FLAG_IF = (1 << RES_IF ),
3891 FLAG_THEN = (1 << RES_THEN ),
3892 FLAG_ELIF = (1 << RES_ELIF ),
3893 FLAG_ELSE = (1 << RES_ELSE ),
3894 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003895# endif
3896# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003897 FLAG_FOR = (1 << RES_FOR ),
3898 FLAG_WHILE = (1 << RES_WHILE),
3899 FLAG_UNTIL = (1 << RES_UNTIL),
3900 FLAG_DO = (1 << RES_DO ),
3901 FLAG_DONE = (1 << RES_DONE ),
3902 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003903# endif
3904# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003905 FLAG_MATCH = (1 << RES_MATCH),
3906 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003907# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003908 FLAG_START = (1 << RES_XXXX ),
3909};
3910
3911static const struct reserved_combo* match_reserved_word(o_string *word)
3912{
Eric Andersen25f27032001-04-26 23:22:31 +00003913 /* Mostly a list of accepted follow-up reserved words.
3914 * FLAG_END means we are done with the sequence, and are ready
3915 * to turn the compound list into a command.
3916 * FLAG_START means the word must start a new compound list.
3917 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003918 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003919# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003920 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3921 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3922 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3923 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3924 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3925 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003926# endif
3927# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003928 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3929 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3930 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3931 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3932 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3933 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003934# endif
3935# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003936 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3937 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003938# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003939 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003940 const struct reserved_combo *r;
3941
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003942 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003943 if (strcmp(word->data, r->literal) == 0)
3944 return r;
3945 }
3946 return NULL;
3947}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003948/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003949 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003950static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003951{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003952# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003953 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003954 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003955 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003956# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003957 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003958
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003959 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003960 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003961 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003962 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003963 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003964
3965 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003966# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003967 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3968 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003969 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003970 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003971# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003972 if (r->flag == 0) { /* '!' */
3973 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003974 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003975 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003976 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003977 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003978 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003979 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003980 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003981 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003982
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003983 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003984 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003985 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003986 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003987 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003988 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003989 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003990 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003991 } else {
3992 /* "{...} fi" is ok. "{...} if" is not
3993 * Example:
3994 * if { echo foo; } then { echo bar; } fi */
3995 if (ctx->command->group)
3996 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003997 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003998
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003999 ctx->ctx_res_w = r->res;
4000 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004001 ctx->is_assignment = r->assignment_flag;
4002 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004003
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004004 if (ctx->old_flag & FLAG_END) {
4005 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004006
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004007 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004008 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004009 old = ctx->stack;
4010 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004011 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004012# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004013 /* At this point, the compound command's string is in
4014 * ctx->as_string... except for the leading keyword!
4015 * Consider this example: "echo a | if true; then echo a; fi"
4016 * ctx->as_string will contain "true; then echo a; fi",
4017 * with "if " remaining in old->as_string!
4018 */
4019 {
4020 char *str;
4021 int len = old->as_string.length;
4022 /* Concatenate halves */
4023 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004024 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004025 /* Find where leading keyword starts in first half */
4026 str = old->as_string.data + len;
4027 if (str > old->as_string.data)
4028 str--; /* skip whitespace after keyword */
4029 while (str > old->as_string.data && isalpha(str[-1]))
4030 str--;
4031 /* Ugh, we're done with this horrid hack */
4032 old->command->group_as_string = xstrdup(str);
4033 debug_printf_parse("pop, remembering as:'%s'\n",
4034 old->command->group_as_string);
4035 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004036# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004037 *ctx = *old; /* physical copy */
4038 free(old);
4039 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004040 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004041}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004042#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004043
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004044/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004045 * Normal return is 0. Syntax errors return 1.
4046 * Note: on return, word is reset, but not o_free'd!
4047 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004048static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004049{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004050 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004051
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004052 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4053 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004054 debug_printf_parse("done_word return 0: true null, ignored\n");
4055 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004056 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004057
Eric Andersen25f27032001-04-26 23:22:31 +00004058 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004059 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4060 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004061 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004062 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004063 * If the redirection operator is "<<" or "<<-", the word
4064 * that follows the redirection operator shall be
4065 * subjected to quote removal; it is unspecified whether
4066 * any of the other expansions occur. For the other
4067 * redirection operators, the word that follows the
4068 * redirection operator shall be subjected to tilde
4069 * expansion, parameter expansion, command substitution,
4070 * arithmetic expansion, and quote removal.
4071 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004072 * on the word by a non-interactive shell; an interactive
4073 * shell may perform it, but shall do so only when
4074 * the expansion would result in one word."
4075 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004076//bash does not do parameter/command substitution or arithmetic expansion
4077//for _heredoc_ redirection word: these constructs look for exact eof marker
4078// as written:
4079// <<EOF$t
4080// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004081// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4082
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004083 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004084 /* Cater for >\file case:
4085 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4086 * Same with heredocs:
4087 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4088 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004089 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4090 unbackslash(ctx->pending_redirect->rd_filename);
4091 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004092 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004093 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4094 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004095 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004096 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004097 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004098 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004099#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004100# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004101 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004102 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004103 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004104 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004105 /* ctx->ctx_res_w = RES_MATCH; */
4106 ctx->ctx_dsemicolon = 0;
4107 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004108# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004109 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004110# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004111 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4112 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004113# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004114# if ENABLE_HUSH_CASE
4115 && ctx->ctx_res_w != RES_CASE
4116# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004117 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004118 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004119 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004120 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004121 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004122# if ENABLE_HUSH_LINENO_VAR
4123/* Case:
4124 * "while ...; do
4125 * cmd ..."
4126 * If we don't close the pipe _now_, immediately after "do", lineno logic
4127 * sees "cmd" as starting at "do" - i.e., at the previous line.
4128 */
4129 if (0
4130 IF_HUSH_IF(|| reserved->res == RES_THEN)
4131 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4132 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4133 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4134 ) {
4135 done_pipe(ctx, PIPE_SEQ);
4136 }
4137# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004138 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004139 debug_printf_parse("done_word return %d\n",
4140 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004141 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004142 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004143# if defined(CMD_SINGLEWORD_NOGLOB)
4144 if (0
4145# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004146 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004147# endif
4148 /* In bash, local/export/readonly are special, args
4149 * are assignments and therefore expansion of them
4150 * should be "one-word" expansion:
4151 * $ export i=`echo 'a b'` # one arg: "i=a b"
4152 * compare with:
4153 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4154 * ls: cannot access i=a: No such file or directory
4155 * ls: cannot access b: No such file or directory
4156 * Note: bash 3.2.33(1) does this only if export word
4157 * itself is not quoted:
4158 * $ export i=`echo 'aaa bbb'`; echo "$i"
4159 * aaa bbb
4160 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4161 * aaa
4162 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004163 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4164 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4165 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004166 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004167 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4168 }
4169 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004170# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004171 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004172#endif /* HAS_KEYWORDS */
4173
Denis Vlasenkobb929512009-04-16 10:59:40 +00004174 if (command->group) {
4175 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004176 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004177 debug_printf_parse("done_word return 1: syntax error, "
4178 "groups and arglists don't mix\n");
4179 return 1;
4180 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004181
4182 /* If this word wasn't an assignment, next ones definitely
4183 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004184 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4185 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004186 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004187 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004188 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004189 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004190 command->assignment_cnt++;
4191 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4192 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004193 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4194 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004195 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004196 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4197 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004198 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004199 }
Eric Andersen25f27032001-04-26 23:22:31 +00004200
Denis Vlasenko06810332007-05-21 23:30:54 +00004201#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004202 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004203 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004204 || !is_well_formed_var_name(command->argv[0], '\0')
4205 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004206 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004207 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004208 return 1;
4209 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004210 /* Force FOR to have just one word (variable name) */
4211 /* NB: basically, this makes hush see "for v in ..."
4212 * syntax as if it is "for v; in ...". FOR and IN become
4213 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004214 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004215 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004216#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004217#if ENABLE_HUSH_CASE
4218 /* Force CASE to have just one word */
4219 if (ctx->ctx_res_w == RES_CASE) {
4220 done_pipe(ctx, PIPE_SEQ);
4221 }
4222#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004223
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004224 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004225
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004226 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004227 return 0;
4228}
4229
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004230
4231/* Peek ahead in the input to find out if we have a "&n" construct,
4232 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004233 * Return:
4234 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4235 * REDIRFD_SYNTAX_ERR if syntax error,
4236 * REDIRFD_TO_FILE if no & was seen,
4237 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004238 */
4239#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004240#define parse_redir_right_fd(as_string, input) \
4241 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004242#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004243static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004244{
4245 int ch, d, ok;
4246
4247 ch = i_peek(input);
4248 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004249 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250
4251 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004252 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004253 ch = i_peek(input);
4254 if (ch == '-') {
4255 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004256 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004257 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004258 }
4259 d = 0;
4260 ok = 0;
4261 while (ch != EOF && isdigit(ch)) {
4262 d = d*10 + (ch-'0');
4263 ok = 1;
4264 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266 ch = i_peek(input);
4267 }
4268 if (ok) return d;
4269
4270//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4271
4272 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004273 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004274}
4275
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004276/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004277 */
4278static int parse_redirect(struct parse_context *ctx,
4279 int fd,
4280 redir_type style,
4281 struct in_str *input)
4282{
4283 struct command *command = ctx->command;
4284 struct redir_struct *redir;
4285 struct redir_struct **redirp;
4286 int dup_num;
4287
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004288 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004290 /* Check for a '>&1' type redirect */
4291 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4292 if (dup_num == REDIRFD_SYNTAX_ERR)
4293 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004294 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004295 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004296 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004297 if (dup_num) { /* <<-... */
4298 ch = i_getch(input);
4299 nommu_addchr(&ctx->as_string, ch);
4300 ch = i_peek(input);
4301 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004302 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004304 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004305 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004306 if (ch == '|') {
4307 /* >|FILE redirect ("clobbering" >).
4308 * Since we do not support "set -o noclobber" yet,
4309 * >| and > are the same for now. Just eat |.
4310 */
4311 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004312 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004313 }
4314 }
4315
4316 /* Create a new redir_struct and append it to the linked list */
4317 redirp = &command->redirects;
4318 while ((redir = *redirp) != NULL) {
4319 redirp = &(redir->next);
4320 }
4321 *redirp = redir = xzalloc(sizeof(*redir));
4322 /* redir->next = NULL; */
4323 /* redir->rd_filename = NULL; */
4324 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004325 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004327 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4328 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004330 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004331 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004332 /* Erik had a check here that the file descriptor in question
4333 * is legit; I postpone that to "run time"
4334 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004335 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4336 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004337 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004338#if 0 /* Instead we emit error message at run time */
4339 if (ctx->pending_redirect) {
4340 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004341 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004342 }
4343#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004344 /* Set ctx->pending_redirect, so we know what to do at the
4345 * end of the next parsed word. */
4346 ctx->pending_redirect = redir;
4347 }
4348 return 0;
4349}
4350
Eric Andersen25f27032001-04-26 23:22:31 +00004351/* If a redirect is immediately preceded by a number, that number is
4352 * supposed to tell which file descriptor to redirect. This routine
4353 * looks for such preceding numbers. In an ideal world this routine
4354 * needs to handle all the following classes of redirects...
4355 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4356 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4357 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4358 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004359 *
4360 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4361 * "2.7 Redirection
4362 * ... If n is quoted, the number shall not be recognized as part of
4363 * the redirection expression. For example:
4364 * echo \2>a
4365 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004366 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004367 *
4368 * A -1 return means no valid number was found,
4369 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004370 */
4371static int redirect_opt_num(o_string *o)
4372{
4373 int num;
4374
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004375 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004376 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004377 num = bb_strtou(o->data, NULL, 10);
4378 if (errno || num < 0)
4379 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004380 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004381 return num;
4382}
4383
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004384#if BB_MMU
4385#define fetch_till_str(as_string, input, word, skip_tabs) \
4386 fetch_till_str(input, word, skip_tabs)
4387#endif
4388static char *fetch_till_str(o_string *as_string,
4389 struct in_str *input,
4390 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004391 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004392{
4393 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004394 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004395 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004396 int ch;
4397
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004398 /* Starting with "" is necessary for this case:
4399 * cat <<EOF
4400 *
4401 * xxx
4402 * EOF
4403 */
4404 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4405
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004406 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004407
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004408 while (1) {
4409 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004410 if (ch != EOF)
4411 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004412 if (ch == '\n' || ch == EOF) {
4413 check_heredoc_end:
4414 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004415 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004416 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4417 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004418 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004419 return heredoc.data;
4420 }
4421 if (ch == '\n') {
4422 /* This is a new line.
4423 * Remember position and backslash-escaping status.
4424 */
4425 o_addchr(&heredoc, ch);
4426 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004427 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004428 past_EOL = heredoc.length;
4429 /* Get 1st char of next line, possibly skipping leading tabs */
4430 do {
4431 ch = i_getch(input);
4432 if (ch != EOF)
4433 nommu_addchr(as_string, ch);
4434 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4435 /* If this immediately ended the line,
4436 * go back to end-of-line checks.
4437 */
4438 if (ch == '\n')
4439 goto check_heredoc_end;
4440 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004441 } else {
4442 /* Backslash-line continuation in an unquoted
4443 * heredoc. This does not need special handling
4444 * for heredoc body (unquoted heredocs are
4445 * expanded on "execution" and that would take
4446 * care of this case too), but not the case
4447 * of line continuation *in terminator*:
4448 * cat <<EOF
4449 * Ok1
4450 * EO\
4451 * F
4452 */
4453 heredoc.data[--heredoc.length] = '\0';
4454 prev = 0; /* not '\' */
4455 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004456 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004457 }
4458 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004459 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004460 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004461 }
4462 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004463 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004464 if (prev == '\\' && ch == '\\')
4465 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004466 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004467 else
4468 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004469 }
4470}
4471
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004472/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4473 * and load them all. There should be exactly heredoc_cnt of them.
4474 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004475#if BB_MMU
4476#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4477 fetch_heredocs(pi, heredoc_cnt, input)
4478#endif
4479static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004480{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004481 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004482 int i;
4483 struct command *cmd = pi->cmds;
4484
Denys Vlasenko3675c372018-07-23 16:31:21 +02004485 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004486 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004487 cmd->argv ? cmd->argv[0] : "NONE"
4488 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004489 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004490 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004491
Denys Vlasenko3675c372018-07-23 16:31:21 +02004492 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004493 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004494 while (redir) {
4495 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004496 char *p;
4497
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004498 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004499 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004500 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004501 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004502 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004503 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004504 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004505 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004506 free(redir->rd_filename);
4507 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004508 heredoc_cnt--;
4509 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004510 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004511 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004512 if (cmd->group) {
4513 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4514 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4515 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4516 if (heredoc_cnt < 0)
4517 return heredoc_cnt; /* error */
4518 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004519 cmd++;
4520 }
4521 pi = pi->next;
4522 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004523 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004524}
4525
4526
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004527static int run_list(struct pipe *pi);
4528#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004529#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4530 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004531#endif
4532static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004533 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004534 struct in_str *input,
4535 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004536
Denys Vlasenko474cb202018-07-24 13:03:03 +02004537/* Returns number of heredocs not yet consumed,
4538 * or -1 on error.
4539 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004540static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004541 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004542{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004543 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004544 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004545 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004546#if BB_MMU
4547# define as_string NULL
4548#else
4549 char *as_string = NULL;
4550#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004551 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004552 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004553 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004554 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004555
4556 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004557#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004558 if (ch == '(' && !ctx->word.has_quoted_part) {
4559 if (ctx->word.length)
4560 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004561 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004562 if (!command->argv)
4563 goto skip; /* (... */
4564 if (command->argv[1]) { /* word word ... (... */
4565 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004566 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004567 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004568 /* it is "word(..." or "word (..." */
4569 do
4570 ch = i_getch(input);
4571 while (ch == ' ' || ch == '\t');
4572 if (ch != ')') {
4573 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004574 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004575 }
4576 nommu_addchr(&ctx->as_string, ch);
4577 do
4578 ch = i_getch(input);
4579 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004580 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004581 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004582 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004583 }
4584 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004585 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004586 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004587 }
4588#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004589
4590#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004591 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004592 || ctx->word.length /* word{... */
4593 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004594 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004595 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004596 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004597 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004598 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004599 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004600#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004601
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004602 IF_HUSH_FUNCTIONS(skip:)
4603
Denis Vlasenko240c2552009-04-03 03:45:05 +00004604 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004605 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004606 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004607 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4608 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004609 } else {
4610 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004611 ch = i_peek(input);
4612 if (ch != ' ' && ch != '\t' && ch != '\n'
4613 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4614 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004615 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004616 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004617 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004618 if (ch != '(') {
4619 ch = i_getch(input);
4620 nommu_addchr(&ctx->as_string, ch);
4621 }
Eric Andersen25f27032001-04-26 23:22:31 +00004622 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004623
Denys Vlasenko474cb202018-07-24 13:03:03 +02004624 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4625 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4626 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004627#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004628 if (as_string)
4629 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004630#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004631
4632 /* empty ()/{} or parse error? */
4633 if (!pipe_list || pipe_list == ERR_PTR) {
4634 /* parse_stream already emitted error msg */
4635 if (!BB_MMU)
4636 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004637 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004638 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004639 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004640 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004641#if !BB_MMU
4642 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4643 command->group_as_string = as_string;
4644 debug_printf_parse("end of group, remembering as:'%s'\n",
4645 command->group_as_string);
4646#endif
4647
4648#if ENABLE_HUSH_FUNCTIONS
4649 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4650 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4651 struct command *cmd2;
4652
4653 cmd2 = xzalloc(sizeof(*cmd2));
4654 cmd2->cmd_type = CMD_SUBSHELL;
4655 cmd2->group = pipe_list;
4656# if !BB_MMU
4657//UNTESTED!
4658 cmd2->group_as_string = command->group_as_string;
4659 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4660# endif
4661
4662 pipe_list = new_pipe();
4663 pipe_list->cmds = cmd2;
4664 pipe_list->num_cmds = 1;
4665 }
4666#endif
4667
4668 command->group = pipe_list;
4669
Denys Vlasenko474cb202018-07-24 13:03:03 +02004670 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4671 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004672 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004673#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004674}
4675
Denys Vlasenko0b883582016-12-23 16:49:07 +01004676#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004677/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004678/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004679static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004680{
4681 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004682 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004683 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004684 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004685 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004686 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004687 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004688 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004689 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004690 }
4691}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004692static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4693{
4694 while (1) {
4695 int ch = i_getch(input);
4696 if (ch == EOF) {
4697 syntax_error_unterm_ch('\'');
4698 return 0;
4699 }
4700 if (ch == '\'')
4701 return 1;
4702 o_addqchr(dest, ch);
4703 }
4704}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004705/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004706static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004707static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004708{
4709 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004710 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004711 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004712 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004713 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004714 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004715 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004716 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004717 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004718 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004719 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004720 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004721 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004722 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004723 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4724 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004725 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004726 continue;
4727 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004728 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004729 }
4730}
4731/* Process `cmd` - copy contents until "`" is seen. Complicated by
4732 * \` quoting.
4733 * "Within the backquoted style of command substitution, backslash
4734 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4735 * The search for the matching backquote shall be satisfied by the first
4736 * backquote found without a preceding backslash; during this search,
4737 * if a non-escaped backquote is encountered within a shell comment,
4738 * a here-document, an embedded command substitution of the $(command)
4739 * form, or a quoted string, undefined results occur. A single-quoted
4740 * or double-quoted string that begins, but does not end, within the
4741 * "`...`" sequence produces undefined results."
4742 * Example Output
4743 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4744 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004745static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004746{
4747 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004748 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004749 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004750 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004751 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004752 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4753 ch = i_getch(input);
4754 if (ch != '`'
4755 && ch != '$'
4756 && ch != '\\'
4757 && (!in_dquote || ch != '"')
4758 ) {
4759 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004760 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004761 }
4762 if (ch == EOF) {
4763 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004764 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004765 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004766 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004767 }
4768}
4769/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4770 * quoting and nested ()s.
4771 * "With the $(command) style of command substitution, all characters
4772 * following the open parenthesis to the matching closing parenthesis
4773 * constitute the command. Any valid shell script can be used for command,
4774 * except a script consisting solely of redirections which produces
4775 * unspecified results."
4776 * Example Output
4777 * echo $(echo '(TEST)' BEST) (TEST) BEST
4778 * echo $(echo 'TEST)' BEST) TEST) BEST
4779 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004780 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004781 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004782 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004783 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4784 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004785 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004786#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004787static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004788{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004789 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004790 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004791# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004792 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004793# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004794 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4795
Denys Vlasenko817a2022018-06-26 15:35:17 +02004796#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004797 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004798#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004799 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4800
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004801 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004802 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004803 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004804 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004805 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004806 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004807 if (ch == end_ch
4808# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004809 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004810# endif
4811 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004812 if (!dbl)
4813 break;
4814 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004815 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004816 i_getch(input); /* eat second ')' */
4817 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004818 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004819 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004820 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004821 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004822 if (ch == '(' || ch == '{') {
4823 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004824 if (!add_till_closing_bracket(dest, input, ch))
4825 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004826 o_addchr(dest, ch);
4827 continue;
4828 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004829 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004830 if (!add_till_single_quote(dest, input))
4831 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004832 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004833 continue;
4834 }
4835 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004836 if (!add_till_double_quote(dest, input))
4837 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004838 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004839 continue;
4840 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004841 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004842 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4843 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004844 o_addchr(dest, ch);
4845 continue;
4846 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004847 if (ch == '\\') {
4848 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004849 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004850 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004851 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004852 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004853 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004854#if 0
4855 if (ch == '\n') {
4856 /* "backslash+newline", ignore both */
4857 o_delchr(dest); /* undo insertion of '\' */
4858 continue;
4859 }
4860#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004861 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004862 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004863 continue;
4864 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004865 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004866 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004867 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004868}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004869#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004870
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004871/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004872#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004873#define parse_dollar(as_string, dest, input, quote_mask) \
4874 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004875#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004876#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004877static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004878 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004879 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004880{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004881 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004882
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004883 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004884 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004885 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004886 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004887 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004888 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004889 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004890 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004891 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004892 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004893 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004894 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004895 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004896 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004897 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004898 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004899 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004900 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004901 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004902 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004903 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004904 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004905 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004906 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004907 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004908 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004909 o_addchr(dest, ch | quote_mask);
4910 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004911 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004912 case '$': /* pid */
4913 case '!': /* last bg pid */
4914 case '?': /* last exit code */
4915 case '#': /* number of args */
4916 case '*': /* args */
4917 case '@': /* args */
4918 goto make_one_char_var;
4919 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004920 char len_single_ch;
4921
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004922 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4923
Denys Vlasenko74369502010-05-21 19:52:01 +02004924 ch = i_getch(input); /* eat '{' */
4925 nommu_addchr(as_string, ch);
4926
Denys Vlasenko46e64982016-09-29 19:50:55 +02004927 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004928 /* It should be ${?}, or ${#var},
4929 * or even ${?+subst} - operator acting on a special variable,
4930 * or the beginning of variable name.
4931 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004932 if (ch == EOF
4933 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4934 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004935 bad_dollar_syntax:
4936 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004937 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4938 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004939 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004940 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004941 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004942 ch |= quote_mask;
4943
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004944 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004945 * However, this regresses some of our testsuite cases
4946 * which check invalid constructs like ${%}.
4947 * Oh well... let's check that the var name part is fine... */
4948
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004949 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004950 unsigned pos;
4951
Denys Vlasenko74369502010-05-21 19:52:01 +02004952 o_addchr(dest, ch);
4953 debug_printf_parse(": '%c'\n", ch);
4954
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004955 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004956 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004957 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004958 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004959
Denys Vlasenko74369502010-05-21 19:52:01 +02004960 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004961 unsigned end_ch;
4962 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004963 /* handle parameter expansions
4964 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4965 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004966 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4967 if (len_single_ch != '#'
4968 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4969 || i_peek(input) != '}'
4970 ) {
4971 goto bad_dollar_syntax;
4972 }
4973 /* else: it's "length of C" ${#C} op,
4974 * where C is a single char
4975 * special var name, e.g. ${#!}.
4976 */
4977 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004978 /* Eat everything until closing '}' (or ':') */
4979 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004980 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004981 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004982 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004983 ) {
4984 /* It's ${var:N[:M]} thing */
4985 end_ch = '}' * 0x100 + ':';
4986 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004987 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004988 && ch == '/'
4989 ) {
4990 /* It's ${var/[/]pattern[/repl]} thing */
4991 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4992 i_getch(input);
4993 nommu_addchr(as_string, '/');
4994 ch = '\\';
4995 }
4996 end_ch = '}' * 0x100 + '/';
4997 }
4998 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02004999 /* The pattern can't be empty.
5000 * IOW: if the first char after "${v//" is a slash,
5001 * it does not terminate the pattern - it's the first char of the pattern:
5002 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5003 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5004 */
5005 if (i_peek(input) == '/') {
5006 o_addchr(dest, i_getch(input));
5007 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005008 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005009 if (!BB_MMU)
5010 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005011#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005012 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005013 if (last_ch == 0) /* error? */
5014 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005015#else
5016#error Simple code to only allow ${var} is not implemented
5017#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005018 if (as_string) {
5019 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005020 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005021 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005022
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005023 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5024 && (end_ch & 0xff00)
5025 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005026 /* close the first block: */
5027 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005028 /* while parsing N from ${var:N[:M]}
5029 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005030 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005031 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005032 end_ch = '}';
5033 goto again;
5034 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005035 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005036 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005037 /* it's ${var:N} - emulate :999999999 */
5038 o_addstr(dest, "999999999");
5039 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005040 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005041 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005042 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005043 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005044 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005045 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5046 break;
5047 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005048#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005049 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005050 unsigned pos;
5051
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005052 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005053 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005054# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005055 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005056 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005057 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005058 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5059 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005060 if (!BB_MMU)
5061 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005062 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5063 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005064 if (as_string) {
5065 o_addstr(as_string, dest->data + pos);
5066 o_addchr(as_string, ')');
5067 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005068 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005069 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005070 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005071 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005072# endif
5073# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005074 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5075 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005076 if (!BB_MMU)
5077 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005078 if (!add_till_closing_bracket(dest, input, ')'))
5079 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005080 if (as_string) {
5081 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005082 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005083 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005084 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005085# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005086 break;
5087 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005088#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005089 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005090 goto make_var;
5091#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005092 /* TODO: $_ and $-: */
5093 /* $_ Shell or shell script name; or last argument of last command
5094 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5095 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005096 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005097 ch = i_getch(input);
5098 nommu_addchr(as_string, ch);
5099 ch = i_peek_and_eat_bkslash_nl(input);
5100 if (isalnum(ch)) { /* it's $_name or $_123 */
5101 ch = '_';
5102 goto make_var1;
5103 }
5104 /* else: it's $_ */
5105#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005106 default:
5107 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005108 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005109 debug_printf_parse("parse_dollar return 1 (ok)\n");
5110 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005111#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005112}
5113
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005114#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005115#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005116 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005117#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005118#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005119static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005120 o_string *dest,
5121 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005122 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005123{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005124 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005125 int next;
5126
5127 again:
5128 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005129 if (ch != EOF)
5130 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005131 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005132 debug_printf_parse("encode_string return 1 (ok)\n");
5133 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005134 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005135 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005136 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005137 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005138 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005139 }
5140 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005141 if (ch != '\n') {
5142 next = i_peek(input);
5143 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005144 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005145 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005146 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005147 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005148 /* Testcase: in interactive shell a file with
5149 * echo "unterminated string\<eof>
5150 * is sourced.
5151 */
5152 syntax_error_unterm_ch('"');
5153 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005154 }
5155 /* bash:
5156 * "The backslash retains its special meaning [in "..."]
5157 * only when followed by one of the following characters:
5158 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005159 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005160 * NB: in (unquoted) heredoc, above does not apply to ",
5161 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005162 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005163 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005164 ch = i_getch(input); /* eat next */
5165 if (ch == '\n')
5166 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005167 } /* else: ch remains == '\\', and we double it below: */
5168 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005169 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005170 goto again;
5171 }
5172 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005173 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5174 debug_printf_parse("encode_string return 0: "
5175 "parse_dollar returned 0 (error)\n");
5176 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005177 }
5178 goto again;
5179 }
5180#if ENABLE_HUSH_TICK
5181 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005182 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005183 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5184 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005185 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5186 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005187 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5188 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005189 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005190 }
5191#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005192 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005193 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005194#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005195}
5196
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005197/*
5198 * Scan input until EOF or end_trigger char.
5199 * Return a list of pipes to execute, or NULL on EOF
5200 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005201 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005202 * reset parsing machinery and start parsing anew,
5203 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005204 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005205static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005206 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005207 struct in_str *input,
5208 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005209{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005210 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005211 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005212
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005213 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005214 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005215 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005216 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005217 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005218 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005219
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005220 initialize_context(&ctx);
5221
5222 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5223 * Preventing this:
5224 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005225 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005226
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005227 /* We used to separate words on $IFS here. This was wrong.
5228 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005229 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005230 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005231
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005232 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005233 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005234 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005235 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005236 int ch;
5237 int next;
5238 int redir_fd;
5239 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005240
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005241 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005242 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005243 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005244 if (ch == EOF) {
5245 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005246
5247 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005248 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005249 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005250 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005251 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005252 syntax_error_unterm_ch('(');
5253 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005254 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005255 if (end_trigger == '}') {
5256 syntax_error_unterm_ch('{');
5257 goto parse_error;
5258 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005259
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005260 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005261 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005262 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005263 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005264 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005265 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005266 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005267 /* (this makes bare "&" cmd a no-op.
5268 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005269 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005270 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005271 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005272 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005273 pi = NULL;
5274 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005275#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005276 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005277 if (pstring)
5278 *pstring = ctx.as_string.data;
5279 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005280 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005281#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005282 // heredoc_cnt must be 0 here anyway
5283 //if (heredoc_cnt_ptr)
5284 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005285 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005286 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005287 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005288 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005289 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005290
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005291 /* Handle "'" and "\" first, as they won't play nice with
5292 * i_peek_and_eat_bkslash_nl() anyway:
5293 * echo z\\
5294 * and
5295 * echo '\
5296 * '
5297 * would break.
5298 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005299 if (ch == '\\') {
5300 ch = i_getch(input);
5301 if (ch == '\n')
5302 continue; /* drop \<newline>, get next char */
5303 nommu_addchr(&ctx.as_string, '\\');
5304 o_addchr(&ctx.word, '\\');
5305 if (ch == EOF) {
5306 /* Testcase: eval 'echo Ok\' */
5307 /* bash-4.3.43 was removing backslash,
5308 * but 4.4.19 retains it, most other shells too
5309 */
5310 continue; /* get next char */
5311 }
5312 /* Example: echo Hello \2>file
5313 * we need to know that word 2 is quoted
5314 */
5315 ctx.word.has_quoted_part = 1;
5316 nommu_addchr(&ctx.as_string, ch);
5317 o_addchr(&ctx.word, ch);
5318 continue; /* get next char */
5319 }
5320 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005321 if (ch == '\'') {
5322 ctx.word.has_quoted_part = 1;
5323 next = i_getch(input);
5324 if (next == '\'' && !ctx.pending_redirect)
5325 goto insert_empty_quoted_str_marker;
5326
5327 ch = next;
5328 while (1) {
5329 if (ch == EOF) {
5330 syntax_error_unterm_ch('\'');
5331 goto parse_error;
5332 }
5333 nommu_addchr(&ctx.as_string, ch);
5334 if (ch == '\'')
5335 break;
5336 if (ch == SPECIAL_VAR_SYMBOL) {
5337 /* Convert raw ^C to corresponding special variable reference */
5338 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5339 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5340 }
5341 o_addqchr(&ctx.word, ch);
5342 ch = i_getch(input);
5343 }
5344 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005345 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005346
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005347 next = '\0';
5348 if (ch != '\n')
5349 next = i_peek_and_eat_bkslash_nl(input);
5350
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005351 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005352 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005353 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005354 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005355 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005356 || ctx.word.length /* word{... - non-special */
5357 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005358 || (next != ';' /* }; - special */
5359 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005360 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005361 && next != '&' /* }& and }&& ... - special */
5362 && next != '|' /* }|| ... - special */
5363 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005364 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005365 ) {
5366 /* They are not special, skip "{}" */
5367 is_special += 2;
5368 }
5369 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005370 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005371
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005372 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005373 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005374 o_addQchr(&ctx.word, ch);
5375 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5376 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005377 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005378 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005379 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005380 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5381 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005382 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005383 continue;
5384 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005385
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005386 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005387#if ENABLE_HUSH_LINENO_VAR
5388/* Case:
5389 * "while ...; do<whitespace><newline>
5390 * cmd ..."
5391 * would think that "cmd" starts in <whitespace> -
5392 * i.e., at the previous line.
5393 * We need to skip all whitespace before newlines.
5394 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005395 while (ch != '\n') {
5396 next = i_peek(input);
5397 if (next != ' ' && next != '\t' && next != '\n')
5398 break; /* next char is not ws */
5399 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005400 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005401 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005402#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005403 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005404 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005405 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005406 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005407 /* Is this a case when newline is simply ignored?
5408 * Some examples:
5409 * "cmd | <newline> cmd ..."
5410 * "case ... in <newline> word) ..."
5411 */
5412 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005413 && ctx.word.length == 0
5414 && !ctx.word.has_quoted_part
5415 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005416 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005417 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005418 * Without check #1, interactive shell
5419 * ignores even bare <newline>,
5420 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005421 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005422 * ps2> _ <=== wrong, should be ps1
5423 * Without check #2, "cmd & <newline>"
5424 * is similarly mistreated.
5425 * (BTW, this makes "cmd & cmd"
5426 * and "cmd && cmd" non-orthogonal.
5427 * Really, ask yourself, why
5428 * "cmd && <newline>" doesn't start
5429 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005430 * The only reason is that it might be
5431 * a "cmd1 && <nl> cmd2 &" construct,
5432 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005433 */
5434 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005435 if (pi->num_cmds != 0 /* check #1 */
5436 && pi->followup != PIPE_BG /* check #2 */
5437 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005438 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005439 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005440 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005441 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005442 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005443 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005444 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005445 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5446 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005447 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005448 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005449 ctx.is_assignment = MAYBE_ASSIGNMENT;
5450 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005451 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005452 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005453 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005454 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005455 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005456
5457 /* "cmd}" or "cmd }..." without semicolon or &:
5458 * } is an ordinary char in this case, even inside { cmd; }
5459 * Pathological example: { ""}; } should exec "}" cmd
5460 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005461 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005462 if (ctx.word.length != 0 /* word} */
5463 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005464 ) {
5465 goto ordinary_char;
5466 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005467 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5468 /* Generally, there should be semicolon: "cmd; }"
5469 * However, bash allows to omit it if "cmd" is
5470 * a group. Examples:
5471 * { { echo 1; } }
5472 * {(echo 1)}
5473 * { echo 0 >&2 | { echo 1; } }
5474 * { while false; do :; done }
5475 * { case a in b) ;; esac }
5476 */
5477 if (ctx.command->group)
5478 goto term_group;
5479 goto ordinary_char;
5480 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005481 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005482 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005483 goto skip_end_trigger;
5484 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005485 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005486 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005487 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005488 && (ch != ';' || heredoc_cnt == 0)
5489#if ENABLE_HUSH_CASE
5490 && (ch != ')'
5491 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005492 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005493 )
5494#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005495 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005496 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005497 goto parse_error;
5498 }
5499 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005500 ctx.is_assignment = MAYBE_ASSIGNMENT;
5501 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005502 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005503 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005504 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005505 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005506 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005507#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005508 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005509 if (pstring)
5510 *pstring = ctx.as_string.data;
5511 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005512 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005513#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005514 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5515 /* Example: bare "{ }", "()" */
5516 G.last_exitcode = 2; /* bash compat */
5517 syntax_error_unexpected_ch(ch);
5518 goto parse_error2;
5519 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005520 if (heredoc_cnt_ptr)
5521 *heredoc_cnt_ptr = heredoc_cnt;
5522 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005523 debug_printf_parse("parse_stream return %p: "
5524 "end_trigger char found\n",
5525 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005526 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005527 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005528 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005529 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005530
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005531 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005532 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005533
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005534 /* Catch <, > before deciding whether this word is
5535 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5536 switch (ch) {
5537 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005538 redir_fd = redirect_opt_num(&ctx.word);
5539 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005540 goto parse_error;
5541 }
5542 redir_style = REDIRECT_OVERWRITE;
5543 if (next == '>') {
5544 redir_style = REDIRECT_APPEND;
5545 ch = i_getch(input);
5546 nommu_addchr(&ctx.as_string, ch);
5547 }
5548#if 0
5549 else if (next == '(') {
5550 syntax_error(">(process) not supported");
5551 goto parse_error;
5552 }
5553#endif
5554 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5555 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005556 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005557 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005558 redir_fd = redirect_opt_num(&ctx.word);
5559 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005560 goto parse_error;
5561 }
5562 redir_style = REDIRECT_INPUT;
5563 if (next == '<') {
5564 redir_style = REDIRECT_HEREDOC;
5565 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005566 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005567 ch = i_getch(input);
5568 nommu_addchr(&ctx.as_string, ch);
5569 } else if (next == '>') {
5570 redir_style = REDIRECT_IO;
5571 ch = i_getch(input);
5572 nommu_addchr(&ctx.as_string, ch);
5573 }
5574#if 0
5575 else if (next == '(') {
5576 syntax_error("<(process) not supported");
5577 goto parse_error;
5578 }
5579#endif
5580 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5581 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005582 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005583 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005584 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005585 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005586 /* note: we do not add it to &ctx.as_string */
5587/* TODO: in bash:
5588 * comment inside $() goes to the next \n, even inside quoted string (!):
5589 * cmd "$(cmd2 #comment)" - syntax error
5590 * cmd "`cmd2 #comment`" - ok
5591 * We accept both (comment ends where command subst ends, in both cases).
5592 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005593 while (1) {
5594 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005595 if (ch == '\n') {
5596 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005597 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005598 }
5599 ch = i_getch(input);
5600 if (ch == EOF)
5601 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005602 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005603 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005604 }
5605 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005606 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005607 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005608
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005609 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005610 /* check that we are not in word in "a=1 2>word b=1": */
5611 && !ctx.pending_redirect
5612 ) {
5613 /* ch is a special char and thus this word
5614 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005615 ctx.is_assignment = NOT_ASSIGNMENT;
5616 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005617 }
5618
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005619 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5620
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005621 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005622 case SPECIAL_VAR_SYMBOL:
5623 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005624 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5625 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005626 /* fall through */
5627 case '#':
5628 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005629 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005630 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005631 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005632 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005633 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005634 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005635 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005636 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005637 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005638 case '"':
5639 ctx.word.has_quoted_part = 1;
5640 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005641 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005642 insert_empty_quoted_str_marker:
5643 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005644 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5645 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005646 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005647 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005648 if (ctx.is_assignment == NOT_ASSIGNMENT)
5649 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005650 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005651 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005652 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005653 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005654#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005655 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005656 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005657
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005658 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5659 o_addchr(&ctx.word, '`');
5660 USE_FOR_NOMMU(pos = ctx.word.length;)
5661 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005662 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005663# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005664 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005665 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005666# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005667 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5668 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005669 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005670 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005671#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005672 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005673#if ENABLE_HUSH_CASE
5674 case_semi:
5675#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005676 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005677 goto parse_error;
5678 }
5679 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005680#if ENABLE_HUSH_CASE
5681 /* Eat multiple semicolons, detect
5682 * whether it means something special */
5683 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005684 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005685 if (ch != ';')
5686 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005687 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005688 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005689 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005690 ctx.ctx_dsemicolon = 1;
5691 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005692 break;
5693 }
5694 }
5695#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005696 new_cmd:
5697 /* We just finished a cmd. New one may start
5698 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005699 ctx.is_assignment = MAYBE_ASSIGNMENT;
5700 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005701 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005702 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005703 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005704 goto parse_error;
5705 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005706 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005707 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005708 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005709 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005710 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005711 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005712 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005713 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005714 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005715 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005716 goto parse_error;
5717 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005718#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005719 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005720 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005721#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005722 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005723 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005724 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005725 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005726 } else {
5727 /* we could pick up a file descriptor choice here
5728 * with redirect_opt_num(), but bash doesn't do it.
5729 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005730 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005731 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005732 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005733 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005734#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005735 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005736 if (ctx.ctx_res_w == RES_MATCH
5737 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005738 && ctx.word.length == 0 /* not word(... */
5739 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005740 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005741 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005742 }
5743#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005744 /* fall through */
5745 case '{': {
5746 int n = parse_group(&ctx, input, ch);
5747 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005748 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005749 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005750 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5751 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005752 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005753 }
Eric Andersen25f27032001-04-26 23:22:31 +00005754 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005755#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005756 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005757 goto case_semi;
5758#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005759
Eric Andersen25f27032001-04-26 23:22:31 +00005760 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005761 /* proper use of this character is caught by end_trigger:
5762 * if we see {, we call parse_group(..., end_trigger='}')
5763 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005764 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005765 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005766 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005767 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005768 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005769 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005770 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005771 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005772
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005773 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005774 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005775 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005776 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005777 struct parse_context *pctx;
5778 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005779
5780 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005781 * Sample for finding leaks on syntax error recovery path.
5782 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005783 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005784 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005785 * while if (true | { true;}); then echo ok; fi; do break; done
5786 * 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 +00005787 */
5788 pctx = &ctx;
5789 do {
5790 /* Update pipe/command counts,
5791 * otherwise freeing may miss some */
5792 done_pipe(pctx, PIPE_SEQ);
5793 debug_printf_clean("freeing list %p from ctx %p\n",
5794 pctx->list_head, pctx);
5795 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005796 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005797 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005798#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005799 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005800#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005801 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005802 if (pctx != &ctx) {
5803 free(pctx);
5804 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005805 IF_HAS_KEYWORDS(pctx = p2;)
5806 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005807
Denys Vlasenko474cb202018-07-24 13:03:03 +02005808 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005809#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005810 if (pstring)
5811 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005812#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005813 debug_leave();
5814 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005815 }
Eric Andersen25f27032001-04-26 23:22:31 +00005816}
5817
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005818
5819/*** Execution routines ***/
5820
5821/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005822#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005823#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005824 expand_string_to_string(str)
5825#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005826static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005827#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005829#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005830static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005831
5832/* expand_strvec_to_strvec() takes a list of strings, expands
5833 * all variable references within and returns a pointer to
5834 * a list of expanded strings, possibly with larger number
5835 * of strings. (Think VAR="a b"; echo $VAR).
5836 * This new list is allocated as a single malloc block.
5837 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005838 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005839 * Caller can deallocate entire list by single free(list). */
5840
Denys Vlasenko238081f2010-10-03 14:26:26 +02005841/* A horde of its helpers come first: */
5842
5843static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5844{
5845 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005846 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005847
Denys Vlasenko9e800222010-10-03 14:28:04 +02005848#if ENABLE_HUSH_BRACE_EXPANSION
5849 if (c == '{' || c == '}') {
5850 /* { -> \{, } -> \} */
5851 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005852 /* And now we want to add { or } and continue:
5853 * o_addchr(o, c);
5854 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005855 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005856 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005857 }
5858#endif
5859 o_addchr(o, c);
5860 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005861 /* \z -> \\\z; \<eol> -> \\<eol> */
5862 o_addchr(o, '\\');
5863 if (len) {
5864 len--;
5865 o_addchr(o, '\\');
5866 o_addchr(o, *str++);
5867 }
5868 }
5869 }
5870}
5871
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005872/* Store given string, finalizing the word and starting new one whenever
5873 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005874 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005875 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005876 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5877 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005878static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005879{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005880 int last_is_ifs = 0;
5881
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005882 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005883 int word_len;
5884
5885 if (!*str) /* EOL - do not finalize word */
5886 break;
5887 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005888 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005889 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005890 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005891 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005892 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005893 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005894 * Example: "v='\*'; echo b$v" prints "b\*"
5895 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005896 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005897 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005898 /*/ Why can't we do it easier? */
5899 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5900 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5901 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005902 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005903 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005904 if (!*str) /* EOL - do not finalize word */
5905 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005906 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005907
5908 /* We know str here points to at least one IFS char */
5909 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005910 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005911 if (!*str) /* EOL - do not finalize word */
5912 break;
5913
Denys Vlasenko96786362018-04-11 16:02:58 +02005914 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5915 && strchr(G.ifs, *str) /* the second check would fail */
5916 ) {
5917 /* This is a non-whitespace $IFS char */
5918 /* Skip it and IFS whitespace chars, start new word */
5919 str++;
5920 str += strspn(str, G.ifs_whitespace);
5921 goto new_word;
5922 }
5923
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005924 /* Start new word... but not always! */
5925 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005926 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005927 /*
5928 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005929 * here nothing precedes the space in $v expansion,
5930 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005931 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005932 * It's okay if this accesses the byte before first argv[]:
5933 * past call to o_save_ptr() cleared it to zero byte
5934 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005935 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005936 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005937 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005938 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005939 o_addchr(output, '\0');
5940 debug_print_list("expand_on_ifs", output, n);
5941 n = o_save_ptr(output, n);
5942 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005943 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005944
Denys Vlasenko168579a2018-07-19 13:45:54 +02005945 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005946 debug_print_list("expand_on_ifs[1]", output, n);
5947 return n;
5948}
5949
5950/* Helper to expand $((...)) and heredoc body. These act as if
5951 * they are in double quotes, with the exception that they are not :).
5952 * Just the rules are similar: "expand only $var and `cmd`"
5953 *
5954 * Returns malloced string.
5955 * As an optimization, we return NULL if expansion is not needed.
5956 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005957static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005958{
5959 char *exp_str;
5960 struct in_str input;
5961 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005962 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005963
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005964 cp = str;
5965 for (;;) {
5966 if (!*cp) return NULL; /* string has no special chars */
5967 if (*cp == '$') break;
5968 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005969#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005970 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005971#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005972 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005973 }
5974
5975 /* We need to expand. Example:
5976 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5977 */
5978 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005979 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005980//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005981 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005982 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005983 EXP_FLAG_ESC_GLOB_CHARS,
5984 /*unbackslash:*/ 1
5985 );
5986 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005987 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005988 return exp_str;
5989}
5990
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005991static const char *first_special_char_in_vararg(const char *cp)
5992{
5993 for (;;) {
5994 if (!*cp) return NULL; /* string has no special chars */
5995 if (*cp == '$') return cp;
5996 if (*cp == '\\') return cp;
5997 if (*cp == '\'') return cp;
5998 if (*cp == '"') return cp;
5999#if ENABLE_HUSH_TICK
6000 if (*cp == '`') return cp;
6001#endif
6002 /* dquoted "${x:+ARG}" should not glob, therefore
6003 * '*' et al require some non-literal processing: */
6004 if (*cp == '*') return cp;
6005 if (*cp == '?') return cp;
6006 if (*cp == '[') return cp;
6007 cp++;
6008 }
6009}
6010
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006011/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6012 * These can contain single- and double-quoted strings,
6013 * and treated as if the ARG string is initially unquoted. IOW:
6014 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6015 * a dquoted string: "${var#"zz"}"), the difference only comes later
6016 * (word splitting and globbing of the ${var...} result).
6017 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006018#if !BASH_PATTERN_SUBST
6019#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6020 encode_then_expand_vararg(str, handle_squotes)
6021#endif
6022static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6023{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006024#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006025 const int do_unbackslash = 0;
6026#endif
6027 char *exp_str;
6028 struct in_str input;
6029 o_string dest = NULL_O_STRING;
6030
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006031 if (!first_special_char_in_vararg(str)) {
6032 /* string has no special chars */
6033 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006034 }
6035
Denys Vlasenkob762c782018-07-17 14:21:38 +02006036 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006037 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006038 exp_str = NULL;
6039
6040 for (;;) {
6041 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006042
6043 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006044 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6045 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006046
6047 if (!dest.o_expflags) {
6048 if (ch == EOF)
6049 break;
6050 if (handle_squotes && ch == '\'') {
6051 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006052 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006053 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006054 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006055 }
6056 if (ch == EOF) {
6057 syntax_error_unterm_ch('"');
6058 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006059 }
6060 if (ch == '"') {
6061 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6062 continue;
6063 }
6064 if (ch == '\\') {
6065 ch = i_getch(&input);
6066 if (ch == EOF) {
6067//example? error message? syntax_error_unterm_ch('"');
6068 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6069 goto ret;
6070 }
6071 o_addqchr(&dest, ch);
6072 continue;
6073 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006074 if (ch == '$') {
6075 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6076 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6077 goto ret;
6078 }
6079 continue;
6080 }
6081#if ENABLE_HUSH_TICK
6082 if (ch == '`') {
6083 //unsigned pos = dest->length;
6084 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6085 o_addchr(&dest, 0x80 | '`');
6086 if (!add_till_backquote(&dest, &input,
6087 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6088 )
6089 ) {
6090 goto ret; /* error */
6091 }
6092 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6093 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6094 continue;
6095 }
6096#endif
6097 o_addQchr(&dest, ch);
6098 } /* for (;;) */
6099
6100 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6101 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006102 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6103 do_unbackslash
6104 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006105 ret:
6106 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006107 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006108 return exp_str;
6109}
6110
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006111/* Expanding ARG in ${var+ARG}, ${var-ARG}
6112 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006113static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006114 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006115{
6116 struct in_str input;
6117 o_string dest = NULL_O_STRING;
6118
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006119 if (!first_special_char_in_vararg(str)
6120 && '\0' == str[strcspn(str, G.ifs)]
6121 ) {
6122 /* string has no special chars
6123 * && string has no $IFS chars
6124 */
6125 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006126 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006127
Denys Vlasenko294eb462018-07-20 16:18:59 +02006128 setup_string_in_str(&input, str);
6129
6130 for (;;) {
6131 int ch;
6132
6133 ch = i_getch(&input);
6134 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6135 __func__, ch, ch, dest.o_expflags);
6136
6137 if (!dest.o_expflags) {
6138 if (ch == EOF)
6139 break;
6140 if (!dquoted && strchr(G.ifs, ch)) {
6141 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6142 * do not assume we are at the start of the word (PREFIX above).
6143 */
6144 if (dest.data) {
6145 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006146 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006147 o_addchr(output, '\0');
6148 n = o_save_ptr(output, n); /* create next word */
6149 } else
6150 if (output->length != o_get_last_ptr(output, n)
6151 || output->has_quoted_part
6152 ) {
6153 /* For these cases:
6154 * f() { for i; do echo "|$i|"; done; }; x=x
6155 * f a${x:+ }b # 1st condition
6156 * |a|
6157 * |b|
6158 * f ""${x:+ }b # 2nd condition
6159 * ||
6160 * |b|
6161 */
6162 o_addchr(output, '\0');
6163 n = o_save_ptr(output, n); /* create next word */
6164 }
6165 continue;
6166 }
6167 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006168 if (!add_till_single_quote_dquoted(&dest, &input))
6169 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006170 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6171 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006172 continue;
6173 }
6174 }
6175 if (ch == EOF) {
6176 syntax_error_unterm_ch('"');
6177 goto ret; /* error */
6178 }
6179 if (ch == '"') {
6180 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006181 if (dest.o_expflags) {
6182 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6183 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6184 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006185 continue;
6186 }
6187 if (ch == '\\') {
6188 ch = i_getch(&input);
6189 if (ch == EOF) {
6190//example? error message? syntax_error_unterm_ch('"');
6191 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6192 goto ret;
6193 }
6194 o_addqchr(&dest, ch);
6195 continue;
6196 }
6197 if (ch == '$') {
6198 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6199 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6200 goto ret;
6201 }
6202 continue;
6203 }
6204#if ENABLE_HUSH_TICK
6205 if (ch == '`') {
6206 //unsigned pos = dest->length;
6207 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6208 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6209 if (!add_till_backquote(&dest, &input,
6210 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6211 )
6212 ) {
6213 goto ret; /* error */
6214 }
6215 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6216 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6217 continue;
6218 }
6219#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006220 if (dquoted) {
6221 /* Always glob-protect if in dquotes:
6222 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6223 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6224 */
6225 o_addqchr(&dest, ch);
6226 } else {
6227 /* Glob-protect only if char is quoted:
6228 * x=x; echo ${x:+/bin/c*} - prints many filenames
6229 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6230 */
6231 o_addQchr(&dest, ch);
6232 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006233 } /* for (;;) */
6234
6235 if (dest.data) {
6236 n = expand_vars_to_list(output, n, dest.data);
6237 }
6238 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006239 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006240 return n;
6241}
6242
Denys Vlasenko0b883582016-12-23 16:49:07 +01006243#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006244static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006245{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006246 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006247 arith_t res;
6248 char *exp_str;
6249
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006250 math_state.lookupvar = get_local_var_value;
6251 math_state.setvar = set_local_var_from_halves;
6252 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006253 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006254 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006255 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006256 if (errmsg_p)
6257 *errmsg_p = math_state.errmsg;
6258 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006259 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006260 return res;
6261}
6262#endif
6263
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006264#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006265/* ${var/[/]pattern[/repl]} helpers */
6266static char *strstr_pattern(char *val, const char *pattern, int *size)
6267{
6268 while (1) {
6269 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6270 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6271 if (end) {
6272 *size = end - val;
6273 return val;
6274 }
6275 if (*val == '\0')
6276 return NULL;
6277 /* Optimization: if "*pat" did not match the start of "string",
6278 * we know that "tring", "ring" etc will not match too:
6279 */
6280 if (pattern[0] == '*')
6281 return NULL;
6282 val++;
6283 }
6284}
6285static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6286{
6287 char *result = NULL;
6288 unsigned res_len = 0;
6289 unsigned repl_len = strlen(repl);
6290
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006291 /* Null pattern never matches, including if "var" is empty */
6292 if (!pattern[0])
6293 return result; /* NULL, no replaces happened */
6294
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006295 while (1) {
6296 int size;
6297 char *s = strstr_pattern(val, pattern, &size);
6298 if (!s)
6299 break;
6300
6301 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006302 strcpy(mempcpy(result + res_len, val, s - val), repl);
6303 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006304 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6305
6306 val = s + size;
6307 if (exp_op == '/')
6308 break;
6309 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006310 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006311 result = xrealloc(result, res_len + strlen(val) + 1);
6312 strcpy(result + res_len, val);
6313 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6314 }
6315 debug_printf_varexp("result:'%s'\n", result);
6316 return result;
6317}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006318#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006319
Denys Vlasenko168579a2018-07-19 13:45:54 +02006320static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006321 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006322{
6323 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6324 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6325 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6326 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006327 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006328 } else { /* quoted "$VAR" */
6329 output->has_quoted_part = 1;
6330 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6331 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6332 if (val && val[0])
6333 o_addQstr(output, val);
6334 }
6335 return n;
6336}
6337
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006338/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006339 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006340static NOINLINE int expand_one_var(o_string *output, int n,
6341 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006342{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006343 const char *val;
6344 char *to_be_freed;
6345 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006346 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006347 char exp_op;
6348 char exp_save = exp_save; /* for compiler */
6349 char *exp_saveptr; /* points to expansion operator */
6350 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006351 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006353 val = NULL;
6354 to_be_freed = NULL;
6355 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006356 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006357 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006358 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006359 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006360 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006361 exp_op = 0;
6362
Denys Vlasenkob762c782018-07-17 14:21:38 +02006363 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006364 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6365 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6366 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006367 ) {
6368 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369 var++;
6370 exp_op = 'L';
6371 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006372 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006373 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006374 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375 ) {
6376 /* ${?:0}, ${#[:]%0} etc */
6377 exp_saveptr = var + 1;
6378 } else {
6379 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6380 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6381 }
6382 exp_op = exp_save = *exp_saveptr;
6383 if (exp_op) {
6384 exp_word = exp_saveptr + 1;
6385 if (exp_op == ':') {
6386 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006387//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006388 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006389 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006390 ) {
6391 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6392 exp_op = ':';
6393 exp_word--;
6394 }
6395 }
6396 *exp_saveptr = '\0';
6397 } /* else: it's not an expansion op, but bare ${var} */
6398 }
6399
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006400 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006401 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006402 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006403 int nn = xatoi_positive(var);
6404 if (nn < G.global_argc)
6405 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006406 /* else val remains NULL: $N with too big N */
6407 } else {
6408 switch (var[0]) {
6409 case '$': /* pid */
6410 val = utoa(G.root_pid);
6411 break;
6412 case '!': /* bg pid */
6413 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6414 break;
6415 case '?': /* exitcode */
6416 val = utoa(G.last_exitcode);
6417 break;
6418 case '#': /* argc */
6419 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6420 break;
6421 default:
6422 val = get_local_var_value(var);
6423 }
6424 }
6425
6426 /* Handle any expansions */
6427 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006428 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006429 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006430 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006431 debug_printf_expand("%s\n", val);
6432 } else if (exp_op) {
6433 if (exp_op == '%' || exp_op == '#') {
6434 /* Standard-mandated substring removal ops:
6435 * ${parameter%word} - remove smallest suffix pattern
6436 * ${parameter%%word} - remove largest suffix pattern
6437 * ${parameter#word} - remove smallest prefix pattern
6438 * ${parameter##word} - remove largest prefix pattern
6439 *
6440 * Word is expanded to produce a glob pattern.
6441 * Then var's value is matched to it and matching part removed.
6442 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006443//FIXME: ${x#...${...}...}
6444//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6445//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006446 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006447 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006448 char *exp_exp_word;
6449 char *loc;
6450 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006451 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006452 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006453 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006454 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006455 if (exp_exp_word)
6456 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006457 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6458 /*
6459 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006460 * G.global_argv and results of utoa and get_local_var_value
6461 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006462 * scan_and_match momentarily stores NULs there.
6463 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006464 t = (char*)val;
6465 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006466 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 +02006467 free(exp_exp_word);
6468 if (loc) { /* match was found */
6469 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006470 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006471 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006472 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006473 }
6474 }
6475 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006476#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006477 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006478 /* It's ${var/[/]pattern[/repl]} thing.
6479 * Note that in encoded form it has TWO parts:
6480 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006481 * and if // is used, it is encoded as \:
6482 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006483 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006484 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006485 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006486 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006487 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006488 * >az >bz
6489 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6490 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6491 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6492 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006493 * (note that a*z _pattern_ is never globbed!)
6494 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006495 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006496 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 if (!pattern)
6498 pattern = xstrdup(exp_word);
6499 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6500 *p++ = SPECIAL_VAR_SYMBOL;
6501 exp_word = p;
6502 p = strchr(p, SPECIAL_VAR_SYMBOL);
6503 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006504 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006505 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6506 /* HACK ALERT. We depend here on the fact that
6507 * G.global_argv and results of utoa and get_local_var_value
6508 * are actually in writable memory:
6509 * replace_pattern momentarily stores NULs there. */
6510 t = (char*)val;
6511 to_be_freed = replace_pattern(t,
6512 pattern,
6513 (repl ? repl : exp_word),
6514 exp_op);
6515 if (to_be_freed) /* at least one replace happened */
6516 val = to_be_freed;
6517 free(pattern);
6518 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006519 } else {
6520 /* Empty variable always gives nothing */
6521 // "v=''; echo ${v/*/w}" prints "", not "w"
6522 /* Just skip "replace" part */
6523 *p++ = SPECIAL_VAR_SYMBOL;
6524 p = strchr(p, SPECIAL_VAR_SYMBOL);
6525 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 }
6527 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006528#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006529 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006530#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006531 /* It's ${var:N[:M]} bashism.
6532 * Note that in encoded form it has TWO parts:
6533 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6534 */
6535 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006536 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006537
Denys Vlasenko063847d2010-09-15 13:33:02 +02006538 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6539 if (errmsg)
6540 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006541 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6542 *p++ = SPECIAL_VAR_SYMBOL;
6543 exp_word = p;
6544 p = strchr(p, SPECIAL_VAR_SYMBOL);
6545 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006546 len = expand_and_evaluate_arith(exp_word, &errmsg);
6547 if (errmsg)
6548 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006549 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006550 if (beg < 0) {
6551 /* negative beg counts from the end */
6552 beg = (arith_t)strlen(val) + beg;
6553 if (beg < 0) /* ${v: -999999} is "" */
6554 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006555 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006556 debug_printf_varexp("from val:'%s'\n", val);
6557 if (len < 0) {
6558 /* in bash, len=-n means strlen()-n */
6559 len = (arith_t)strlen(val) - beg + len;
6560 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006561 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006562 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006563 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006564 arith_err:
6565 val = NULL;
6566 } else {
6567 /* Paranoia. What if user entered 9999999999999
6568 * which fits in arith_t but not int? */
6569 if (len >= INT_MAX)
6570 len = INT_MAX;
6571 val = to_be_freed = xstrndup(val + beg, len);
6572 }
6573 debug_printf_varexp("val:'%s'\n", val);
6574#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006575 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006576 val = NULL;
6577#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006578 } else { /* one of "-=+?" */
6579 /* Standard-mandated substitution ops:
6580 * ${var?word} - indicate error if unset
6581 * If var is unset, word (or a message indicating it is unset
6582 * if word is null) is written to standard error
6583 * and the shell exits with a non-zero exit status.
6584 * Otherwise, the value of var is substituted.
6585 * ${var-word} - use default value
6586 * If var is unset, word is substituted.
6587 * ${var=word} - assign and use default value
6588 * If var is unset, word is assigned to var.
6589 * In all cases, final value of var is substituted.
6590 * ${var+word} - use alternative value
6591 * If var is unset, null is substituted.
6592 * Otherwise, word is substituted.
6593 *
6594 * Word is subjected to tilde expansion, parameter expansion,
6595 * command substitution, and arithmetic expansion.
6596 * If word is not needed, it is not expanded.
6597 *
6598 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6599 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006600 *
6601 * Word-splitting and single quote behavior:
6602 *
6603 * $ f() { for i; do echo "|$i|"; done; };
6604 *
6605 * $ x=; f ${x:?'x y' z}
6606 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6607 * $ x=; f "${x:?'x y' z}"
6608 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6609 *
6610 * $ x=; f ${x:='x y' z}
6611 * |x|
6612 * |y|
6613 * |z|
6614 * $ x=; f "${x:='x y' z}"
6615 * |'x y' z|
6616 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006617 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006618 * |x y|
6619 * |z|
6620 * $ x=x; f "${x:+'x y' z}"
6621 * |'x y' z|
6622 *
6623 * $ x=; f ${x:-'x y' z}
6624 * |x y|
6625 * |z|
6626 * $ x=; f "${x:-'x y' z}"
6627 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006628 */
6629 int use_word = (!val || ((exp_save == ':') && !val[0]));
6630 if (exp_op == '+')
6631 use_word = !use_word;
6632 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6633 (exp_save == ':') ? "true" : "false", use_word);
6634 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006635 if (exp_op == '+' || exp_op == '-') {
6636 /* ${var+word} - use alternative value */
6637 /* ${var-word} - use default value */
6638 n = encode_then_append_var_plusminus(output, n, exp_word,
6639 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006640 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006641 val = NULL;
6642 } else {
6643 /* ${var?word} - indicate error if unset */
6644 /* ${var=word} - assign and use default value */
6645 to_be_freed = encode_then_expand_vararg(exp_word,
6646 /*handle_squotes:*/ !(arg0 & 0x80),
6647 /*unbackslash:*/ 0
6648 );
6649 if (to_be_freed)
6650 exp_word = to_be_freed;
6651 if (exp_op == '?') {
6652 /* mimic bash message */
6653 msg_and_die_if_script("%s: %s",
6654 var,
6655 exp_word[0]
6656 ? exp_word
6657 : "parameter null or not set"
6658 /* ash has more specific messages, a-la: */
6659 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6660 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006661//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006662//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006663// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6664// bash: x: x y z
6665// $
6666// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006667 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006668 val = exp_word;
6669 }
6670 if (exp_op == '=') {
6671 /* ${var=[word]} or ${var:=[word]} */
6672 if (isdigit(var[0]) || var[0] == '#') {
6673 /* mimic bash message */
6674 msg_and_die_if_script("$%s: cannot assign in this way", var);
6675 val = NULL;
6676 } else {
6677 char *new_var = xasprintf("%s=%s", var, val);
6678 set_local_var(new_var, /*flag:*/ 0);
6679 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006680 }
6681 }
6682 }
6683 } /* one of "-=+?" */
6684
6685 *exp_saveptr = exp_save;
6686 } /* if (exp_op) */
6687
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006688 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006690
Denys Vlasenko168579a2018-07-19 13:45:54 +02006691 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006692
6693 free(to_be_freed);
6694 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006695}
6696
6697/* Expand all variable references in given string, adding words to list[]
6698 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6699 * to be filled). This routine is extremely tricky: has to deal with
6700 * variables/parameters with whitespace, $* and $@, and constructs like
6701 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006702static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006703{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006704 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006705 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006706 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006707 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006708 char *p;
6709
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006710 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6711 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006712 debug_print_list("expand_vars_to_list[0]", output, n);
6713
6714 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6715 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006716#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006717 char arith_buf[sizeof(arith_t)*3 + 2];
6718#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006719
Denys Vlasenko168579a2018-07-19 13:45:54 +02006720 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006721 o_addchr(output, '\0');
6722 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006723 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006724 }
6725
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006726 o_addblock(output, arg, p - arg);
6727 debug_print_list("expand_vars_to_list[1]", output, n);
6728 arg = ++p;
6729 p = strchr(p, SPECIAL_VAR_SYMBOL);
6730
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006731 /* Fetch special var name (if it is indeed one of them)
6732 * and quote bit, force the bit on if singleword expansion -
6733 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006734 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006735
6736 /* Is this variable quoted and thus expansion can't be null?
6737 * "$@" is special. Even if quoted, it can still
6738 * expand to nothing (not even an empty string),
6739 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006740 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006741 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742
6743 switch (first_ch & 0x7f) {
6744 /* Highest bit in first_ch indicates that var is double-quoted */
6745 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006746 case '@': {
6747 int i;
6748 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006749 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006750 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006751 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006752 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006753 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006754 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006755 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6756 if (G.global_argv[i++][0] && G.global_argv[i]) {
6757 /* this argv[] is not empty and not last:
6758 * put terminating NUL, start new word */
6759 o_addchr(output, '\0');
6760 debug_print_list("expand_vars_to_list[2]", output, n);
6761 n = o_save_ptr(output, n);
6762 debug_print_list("expand_vars_to_list[3]", output, n);
6763 }
6764 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006765 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006766 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006767 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006768 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006769 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006770 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006771 while (1) {
6772 o_addQstr(output, G.global_argv[i]);
6773 if (++i >= G.global_argc)
6774 break;
6775 o_addchr(output, '\0');
6776 debug_print_list("expand_vars_to_list[4]", output, n);
6777 n = o_save_ptr(output, n);
6778 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006779 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006780 while (1) {
6781 o_addQstr(output, G.global_argv[i]);
6782 if (!G.global_argv[++i])
6783 break;
6784 if (G.ifs[0])
6785 o_addchr(output, G.ifs[0]);
6786 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006787 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788 }
6789 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006790 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006791 case SPECIAL_VAR_SYMBOL: {
6792 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006793 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006794 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006795 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006796 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006797 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006798 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006799 case SPECIAL_VAR_QUOTED_SVS:
6800 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006801 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006802 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006803 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006804 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006805#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006806 case '`': {
6807 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006808 o_string subst_result = NULL_O_STRING;
6809
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006810 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006811 arg++;
6812 /* Can't just stuff it into output o_string,
6813 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006814 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006815 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6816 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006817 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006818 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006819 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006820 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006821 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006822 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006823#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006824#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006825 case '+': {
6826 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006827 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006828
6829 arg++; /* skip '+' */
6830 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6831 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006832 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006833 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6834 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006835 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006836 break;
6837 }
6838#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006839 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006840 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006841 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006842 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006843 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6844
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006845 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6846 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847 if (*p != SPECIAL_VAR_SYMBOL)
6848 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006849 arg = ++p;
6850 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6851
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006852 if (*arg) {
6853 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006854 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006855 o_addchr(output, '\0');
6856 n = o_save_ptr(output, n);
6857 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006858 debug_print_list("expand_vars_to_list[a]", output, n);
6859 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006860 * if needed (much earlier), do not use o_addQstr here!
6861 */
6862 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006863 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006864 } else
6865 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006866 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6867 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006868 ) {
6869 n--;
6870 /* allow to reuse list[n] later without re-growth */
6871 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006872 }
6873
6874 return n;
6875}
6876
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006877static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006878{
6879 int n;
6880 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006881 o_string output = NULL_O_STRING;
6882
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006883 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006884
6885 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006886 for (;;) {
6887 /* go to next list[n] */
6888 output.ended_in_ifs = 0;
6889 n = o_save_ptr(&output, n);
6890
6891 if (!*argv)
6892 break;
6893
6894 /* expand argv[i] */
6895 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006896 /* if (!output->has_empty_slot) -- need this?? */
6897 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006898 }
6899 debug_print_list("expand_variables", &output, n);
6900
6901 /* output.data (malloced in one block) gets returned in "list" */
6902 list = o_finalize_list(&output, n);
6903 debug_print_strings("expand_variables[1]", list);
6904 return list;
6905}
6906
6907static char **expand_strvec_to_strvec(char **argv)
6908{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006909 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006910}
6911
Denys Vlasenko11752d42018-04-03 08:20:58 +02006912#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6914{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006915 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006916}
6917#endif
6918
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006919/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006920 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006921 *
6922 * NB: should NOT do globbing!
6923 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6924 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006925static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006926{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006927#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006928 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006929 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006930#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006931 char *argv[2], **list;
6932
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006933 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006934 /* This is generally an optimization, but it also
6935 * handles "", which otherwise trips over !list[0] check below.
6936 * (is this ever happens that we actually get str="" here?)
6937 */
6938 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6939 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006940 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006941 return xstrdup(str);
6942 }
6943
6944 argv[0] = (char*)str;
6945 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006946 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006947 if (!list[0]) {
6948 /* Example where it happens:
6949 * x=; echo ${x:-"$@"}
6950 */
6951 ((char*)list)[0] = '\0';
6952 } else {
6953 if (HUSH_DEBUG)
6954 if (list[1])
6955 bb_error_msg_and_die("BUG in varexp2");
6956 /* actually, just move string 2*sizeof(char*) bytes back */
6957 overlapping_strcpy((char*)list, list[0]);
6958 if (do_unbackslash)
6959 unbackslash((char*)list);
6960 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006961 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006962 return (char*)list;
6963}
6964
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006965#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006966static char* expand_strvec_to_string(char **argv)
6967{
6968 char **list;
6969
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006970 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006971 /* Convert all NULs to spaces */
6972 if (list[0]) {
6973 int n = 1;
6974 while (list[n]) {
6975 if (HUSH_DEBUG)
6976 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6977 bb_error_msg_and_die("BUG in varexp3");
6978 /* bash uses ' ' regardless of $IFS contents */
6979 list[n][-1] = ' ';
6980 n++;
6981 }
6982 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006983 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006984 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6985 return (char*)list;
6986}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006987#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006988
6989static char **expand_assignments(char **argv, int count)
6990{
6991 int i;
6992 char **p;
6993
6994 G.expanded_assignments = p = NULL;
6995 /* Expand assignments into one string each */
6996 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006997 p = add_string_to_strings(p,
6998 expand_string_to_string(argv[i],
6999 EXP_FLAG_ESC_GLOB_CHARS,
7000 /*unbackslash:*/ 1
7001 )
7002 );
7003 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007004 }
7005 G.expanded_assignments = NULL;
7006 return p;
7007}
7008
7009
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007010static void switch_off_special_sigs(unsigned mask)
7011{
7012 unsigned sig = 0;
7013 while ((mask >>= 1) != 0) {
7014 sig++;
7015 if (!(mask & 1))
7016 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007017#if ENABLE_HUSH_TRAP
7018 if (G_traps) {
7019 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007020 /* trap is '', has to remain SIG_IGN */
7021 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007022 free(G_traps[sig]);
7023 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007024 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007025#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007026 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007027 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007028 }
7029}
7030
Denys Vlasenkob347df92011-08-09 22:49:15 +02007031#if BB_MMU
7032/* never called */
7033void re_execute_shell(char ***to_free, const char *s,
7034 char *g_argv0, char **g_argv,
7035 char **builtin_argv) NORETURN;
7036
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007037static void reset_traps_to_defaults(void)
7038{
7039 /* This function is always called in a child shell
7040 * after fork (not vfork, NOMMU doesn't use this function).
7041 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007042 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007043 unsigned mask;
7044
7045 /* Child shells are not interactive.
7046 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7047 * Testcase: (while :; do :; done) + ^Z should background.
7048 * Same goes for SIGTERM, SIGHUP, SIGINT.
7049 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007050 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007051 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007052 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007053
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007054 /* Switch off special sigs */
7055 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007056# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007057 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007058# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007059 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007060 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7061 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007063# if ENABLE_HUSH_TRAP
7064 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007065 return;
7066
7067 /* Reset all sigs to default except ones with empty traps */
7068 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007069 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007070 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007071 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007072 continue; /* empty trap: has to remain SIG_IGN */
7073 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007074 free(G_traps[sig]);
7075 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007076 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007077 if (sig == 0)
7078 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007079 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007080 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007081# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007082}
7083
7084#else /* !BB_MMU */
7085
7086static void re_execute_shell(char ***to_free, const char *s,
7087 char *g_argv0, char **g_argv,
7088 char **builtin_argv) NORETURN;
7089static void re_execute_shell(char ***to_free, const char *s,
7090 char *g_argv0, char **g_argv,
7091 char **builtin_argv)
7092{
7093# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7094 /* delims + 2 * (number of bytes in printed hex numbers) */
7095 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7096 char *heredoc_argv[4];
7097 struct variable *cur;
7098# if ENABLE_HUSH_FUNCTIONS
7099 struct function *funcp;
7100# endif
7101 char **argv, **pp;
7102 unsigned cnt;
7103 unsigned long long empty_trap_mask;
7104
7105 if (!g_argv0) { /* heredoc */
7106 argv = heredoc_argv;
7107 argv[0] = (char *) G.argv0_for_re_execing;
7108 argv[1] = (char *) "-<";
7109 argv[2] = (char *) s;
7110 argv[3] = NULL;
7111 pp = &argv[3]; /* used as pointer to empty environment */
7112 goto do_exec;
7113 }
7114
7115 cnt = 0;
7116 pp = builtin_argv;
7117 if (pp) while (*pp++)
7118 cnt++;
7119
7120 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007121 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007122 int sig;
7123 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007124 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007125 empty_trap_mask |= 1LL << sig;
7126 }
7127 }
7128
7129 sprintf(param_buf, NOMMU_HACK_FMT
7130 , (unsigned) G.root_pid
7131 , (unsigned) G.root_ppid
7132 , (unsigned) G.last_bg_pid
7133 , (unsigned) G.last_exitcode
7134 , cnt
7135 , empty_trap_mask
7136 IF_HUSH_LOOPS(, G.depth_of_loop)
7137 );
7138# undef NOMMU_HACK_FMT
7139 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7140 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7141 */
7142 cnt += 6;
7143 for (cur = G.top_var; cur; cur = cur->next) {
7144 if (!cur->flg_export || cur->flg_read_only)
7145 cnt += 2;
7146 }
7147# if ENABLE_HUSH_FUNCTIONS
7148 for (funcp = G.top_func; funcp; funcp = funcp->next)
7149 cnt += 3;
7150# endif
7151 pp = g_argv;
7152 while (*pp++)
7153 cnt++;
7154 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7155 *pp++ = (char *) G.argv0_for_re_execing;
7156 *pp++ = param_buf;
7157 for (cur = G.top_var; cur; cur = cur->next) {
7158 if (strcmp(cur->varstr, hush_version_str) == 0)
7159 continue;
7160 if (cur->flg_read_only) {
7161 *pp++ = (char *) "-R";
7162 *pp++ = cur->varstr;
7163 } else if (!cur->flg_export) {
7164 *pp++ = (char *) "-V";
7165 *pp++ = cur->varstr;
7166 }
7167 }
7168# if ENABLE_HUSH_FUNCTIONS
7169 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7170 *pp++ = (char *) "-F";
7171 *pp++ = funcp->name;
7172 *pp++ = funcp->body_as_string;
7173 }
7174# endif
7175 /* We can pass activated traps here. Say, -Tnn:trap_string
7176 *
7177 * However, POSIX says that subshells reset signals with traps
7178 * to SIG_DFL.
7179 * I tested bash-3.2 and it not only does that with true subshells
7180 * of the form ( list ), but with any forked children shells.
7181 * I set trap "echo W" WINCH; and then tried:
7182 *
7183 * { echo 1; sleep 20; echo 2; } &
7184 * while true; do echo 1; sleep 20; echo 2; break; done &
7185 * true | { echo 1; sleep 20; echo 2; } | cat
7186 *
7187 * In all these cases sending SIGWINCH to the child shell
7188 * did not run the trap. If I add trap "echo V" WINCH;
7189 * _inside_ group (just before echo 1), it works.
7190 *
7191 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007192 */
7193 *pp++ = (char *) "-c";
7194 *pp++ = (char *) s;
7195 if (builtin_argv) {
7196 while (*++builtin_argv)
7197 *pp++ = *builtin_argv;
7198 *pp++ = (char *) "";
7199 }
7200 *pp++ = g_argv0;
7201 while (*g_argv)
7202 *pp++ = *g_argv++;
7203 /* *pp = NULL; - is already there */
7204 pp = environ;
7205
7206 do_exec:
7207 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007208 /* Don't propagate SIG_IGN to the child */
7209 if (SPECIAL_JOBSTOP_SIGS != 0)
7210 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007211 execve(bb_busybox_exec_path, argv, pp);
7212 /* Fallback. Useful for init=/bin/hush usage etc */
7213 if (argv[0][0] == '/')
7214 execve(argv[0], argv, pp);
7215 xfunc_error_retval = 127;
7216 bb_error_msg_and_die("can't re-execute the shell");
7217}
7218#endif /* !BB_MMU */
7219
7220
7221static int run_and_free_list(struct pipe *pi);
7222
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007223/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007224 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7225 * end_trigger controls how often we stop parsing
7226 * NUL: parse all, execute, return
7227 * ';': parse till ';' or newline, execute, repeat till EOF
7228 */
7229static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007230{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007231 /* Why we need empty flag?
7232 * An obscure corner case "false; ``; echo $?":
7233 * empty command in `` should still set $? to 0.
7234 * But we can't just set $? to 0 at the start,
7235 * this breaks "false; echo `echo $?`" case.
7236 */
7237 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007238 while (1) {
7239 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007240
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007241#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007242 if (end_trigger == ';') {
7243 G.promptmode = 0; /* PS1 */
7244 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7245 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007246#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007247 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007248 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7249 /* If we are in "big" script
7250 * (not in `cmd` or something similar)...
7251 */
7252 if (pipe_list == ERR_PTR && end_trigger == ';') {
7253 /* Discard cached input (rest of line) */
7254 int ch = inp->last_char;
7255 while (ch != EOF && ch != '\n') {
7256 //bb_error_msg("Discarded:'%c'", ch);
7257 ch = i_getch(inp);
7258 }
7259 /* Force prompt */
7260 inp->p = NULL;
7261 /* This stream isn't empty */
7262 empty = 0;
7263 continue;
7264 }
7265 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007266 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007267 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007268 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007269 debug_print_tree(pipe_list, 0);
7270 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7271 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007272 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007273 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007274 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007275 }
Eric Andersen25f27032001-04-26 23:22:31 +00007276}
7277
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007278static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007279{
7280 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007281 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7282
Eric Andersen25f27032001-04-26 23:22:31 +00007283 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007284 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007285 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007286}
7287
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007288static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007289{
Eric Andersen25f27032001-04-26 23:22:31 +00007290 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007291 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007292
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007293 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007294 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007295 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007296 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007297}
7298
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007299#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007300static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007301{
7302 pid_t pid;
7303 int channel[2];
7304# if !BB_MMU
7305 char **to_free = NULL;
7306# endif
7307
7308 xpipe(channel);
7309 pid = BB_MMU ? xfork() : xvfork();
7310 if (pid == 0) { /* child */
7311 disable_restore_tty_pgrp_on_exit();
7312 /* Process substitution is not considered to be usual
7313 * 'command execution'.
7314 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7315 */
7316 bb_signals(0
7317 + (1 << SIGTSTP)
7318 + (1 << SIGTTIN)
7319 + (1 << SIGTTOU)
7320 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007321 close(channel[0]); /* NB: close _first_, then move fd! */
7322 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007323# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007324 /* Awful hack for `trap` or $(trap).
7325 *
7326 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7327 * contains an example where "trap" is executed in a subshell:
7328 *
7329 * save_traps=$(trap)
7330 * ...
7331 * eval "$save_traps"
7332 *
7333 * Standard does not say that "trap" in subshell shall print
7334 * parent shell's traps. It only says that its output
7335 * must have suitable form, but then, in the above example
7336 * (which is not supposed to be normative), it implies that.
7337 *
7338 * bash (and probably other shell) does implement it
7339 * (traps are reset to defaults, but "trap" still shows them),
7340 * but as a result, "trap" logic is hopelessly messed up:
7341 *
7342 * # trap
7343 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7344 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7345 * # true | trap <--- trap is in subshell - no output (ditto)
7346 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7347 * trap -- 'echo Ho' SIGWINCH
7348 * # echo `(trap)` <--- in subshell in subshell - output
7349 * trap -- 'echo Ho' SIGWINCH
7350 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7351 * trap -- 'echo Ho' SIGWINCH
7352 *
7353 * The rules when to forget and when to not forget traps
7354 * get really complex and nonsensical.
7355 *
7356 * Our solution: ONLY bare $(trap) or `trap` is special.
7357 */
7358 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007359 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007360 && skip_whitespace(s + 4)[0] == '\0'
7361 ) {
7362 static const char *const argv[] = { NULL, NULL };
7363 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007364 fflush_all(); /* important */
7365 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007366 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007367# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007368# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007369 /* Prevent it from trying to handle ctrl-z etc */
7370 IF_HUSH_JOB(G.run_list_level = 1;)
7371 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007372 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007373 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007374 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007375 parse_and_run_string(s);
7376 _exit(G.last_exitcode);
7377# else
7378 /* We re-execute after vfork on NOMMU. This makes this script safe:
7379 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7380 * huge=`cat BIG` # was blocking here forever
7381 * echo OK
7382 */
7383 re_execute_shell(&to_free,
7384 s,
7385 G.global_argv[0],
7386 G.global_argv + 1,
7387 NULL);
7388# endif
7389 }
7390
7391 /* parent */
7392 *pid_p = pid;
7393# if ENABLE_HUSH_FAST
7394 G.count_SIGCHLD++;
7395//bb_error_msg("[%d] fork in generate_stream_from_string:"
7396// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7397// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7398# endif
7399 enable_restore_tty_pgrp_on_exit();
7400# if !BB_MMU
7401 free(to_free);
7402# endif
7403 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007404 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007405}
7406
7407/* Return code is exit status of the process that is run. */
7408static int process_command_subs(o_string *dest, const char *s)
7409{
7410 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007411 pid_t pid;
7412 int status, ch, eol_cnt;
7413
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007414 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007415
7416 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007417 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007418 while ((ch = getc(fp)) != EOF) {
7419 if (ch == '\0')
7420 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007421 if (ch == '\n') {
7422 eol_cnt++;
7423 continue;
7424 }
7425 while (eol_cnt) {
7426 o_addchr(dest, '\n');
7427 eol_cnt--;
7428 }
7429 o_addQchr(dest, ch);
7430 }
7431
7432 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007433 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007434 /* We need to extract exitcode. Test case
7435 * "true; echo `sleep 1; false` $?"
7436 * should print 1 */
7437 safe_waitpid(pid, &status, 0);
7438 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7439 return WEXITSTATUS(status);
7440}
7441#endif /* ENABLE_HUSH_TICK */
7442
7443
7444static void setup_heredoc(struct redir_struct *redir)
7445{
7446 struct fd_pair pair;
7447 pid_t pid;
7448 int len, written;
7449 /* the _body_ of heredoc (misleading field name) */
7450 const char *heredoc = redir->rd_filename;
7451 char *expanded;
7452#if !BB_MMU
7453 char **to_free;
7454#endif
7455
7456 expanded = NULL;
7457 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007458 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007459 if (expanded)
7460 heredoc = expanded;
7461 }
7462 len = strlen(heredoc);
7463
7464 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7465 xpiped_pair(pair);
7466 xmove_fd(pair.rd, redir->rd_fd);
7467
7468 /* Try writing without forking. Newer kernels have
7469 * dynamically growing pipes. Must use non-blocking write! */
7470 ndelay_on(pair.wr);
7471 while (1) {
7472 written = write(pair.wr, heredoc, len);
7473 if (written <= 0)
7474 break;
7475 len -= written;
7476 if (len == 0) {
7477 close(pair.wr);
7478 free(expanded);
7479 return;
7480 }
7481 heredoc += written;
7482 }
7483 ndelay_off(pair.wr);
7484
7485 /* Okay, pipe buffer was not big enough */
7486 /* Note: we must not create a stray child (bastard? :)
7487 * for the unsuspecting parent process. Child creates a grandchild
7488 * and exits before parent execs the process which consumes heredoc
7489 * (that exec happens after we return from this function) */
7490#if !BB_MMU
7491 to_free = NULL;
7492#endif
7493 pid = xvfork();
7494 if (pid == 0) {
7495 /* child */
7496 disable_restore_tty_pgrp_on_exit();
7497 pid = BB_MMU ? xfork() : xvfork();
7498 if (pid != 0)
7499 _exit(0);
7500 /* grandchild */
7501 close(redir->rd_fd); /* read side of the pipe */
7502#if BB_MMU
7503 full_write(pair.wr, heredoc, len); /* may loop or block */
7504 _exit(0);
7505#else
7506 /* Delegate blocking writes to another process */
7507 xmove_fd(pair.wr, STDOUT_FILENO);
7508 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7509#endif
7510 }
7511 /* parent */
7512#if ENABLE_HUSH_FAST
7513 G.count_SIGCHLD++;
7514//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7515#endif
7516 enable_restore_tty_pgrp_on_exit();
7517#if !BB_MMU
7518 free(to_free);
7519#endif
7520 close(pair.wr);
7521 free(expanded);
7522 wait(NULL); /* wait till child has died */
7523}
7524
Denys Vlasenko2db74612017-07-07 22:07:28 +02007525struct squirrel {
7526 int orig_fd;
7527 int moved_to;
7528 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7529 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7530};
7531
Denys Vlasenko621fc502017-07-24 12:42:17 +02007532static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7533{
7534 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7535 sq[i].orig_fd = orig;
7536 sq[i].moved_to = moved;
7537 sq[i+1].orig_fd = -1; /* end marker */
7538 return sq;
7539}
7540
Denys Vlasenko2db74612017-07-07 22:07:28 +02007541static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7542{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007543 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007544 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007545
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007546 i = 0;
7547 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007548 /* If we collide with an already moved fd... */
7549 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007550 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007551 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7552 if (sq[i].moved_to < 0) /* what? */
7553 xfunc_die();
7554 return sq;
7555 }
7556 if (fd == sq[i].orig_fd) {
7557 /* Example: echo Hello >/dev/null 1>&2 */
7558 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7559 return sq;
7560 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007561 }
7562
Denys Vlasenko2db74612017-07-07 22:07:28 +02007563 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007564 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007565 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7566 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007567 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007568 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007569}
7570
Denys Vlasenko657e9002017-07-30 23:34:04 +02007571static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7572{
7573 int i;
7574
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007575 i = 0;
7576 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007577 /* If we collide with an already moved fd... */
7578 if (fd == sq[i].orig_fd) {
7579 /* Examples:
7580 * "echo 3>FILE 3>&- 3>FILE"
7581 * "echo 3>&- 3>FILE"
7582 * No need for last redirect to insert
7583 * another "need to close 3" indicator.
7584 */
7585 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7586 return sq;
7587 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007588 }
7589
7590 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7591 return append_squirrel(sq, i, fd, -1);
7592}
7593
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007594/* fd: redirect wants this fd to be used (e.g. 3>file).
7595 * Move all conflicting internally used fds,
7596 * and remember them so that we can restore them later.
7597 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007598static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007599{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007600 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7601 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007602
7603#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007604 if (fd == G.interactive_fd) {
7605 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007606 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007607 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7608 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007609 }
7610#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007611 /* Are we called from setup_redirects(squirrel==NULL)
7612 * in redirect in a [v]forked child?
7613 */
7614 if (sqp == NULL) {
7615 /* No need to move script fds.
7616 * For NOMMU case, it's actively wrong: we'd change ->fd
7617 * fields in memory for the parent, but parent's fds
7618 * aren't be moved, it would use wrong fd!
7619 * Reproducer: "cmd 3>FILE" in script.
7620 * If we would call move_HFILEs_on_redirect(), child would:
7621 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7622 * close(3) = 0
7623 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7624 */
7625 //bb_error_msg("sqp == NULL: [v]forked child");
7626 return 0;
7627 }
7628
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007629 /* If this one of script's fds? */
7630 if (move_HFILEs_on_redirect(fd, avoid_fd))
7631 return 1; /* yes. "we closed fd" (actually moved it) */
7632
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007633 /* Are we called for "exec 3>FILE"? Came through
7634 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7635 * This case used to fail for this script:
7636 * exec 3>FILE
7637 * echo Ok
7638 * ...100000 more lines...
7639 * echo Ok
7640 * as follows:
7641 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7642 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7643 * dup2(4, 3) = 3
7644 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7645 * close(4) = 0
7646 * write(1, "Ok\n", 3) = 3
7647 * ... = 3
7648 * write(1, "Ok\n", 3) = 3
7649 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7650 * ^^^^^^^^ oops, wrong fd!!!
7651 * With this case separate from sqp == NULL and *after* move_HFILEs,
7652 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007653 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007654 if (sqp == ERR_PTR) {
7655 /* Don't preserve redirected fds: exec is _meant_ to change these */
7656 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007657 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007658 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007659
Denys Vlasenko2db74612017-07-07 22:07:28 +02007660 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7661 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7662 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007663}
7664
Denys Vlasenko2db74612017-07-07 22:07:28 +02007665static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007666{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007667 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007668 int i;
7669 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007670 if (sq[i].moved_to >= 0) {
7671 /* We simply die on error */
7672 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7673 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7674 } else {
7675 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7676 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7677 close(sq[i].orig_fd);
7678 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007679 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007680 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007681 }
7682
Denys Vlasenko2db74612017-07-07 22:07:28 +02007683 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007684}
7685
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007686#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007687static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007688{
7689 if (G_interactive_fd)
7690 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007691 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007692}
7693#endif
7694
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007695static int internally_opened_fd(int fd, struct squirrel *sq)
7696{
7697 int i;
7698
7699#if ENABLE_HUSH_INTERACTIVE
7700 if (fd == G.interactive_fd)
7701 return 1;
7702#endif
7703 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007704 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007705 return 1;
7706
7707 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7708 if (fd == sq[i].moved_to)
7709 return 1;
7710 }
7711 return 0;
7712}
7713
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007714/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7715 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007716static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007717{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007718 struct redir_struct *redir;
7719
7720 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007721 int newfd;
7722 int closed;
7723
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007724 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007725 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007726 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007727 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7728 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007729 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007730 redir->rd_filename);
7731 setup_heredoc(redir);
7732 continue;
7733 }
7734
7735 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007736 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007737 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007738 int mode;
7739
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007740 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007741 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007742 * "cmd >" (no filename)
7743 * "cmd > <file" (2nd redirect starts too early)
7744 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007745 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007746 continue;
7747 }
7748 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007749 p = expand_string_to_string(redir->rd_filename,
7750 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007751 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007752 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007753 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007754 /* Error message from open_or_warn can be lost
7755 * if stderr has been redirected, but bash
7756 * and ash both lose it as well
7757 * (though zsh doesn't!)
7758 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007759 return 1;
7760 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007761 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007762 /* open() gave us precisely the fd we wanted.
7763 * This means that this fd was not busy
7764 * (not opened to anywhere).
7765 * Remember to close it on restore:
7766 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007767 *sqp = add_squirrel_closed(*sqp, newfd);
7768 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007769 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007770 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007771 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7772 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007773 }
7774
Denys Vlasenko657e9002017-07-30 23:34:04 +02007775 if (newfd == redir->rd_fd)
7776 continue;
7777
7778 /* if "N>FILE": move newfd to redir->rd_fd */
7779 /* if "N>&M": dup newfd to redir->rd_fd */
7780 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7781
7782 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7783 if (newfd == REDIRFD_CLOSE) {
7784 /* "N>&-" means "close me" */
7785 if (!closed) {
7786 /* ^^^ optimization: saving may already
7787 * have closed it. If not... */
7788 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007789 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007790 /* Sometimes we do another close on restore, getting EBADF.
7791 * Consider "echo 3>FILE 3>&-"
7792 * first redirect remembers "need to close 3",
7793 * and second redirect closes 3! Restore code then closes 3 again.
7794 */
7795 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007796 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007797 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007798 //errno = EBADF;
7799 //bb_perror_msg_and_die("can't duplicate file descriptor");
7800 newfd = -1; /* same effect as code above */
7801 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007802 xdup2(newfd, redir->rd_fd);
7803 if (redir->rd_dup == REDIRFD_TO_FILE)
7804 /* "rd_fd > FILE" */
7805 close(newfd);
7806 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007807 }
7808 }
7809 return 0;
7810}
7811
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007812static char *find_in_path(const char *arg)
7813{
7814 char *ret = NULL;
7815 const char *PATH = get_local_var_value("PATH");
7816
7817 if (!PATH)
7818 return NULL;
7819
7820 while (1) {
7821 const char *end = strchrnul(PATH, ':');
7822 int sz = end - PATH; /* must be int! */
7823
7824 free(ret);
7825 if (sz != 0) {
7826 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7827 } else {
7828 /* We have xxx::yyyy in $PATH,
7829 * it means "use current dir" */
7830 ret = xstrdup(arg);
7831 }
7832 if (access(ret, F_OK) == 0)
7833 break;
7834
7835 if (*end == '\0') {
7836 free(ret);
7837 return NULL;
7838 }
7839 PATH = end + 1;
7840 }
7841
7842 return ret;
7843}
7844
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007845static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007846 const struct built_in_command *x,
7847 const struct built_in_command *end)
7848{
7849 while (x != end) {
7850 if (strcmp(name, x->b_cmd) != 0) {
7851 x++;
7852 continue;
7853 }
7854 debug_printf_exec("found builtin '%s'\n", name);
7855 return x;
7856 }
7857 return NULL;
7858}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007859static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007860{
7861 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7862}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007863static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007864{
7865 const struct built_in_command *x = find_builtin1(name);
7866 if (x)
7867 return x;
7868 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7869}
7870
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007871static void remove_nested_vars(void)
7872{
7873 struct variable *cur;
7874 struct variable **cur_pp;
7875
7876 cur_pp = &G.top_var;
7877 while ((cur = *cur_pp) != NULL) {
7878 if (cur->var_nest_level <= G.var_nest_level) {
7879 cur_pp = &cur->next;
7880 continue;
7881 }
7882 /* Unexport */
7883 if (cur->flg_export) {
7884 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7885 bb_unsetenv(cur->varstr);
7886 }
7887 /* Remove from global list */
7888 *cur_pp = cur->next;
7889 /* Free */
7890 if (!cur->max_len) {
7891 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7892 free(cur->varstr);
7893 }
7894 free(cur);
7895 }
7896}
7897
7898static void enter_var_nest_level(void)
7899{
7900 G.var_nest_level++;
7901 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7902
7903 /* Try: f() { echo -n .; f; }; f
7904 * struct variable::var_nest_level is uint16_t,
7905 * thus limiting recursion to < 2^16.
7906 * In any case, with 8 Mbyte stack SEGV happens
7907 * not too long after 2^16 recursions anyway.
7908 */
7909 if (G.var_nest_level > 0xff00)
7910 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7911}
7912
7913static void leave_var_nest_level(void)
7914{
7915 G.var_nest_level--;
7916 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7917 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7918 bb_error_msg_and_die("BUG: nesting underflow");
7919
7920 remove_nested_vars();
7921}
7922
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007923#if ENABLE_HUSH_FUNCTIONS
7924static struct function **find_function_slot(const char *name)
7925{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007926 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007927 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007928
7929 while ((funcp = *funcpp) != NULL) {
7930 if (strcmp(name, funcp->name) == 0) {
7931 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007932 break;
7933 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007934 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007935 }
7936 return funcpp;
7937}
7938
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007939static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007940{
7941 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007942 return funcp;
7943}
7944
7945/* Note: takes ownership on name ptr */
7946static struct function *new_function(char *name)
7947{
7948 struct function **funcpp = find_function_slot(name);
7949 struct function *funcp = *funcpp;
7950
7951 if (funcp != NULL) {
7952 struct command *cmd = funcp->parent_cmd;
7953 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7954 if (!cmd) {
7955 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7956 free(funcp->name);
7957 /* Note: if !funcp->body, do not free body_as_string!
7958 * This is a special case of "-F name body" function:
7959 * body_as_string was not malloced! */
7960 if (funcp->body) {
7961 free_pipe_list(funcp->body);
7962# if !BB_MMU
7963 free(funcp->body_as_string);
7964# endif
7965 }
7966 } else {
7967 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7968 cmd->argv[0] = funcp->name;
7969 cmd->group = funcp->body;
7970# if !BB_MMU
7971 cmd->group_as_string = funcp->body_as_string;
7972# endif
7973 }
7974 } else {
7975 debug_printf_exec("remembering new function '%s'\n", name);
7976 funcp = *funcpp = xzalloc(sizeof(*funcp));
7977 /*funcp->next = NULL;*/
7978 }
7979
7980 funcp->name = name;
7981 return funcp;
7982}
7983
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007984# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007985static void unset_func(const char *name)
7986{
7987 struct function **funcpp = find_function_slot(name);
7988 struct function *funcp = *funcpp;
7989
7990 if (funcp != NULL) {
7991 debug_printf_exec("freeing function '%s'\n", funcp->name);
7992 *funcpp = funcp->next;
7993 /* funcp is unlinked now, deleting it.
7994 * Note: if !funcp->body, the function was created by
7995 * "-F name body", do not free ->body_as_string
7996 * and ->name as they were not malloced. */
7997 if (funcp->body) {
7998 free_pipe_list(funcp->body);
7999 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008000# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008001 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008002# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008003 }
8004 free(funcp);
8005 }
8006}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008007# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008008
8009# if BB_MMU
8010#define exec_function(to_free, funcp, argv) \
8011 exec_function(funcp, argv)
8012# endif
8013static void exec_function(char ***to_free,
8014 const struct function *funcp,
8015 char **argv) NORETURN;
8016static void exec_function(char ***to_free,
8017 const struct function *funcp,
8018 char **argv)
8019{
8020# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008021 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008022
8023 argv[0] = G.global_argv[0];
8024 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008025 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008026
8027// Example when we are here: "cmd | func"
8028// func will run with saved-redirect fds open.
8029// $ f() { echo /proc/self/fd/*; }
8030// $ true | f
8031// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8032// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8033// Same in script:
8034// $ . ./SCRIPT
8035// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8036// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8037// They are CLOEXEC so external programs won't see them, but
8038// for "more correctness" we might want to close those extra fds here:
8039//? close_saved_fds_and_FILE_fds();
8040
Denys Vlasenko332e4112018-04-04 22:32:59 +02008041 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008042 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008043 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008044 IF_HUSH_LOCAL(G.func_nest_level++;)
8045
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008046 /* On MMU, funcp->body is always non-NULL */
8047 n = run_list(funcp->body);
8048 fflush_all();
8049 _exit(n);
8050# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008051//? close_saved_fds_and_FILE_fds();
8052
8053//TODO: check whether "true | func_with_return" works
8054
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008055 re_execute_shell(to_free,
8056 funcp->body_as_string,
8057 G.global_argv[0],
8058 argv + 1,
8059 NULL);
8060# endif
8061}
8062
8063static int run_function(const struct function *funcp, char **argv)
8064{
8065 int rc;
8066 save_arg_t sv;
8067 smallint sv_flg;
8068
8069 save_and_replace_G_args(&sv, argv);
8070
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008071 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008072 sv_flg = G_flag_return_in_progress;
8073 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008074
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008075 /* Make "local" variables properly shadow previous ones */
8076 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008077 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008078
8079 /* On MMU, funcp->body is always non-NULL */
8080# if !BB_MMU
8081 if (!funcp->body) {
8082 /* Function defined by -F */
8083 parse_and_run_string(funcp->body_as_string);
8084 rc = G.last_exitcode;
8085 } else
8086# endif
8087 {
8088 rc = run_list(funcp->body);
8089 }
8090
Denys Vlasenko332e4112018-04-04 22:32:59 +02008091 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008092 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008093
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008094 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008095
8096 restore_G_args(&sv, argv);
8097
8098 return rc;
8099}
8100#endif /* ENABLE_HUSH_FUNCTIONS */
8101
8102
8103#if BB_MMU
8104#define exec_builtin(to_free, x, argv) \
8105 exec_builtin(x, argv)
8106#else
8107#define exec_builtin(to_free, x, argv) \
8108 exec_builtin(to_free, argv)
8109#endif
8110static void exec_builtin(char ***to_free,
8111 const struct built_in_command *x,
8112 char **argv) NORETURN;
8113static void exec_builtin(char ***to_free,
8114 const struct built_in_command *x,
8115 char **argv)
8116{
8117#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008118 int rcode;
8119 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008120//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008121 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008122 fflush_all();
8123 _exit(rcode);
8124#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008125 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008126 /* On NOMMU, we must never block!
8127 * Example: { sleep 99 | read line; } & echo Ok
8128 */
8129 re_execute_shell(to_free,
8130 argv[0],
8131 G.global_argv[0],
8132 G.global_argv + 1,
8133 argv);
8134#endif
8135}
8136
8137
8138static void execvp_or_die(char **argv) NORETURN;
8139static void execvp_or_die(char **argv)
8140{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008141 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008142 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008143 /* Don't propagate SIG_IGN to the child */
8144 if (SPECIAL_JOBSTOP_SIGS != 0)
8145 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008146 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008147 e = 2;
8148 if (errno == EACCES) e = 126;
8149 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008150 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008151 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008152}
8153
8154#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008155static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008156{
8157 unsigned len;
8158 const char *cp;
8159
8160 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008161
8162 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8163 /* test a char with: bash -c 'set -x; echo "CH"' */
8164 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8165 " " "\001\002\003\004\005\006\007"
8166 "\010\011\012\013\014\015\016\017"
8167 "\020\021\022\023\024\025\026\027"
8168 "\030\031\032\033\034\035\036\037"
8169 )
8170 ] == '\0'
8171 ) {
8172 /* string has no special chars */
8173 x_mode_addstr(str);
8174 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008175 }
8176
8177 cp = str;
8178 for (;;) {
8179 /* print '....' up to EOL or first squote */
8180 len = (int)(strchrnul(cp, '\'') - cp);
8181 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008182 x_mode_addchr('\'');
8183 x_mode_addblock(cp, len);
8184 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008185 cp += len;
8186 }
8187 if (*cp == '\0')
8188 break;
8189 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008190 x_mode_addchr('\\');
8191 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008192 cp++;
8193 }
8194}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008195static void dump_cmd_in_x_mode(char **argv)
8196{
8197 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008198 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008199
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008200 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008201 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008202 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008203 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008204 x_mode_addchr(' ');
8205 if (argv[n][0] == '\0') {
8206 x_mode_addchr('\'');
8207 x_mode_addchr('\'');
8208 } else {
8209 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008210 }
8211 n++;
8212 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008213 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008214 }
8215}
8216#else
8217# define dump_cmd_in_x_mode(argv) ((void)0)
8218#endif
8219
Denys Vlasenko57000292018-01-12 14:41:45 +01008220#if ENABLE_HUSH_COMMAND
8221static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8222{
8223 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008224
Denys Vlasenko57000292018-01-12 14:41:45 +01008225 if (!opt_vV)
8226 return;
8227
8228 to_free = NULL;
8229 if (!explanation) {
8230 char *path = getenv("PATH");
8231 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008232 if (!explanation)
8233 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008234 if (opt_vV != 'V')
8235 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8236 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008237 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008238 free(to_free);
8239 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008240 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008241}
8242#else
8243# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8244#endif
8245
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008246#if BB_MMU
8247#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8248 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8249#define pseudo_exec(nommu_save, command, argv_expanded) \
8250 pseudo_exec(command, argv_expanded)
8251#endif
8252
8253/* Called after [v]fork() in run_pipe, or from builtin_exec.
8254 * Never returns.
8255 * Don't exit() here. If you don't exec, use _exit instead.
8256 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008257 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008258 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008259static void pseudo_exec_argv(nommu_save_t *nommu_save,
8260 char **argv, int assignment_cnt,
8261 char **argv_expanded) NORETURN;
8262static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8263 char **argv, int assignment_cnt,
8264 char **argv_expanded)
8265{
Denys Vlasenko57000292018-01-12 14:41:45 +01008266 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008267 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008268 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008269 IF_HUSH_COMMAND(char opt_vV = 0;)
8270 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008271
8272 new_env = expand_assignments(argv, assignment_cnt);
8273 dump_cmd_in_x_mode(new_env);
8274
8275 if (!argv[assignment_cnt]) {
8276 /* Case when we are here: ... | var=val | ...
8277 * (note that we do not exit early, i.e., do not optimize out
8278 * expand_assignments(): think about ... | var=`sleep 1` | ...
8279 */
8280 free_strings(new_env);
8281 _exit(EXIT_SUCCESS);
8282 }
8283
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008284 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008285#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008286 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008287#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008288 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008289 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008290#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008291 set_vars_and_save_old(new_env);
8292 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008293
8294 if (argv_expanded) {
8295 argv = argv_expanded;
8296 } else {
8297 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8298#if !BB_MMU
8299 nommu_save->argv = argv;
8300#endif
8301 }
8302 dump_cmd_in_x_mode(argv);
8303
8304#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8305 if (strchr(argv[0], '/') != NULL)
8306 goto skip;
8307#endif
8308
Denys Vlasenko75481d32017-07-31 05:27:09 +02008309#if ENABLE_HUSH_FUNCTIONS
8310 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008311 funcp = find_function(argv[0]);
8312 if (funcp)
8313 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008314#endif
8315
Denys Vlasenko57000292018-01-12 14:41:45 +01008316#if ENABLE_HUSH_COMMAND
8317 /* "command BAR": run BAR without looking it up among functions
8318 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8319 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8320 */
8321 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8322 char *p;
8323
8324 argv++;
8325 p = *argv;
8326 if (p[0] != '-' || !p[1])
8327 continue; /* bash allows "command command command [-OPT] BAR" */
8328
8329 for (;;) {
8330 p++;
8331 switch (*p) {
8332 case '\0':
8333 argv++;
8334 p = *argv;
8335 if (p[0] != '-' || !p[1])
8336 goto after_opts;
8337 continue; /* next arg is also -opts, process it too */
8338 case 'v':
8339 case 'V':
8340 opt_vV = *p;
8341 continue;
8342 default:
8343 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8344 }
8345 }
8346 }
8347 after_opts:
8348# if ENABLE_HUSH_FUNCTIONS
8349 if (opt_vV && find_function(argv[0]))
8350 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8351# endif
8352#endif
8353
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008354 /* Check if the command matches any of the builtins.
8355 * Depending on context, this might be redundant. But it's
8356 * easier to waste a few CPU cycles than it is to figure out
8357 * if this is one of those cases.
8358 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008359 /* Why "BB_MMU ? :" difference in logic? -
8360 * On NOMMU, it is more expensive to re-execute shell
8361 * just in order to run echo or test builtin.
8362 * It's better to skip it here and run corresponding
8363 * non-builtin later. */
8364 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8365 if (x) {
8366 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8367 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008368 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008369
8370#if ENABLE_FEATURE_SH_STANDALONE
8371 /* Check if the command matches any busybox applets */
8372 {
8373 int a = find_applet_by_name(argv[0]);
8374 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008375 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008376# if BB_MMU /* see above why on NOMMU it is not allowed */
8377 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008378 /* Do not leak open fds from opened script files etc.
8379 * Testcase: interactive "ls -l /proc/self/fd"
8380 * should not show tty fd open.
8381 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008382 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008383//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008384//This casuses test failures in
8385//redir_children_should_not_see_saved_fd_2.tests
8386//redir_children_should_not_see_saved_fd_3.tests
8387//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008388 /* Without this, "rm -i FILE" can't be ^C'ed: */
8389 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008390 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008391 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008392 }
8393# endif
8394 /* Re-exec ourselves */
8395 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008396 /* Don't propagate SIG_IGN to the child */
8397 if (SPECIAL_JOBSTOP_SIGS != 0)
8398 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008399 execv(bb_busybox_exec_path, argv);
8400 /* If they called chroot or otherwise made the binary no longer
8401 * executable, fall through */
8402 }
8403 }
8404#endif
8405
8406#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8407 skip:
8408#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008409 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008410 execvp_or_die(argv);
8411}
8412
8413/* Called after [v]fork() in run_pipe
8414 */
8415static void pseudo_exec(nommu_save_t *nommu_save,
8416 struct command *command,
8417 char **argv_expanded) NORETURN;
8418static void pseudo_exec(nommu_save_t *nommu_save,
8419 struct command *command,
8420 char **argv_expanded)
8421{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008422#if ENABLE_HUSH_FUNCTIONS
8423 if (command->cmd_type == CMD_FUNCDEF) {
8424 /* Ignore funcdefs in pipes:
8425 * true | f() { cmd }
8426 */
8427 _exit(0);
8428 }
8429#endif
8430
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008431 if (command->argv) {
8432 pseudo_exec_argv(nommu_save, command->argv,
8433 command->assignment_cnt, argv_expanded);
8434 }
8435
8436 if (command->group) {
8437 /* Cases when we are here:
8438 * ( list )
8439 * { list } &
8440 * ... | ( list ) | ...
8441 * ... | { list } | ...
8442 */
8443#if BB_MMU
8444 int rcode;
8445 debug_printf_exec("pseudo_exec: run_list\n");
8446 reset_traps_to_defaults();
8447 rcode = run_list(command->group);
8448 /* OK to leak memory by not calling free_pipe_list,
8449 * since this process is about to exit */
8450 _exit(rcode);
8451#else
8452 re_execute_shell(&nommu_save->argv_from_re_execing,
8453 command->group_as_string,
8454 G.global_argv[0],
8455 G.global_argv + 1,
8456 NULL);
8457#endif
8458 }
8459
8460 /* Case when we are here: ... | >file */
8461 debug_printf_exec("pseudo_exec'ed null command\n");
8462 _exit(EXIT_SUCCESS);
8463}
8464
8465#if ENABLE_HUSH_JOB
8466static const char *get_cmdtext(struct pipe *pi)
8467{
8468 char **argv;
8469 char *p;
8470 int len;
8471
8472 /* This is subtle. ->cmdtext is created only on first backgrounding.
8473 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8474 * On subsequent bg argv is trashed, but we won't use it */
8475 if (pi->cmdtext)
8476 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008477
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008478 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008479 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008480 pi->cmdtext = xzalloc(1);
8481 return pi->cmdtext;
8482 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008483 len = 0;
8484 do {
8485 len += strlen(*argv) + 1;
8486 } while (*++argv);
8487 p = xmalloc(len);
8488 pi->cmdtext = p;
8489 argv = pi->cmds[0].argv;
8490 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008491 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008492 *p++ = ' ';
8493 } while (*++argv);
8494 p[-1] = '\0';
8495 return pi->cmdtext;
8496}
8497
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008498static void remove_job_from_table(struct pipe *pi)
8499{
8500 struct pipe *prev_pipe;
8501
8502 if (pi == G.job_list) {
8503 G.job_list = pi->next;
8504 } else {
8505 prev_pipe = G.job_list;
8506 while (prev_pipe->next != pi)
8507 prev_pipe = prev_pipe->next;
8508 prev_pipe->next = pi->next;
8509 }
8510 G.last_jobid = 0;
8511 if (G.job_list)
8512 G.last_jobid = G.job_list->jobid;
8513}
8514
8515static void delete_finished_job(struct pipe *pi)
8516{
8517 remove_job_from_table(pi);
8518 free_pipe(pi);
8519}
8520
8521static void clean_up_last_dead_job(void)
8522{
8523 if (G.job_list && !G.job_list->alive_cmds)
8524 delete_finished_job(G.job_list);
8525}
8526
Denys Vlasenko16096292017-07-10 10:00:28 +02008527static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008528{
8529 struct pipe *job, **jobp;
8530 int i;
8531
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008532 clean_up_last_dead_job();
8533
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008534 /* Find the end of the list, and find next job ID to use */
8535 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008536 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008537 while ((job = *jobp) != NULL) {
8538 if (job->jobid > i)
8539 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008540 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008541 }
8542 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008543
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008544 /* Create a new job struct at the end */
8545 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008546 job->next = NULL;
8547 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8548 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8549 for (i = 0; i < pi->num_cmds; i++) {
8550 job->cmds[i].pid = pi->cmds[i].pid;
8551 /* all other fields are not used and stay zero */
8552 }
8553 job->cmdtext = xstrdup(get_cmdtext(pi));
8554
8555 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008556 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008557 G.last_jobid = job->jobid;
8558}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008559#endif /* JOB */
8560
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008561static int job_exited_or_stopped(struct pipe *pi)
8562{
8563 int rcode, i;
8564
8565 if (pi->alive_cmds != pi->stopped_cmds)
8566 return -1;
8567
8568 /* All processes in fg pipe have exited or stopped */
8569 rcode = 0;
8570 i = pi->num_cmds;
8571 while (--i >= 0) {
8572 rcode = pi->cmds[i].cmd_exitcode;
8573 /* usually last process gives overall exitstatus,
8574 * but with "set -o pipefail", last *failed* process does */
8575 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8576 break;
8577 }
8578 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8579 return rcode;
8580}
8581
Denys Vlasenko7e675362016-10-28 21:57:31 +02008582static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008583{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008584#if ENABLE_HUSH_JOB
8585 struct pipe *pi;
8586#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008587 int i, dead;
8588
8589 dead = WIFEXITED(status) || WIFSIGNALED(status);
8590
8591#if DEBUG_JOBS
8592 if (WIFSTOPPED(status))
8593 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8594 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8595 if (WIFSIGNALED(status))
8596 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8597 childpid, WTERMSIG(status), WEXITSTATUS(status));
8598 if (WIFEXITED(status))
8599 debug_printf_jobs("pid %d exited, exitcode %d\n",
8600 childpid, WEXITSTATUS(status));
8601#endif
8602 /* Were we asked to wait for a fg pipe? */
8603 if (fg_pipe) {
8604 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008605
Denys Vlasenko7e675362016-10-28 21:57:31 +02008606 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008607 int rcode;
8608
Denys Vlasenko7e675362016-10-28 21:57:31 +02008609 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8610 if (fg_pipe->cmds[i].pid != childpid)
8611 continue;
8612 if (dead) {
8613 int ex;
8614 fg_pipe->cmds[i].pid = 0;
8615 fg_pipe->alive_cmds--;
8616 ex = WEXITSTATUS(status);
8617 /* bash prints killer signal's name for *last*
8618 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8619 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8620 */
8621 if (WIFSIGNALED(status)) {
8622 int sig = WTERMSIG(status);
8623 if (i == fg_pipe->num_cmds-1)
8624 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8625 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8626 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8627 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8628 * Maybe we need to use sig | 128? */
8629 ex = sig + 128;
8630 }
8631 fg_pipe->cmds[i].cmd_exitcode = ex;
8632 } else {
8633 fg_pipe->stopped_cmds++;
8634 }
8635 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8636 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008637 rcode = job_exited_or_stopped(fg_pipe);
8638 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008639/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8640 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8641 * and "killall -STOP cat" */
8642 if (G_interactive_fd) {
8643#if ENABLE_HUSH_JOB
8644 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008645 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008646#endif
8647 return rcode;
8648 }
8649 if (fg_pipe->alive_cmds == 0)
8650 return rcode;
8651 }
8652 /* There are still running processes in the fg_pipe */
8653 return -1;
8654 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008655 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008656 }
8657
8658#if ENABLE_HUSH_JOB
8659 /* We were asked to wait for bg or orphaned children */
8660 /* No need to remember exitcode in this case */
8661 for (pi = G.job_list; pi; pi = pi->next) {
8662 for (i = 0; i < pi->num_cmds; i++) {
8663 if (pi->cmds[i].pid == childpid)
8664 goto found_pi_and_prognum;
8665 }
8666 }
8667 /* Happens when shell is used as init process (init=/bin/sh) */
8668 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8669 return -1; /* this wasn't a process from fg_pipe */
8670
8671 found_pi_and_prognum:
8672 if (dead) {
8673 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008674 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008675 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008676 rcode = 128 + WTERMSIG(status);
8677 pi->cmds[i].cmd_exitcode = rcode;
8678 if (G.last_bg_pid == pi->cmds[i].pid)
8679 G.last_bg_pid_exitcode = rcode;
8680 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008681 pi->alive_cmds--;
8682 if (!pi->alive_cmds) {
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008683#if ENABLE_HUSH_BASH_COMPAT
8684 G.dead_job_exitcode = job_exited_or_stopped(pi);
8685#endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008686 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008687 printf(JOB_STATUS_FORMAT, pi->jobid,
8688 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008689 delete_finished_job(pi);
8690 } else {
8691/*
8692 * bash deletes finished jobs from job table only in interactive mode,
8693 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8694 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8695 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8696 * We only retain one "dead" job, if it's the single job on the list.
8697 * This covers most of real-world scenarios where this is useful.
8698 */
8699 if (pi != G.job_list)
8700 delete_finished_job(pi);
8701 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008702 }
8703 } else {
8704 /* child stopped */
8705 pi->stopped_cmds++;
8706 }
8707#endif
8708 return -1; /* this wasn't a process from fg_pipe */
8709}
8710
8711/* Check to see if any processes have exited -- if they have,
8712 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008713 *
8714 * If non-NULL fg_pipe: wait for its completion or stop.
8715 * Return its exitcode or zero if stopped.
8716 *
8717 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8718 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8719 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8720 * or 0 if no children changed status.
8721 *
8722 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8723 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8724 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008725 */
8726static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8727{
8728 int attributes;
8729 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008730 int rcode = 0;
8731
8732 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8733
8734 attributes = WUNTRACED;
8735 if (fg_pipe == NULL)
8736 attributes |= WNOHANG;
8737
8738 errno = 0;
8739#if ENABLE_HUSH_FAST
8740 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8741//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8742//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8743 /* There was neither fork nor SIGCHLD since last waitpid */
8744 /* Avoid doing waitpid syscall if possible */
8745 if (!G.we_have_children) {
8746 errno = ECHILD;
8747 return -1;
8748 }
8749 if (fg_pipe == NULL) { /* is WNOHANG set? */
8750 /* We have children, but they did not exit
8751 * or stop yet (we saw no SIGCHLD) */
8752 return 0;
8753 }
8754 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8755 }
8756#endif
8757
8758/* Do we do this right?
8759 * bash-3.00# sleep 20 | false
8760 * <ctrl-Z pressed>
8761 * [3]+ Stopped sleep 20 | false
8762 * bash-3.00# echo $?
8763 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8764 * [hush 1.14.0: yes we do it right]
8765 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008766 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008767 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008768#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008769 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008770 i = G.count_SIGCHLD;
8771#endif
8772 childpid = waitpid(-1, &status, attributes);
8773 if (childpid <= 0) {
8774 if (childpid && errno != ECHILD)
8775 bb_perror_msg("waitpid");
8776#if ENABLE_HUSH_FAST
8777 else { /* Until next SIGCHLD, waitpid's are useless */
8778 G.we_have_children = (childpid == 0);
8779 G.handled_SIGCHLD = i;
8780//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8781 }
8782#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008783 /* ECHILD (no children), or 0 (no change in children status) */
8784 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008785 break;
8786 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008787 rcode = process_wait_result(fg_pipe, childpid, status);
8788 if (rcode >= 0) {
8789 /* fg_pipe exited or stopped */
8790 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008791 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008792 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008793 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008794 rcode = WEXITSTATUS(status);
8795 if (WIFSIGNALED(status))
8796 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008797 if (WIFSTOPPED(status))
8798 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8799 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008800 rcode++;
8801 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008802 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008803#if ENABLE_HUSH_BASH_COMPAT
8804 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8805 && G.dead_job_exitcode >= 0 /* some job did finish */
8806 ) {
8807 debug_printf_exec("waitfor_pid:-1\n");
8808 rcode = G.dead_job_exitcode + 1;
8809 break;
8810 }
8811#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008812 /* This wasn't one of our processes, or */
8813 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008814 } /* while (waitpid succeeds)... */
8815
8816 return rcode;
8817}
8818
8819#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008820static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008821{
8822 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008823 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008824 if (G_saved_tty_pgrp) {
8825 /* Job finished, move the shell to the foreground */
8826 p = getpgrp(); /* our process group id */
8827 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8828 tcsetpgrp(G_interactive_fd, p);
8829 }
8830 return rcode;
8831}
8832#endif
8833
8834/* Start all the jobs, but don't wait for anything to finish.
8835 * See checkjobs().
8836 *
8837 * Return code is normally -1, when the caller has to wait for children
8838 * to finish to determine the exit status of the pipe. If the pipe
8839 * is a simple builtin command, however, the action is done by the
8840 * time run_pipe returns, and the exit code is provided as the
8841 * return value.
8842 *
8843 * Returns -1 only if started some children. IOW: we have to
8844 * mask out retvals of builtins etc with 0xff!
8845 *
8846 * The only case when we do not need to [v]fork is when the pipe
8847 * is single, non-backgrounded, non-subshell command. Examples:
8848 * cmd ; ... { list } ; ...
8849 * cmd && ... { list } && ...
8850 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008851 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008852 * or (if SH_STANDALONE) an applet, and we can run the { list }
8853 * with run_list. If it isn't one of these, we fork and exec cmd.
8854 *
8855 * Cases when we must fork:
8856 * non-single: cmd | cmd
8857 * backgrounded: cmd & { list } &
8858 * subshell: ( list ) [&]
8859 */
8860#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008861#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8862 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008863#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008864static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008865 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008866 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008867 char **argv_expanded)
8868{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008869 /* Assignments occur before redirects. Try:
8870 * a=`sleep 1` sleep 2 3>/qwe/rty
8871 */
8872
8873 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8874 dump_cmd_in_x_mode(new_env);
8875 dump_cmd_in_x_mode(argv_expanded);
8876 /* this takes ownership of new_env[i] elements, and frees new_env: */
8877 set_vars_and_save_old(new_env);
8878
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008879 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008880}
8881static NOINLINE int run_pipe(struct pipe *pi)
8882{
8883 static const char *const null_ptr = NULL;
8884
8885 int cmd_no;
8886 int next_infd;
8887 struct command *command;
8888 char **argv_expanded;
8889 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008890 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008891 int rcode;
8892
8893 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8894 debug_enter();
8895
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008896 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8897 * Result should be 3 lines: q w e, qwe, q w e
8898 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008899 if (G.ifs_whitespace != G.ifs)
8900 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008901 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008902 if (G.ifs) {
8903 char *p;
8904 G.ifs_whitespace = (char*)G.ifs;
8905 p = skip_whitespace(G.ifs);
8906 if (*p) {
8907 /* Not all $IFS is whitespace */
8908 char *d;
8909 int len = p - G.ifs;
8910 p = skip_non_whitespace(p);
8911 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8912 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8913 while (*p) {
8914 if (isspace(*p))
8915 *d++ = *p;
8916 p++;
8917 }
8918 *d = '\0';
8919 }
8920 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008921 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008922 G.ifs_whitespace = (char*)G.ifs;
8923 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008924
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008925 IF_HUSH_JOB(pi->pgrp = -1;)
8926 pi->stopped_cmds = 0;
8927 command = &pi->cmds[0];
8928 argv_expanded = NULL;
8929
8930 if (pi->num_cmds != 1
8931 || pi->followup == PIPE_BG
8932 || command->cmd_type == CMD_SUBSHELL
8933 ) {
8934 goto must_fork;
8935 }
8936
8937 pi->alive_cmds = 1;
8938
8939 debug_printf_exec(": group:%p argv:'%s'\n",
8940 command->group, command->argv ? command->argv[0] : "NONE");
8941
8942 if (command->group) {
8943#if ENABLE_HUSH_FUNCTIONS
8944 if (command->cmd_type == CMD_FUNCDEF) {
8945 /* "executing" func () { list } */
8946 struct function *funcp;
8947
8948 funcp = new_function(command->argv[0]);
8949 /* funcp->name is already set to argv[0] */
8950 funcp->body = command->group;
8951# if !BB_MMU
8952 funcp->body_as_string = command->group_as_string;
8953 command->group_as_string = NULL;
8954# endif
8955 command->group = NULL;
8956 command->argv[0] = NULL;
8957 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8958 funcp->parent_cmd = command;
8959 command->child_func = funcp;
8960
8961 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8962 debug_leave();
8963 return EXIT_SUCCESS;
8964 }
8965#endif
8966 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008967 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008968 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008969 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008970 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008971//FIXME: we need to pass squirrel down into run_list()
8972//for SH_STANDALONE case, or else this construct:
8973// { find /proc/self/fd; true; } >FILE; cmd2
8974//has no way of closing saved fd#1 for "find",
8975//and in SH_STANDALONE mode, "find" is not execed,
8976//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008977 rcode = run_list(command->group) & 0xff;
8978 }
8979 restore_redirects(squirrel);
8980 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8981 debug_leave();
8982 debug_printf_exec("run_pipe: return %d\n", rcode);
8983 return rcode;
8984 }
8985
8986 argv = command->argv ? command->argv : (char **) &null_ptr;
8987 {
8988 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008989 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8990 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008991 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008992 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008993
Denys Vlasenko5807e182018-02-08 19:19:04 +01008994#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008995 if (G.lineno_var)
8996 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8997#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008998
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008999 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009000 /* Assignments, but no command.
9001 * Ensure redirects take effect (that is, create files).
9002 * Try "a=t >file"
9003 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009004 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009005 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009006 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009007 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009008 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009009
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009010 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009011 i = 0;
9012 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009013 char *p = expand_string_to_string(argv[i],
9014 EXP_FLAG_ESC_GLOB_CHARS,
9015 /*unbackslash:*/ 1
9016 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009017#if ENABLE_HUSH_MODE_X
9018 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009019 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009020 if (i == 0)
9021 x_mode_prefix();
9022 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009023 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009024 if (*eq) eq++;
9025 x_mode_addblock(p, (eq - p));
9026 x_mode_print_optionally_squoted(eq);
9027 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009028 }
9029#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009030 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009031 if (set_local_var(p, /*flag:*/ 0)) {
9032 /* assignment to readonly var / putenv error? */
9033 rcode = 1;
9034 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009035 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009036 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009037 /* Redirect error sets $? to 1. Otherwise,
9038 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009039 * Else, clear $?:
9040 * false; q=`exit 2`; echo $? - should print 2
9041 * false; x=1; echo $? - should print 0
9042 * Because of the 2nd case, we can't just use G.last_exitcode.
9043 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009044 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009045 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009046 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9047 debug_leave();
9048 debug_printf_exec("run_pipe: return %d\n", rcode);
9049 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009050 }
9051
9052 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02009053#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009054 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009055 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009056 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009057#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009058 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009059
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009060 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009061 if (!argv_expanded[0]) {
9062 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009063 /* `false` still has to set exitcode 1 */
9064 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009065 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009066 }
9067
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009068 old_vars = NULL;
9069 sv_shadowed = G.shadowed_vars_pp;
9070
Denys Vlasenko75481d32017-07-31 05:27:09 +02009071 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009072 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9073 IF_HUSH_FUNCTIONS(x = NULL;)
9074 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009075 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009076 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009077 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9078 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009079 /*
9080 * Variable assignments are executed, but then "forgotten":
9081 * a=`sleep 1;echo A` exec 3>&-; echo $a
9082 * sleeps, but prints nothing.
9083 */
9084 enter_var_nest_level();
9085 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009086 rcode = redirect_and_varexp_helper(command,
9087 /*squirrel:*/ ERR_PTR,
9088 argv_expanded
9089 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009090 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009091 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009092
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009093 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009094 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009095
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009096 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009097 * a=b true; env | grep ^a=
9098 */
9099 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009100 /* Collect all variables "shadowed" by helper
9101 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9102 * into old_vars list:
9103 */
9104 G.shadowed_vars_pp = &old_vars;
9105 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009106 if (rcode == 0) {
9107 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009108 /* Do not collect *to old_vars list* vars shadowed
9109 * by e.g. "local VAR" builtin (collect them
9110 * in the previously nested list instead):
9111 * don't want them to be restored immediately
9112 * after "local" completes.
9113 */
9114 G.shadowed_vars_pp = sv_shadowed;
9115
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009116 debug_printf_exec(": builtin '%s' '%s'...\n",
9117 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009118 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009119 rcode = x->b_function(argv_expanded) & 0xff;
9120 fflush_all();
9121 }
9122#if ENABLE_HUSH_FUNCTIONS
9123 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009124 debug_printf_exec(": function '%s' '%s'...\n",
9125 funcp->name, argv_expanded[1]);
9126 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009127 /*
9128 * But do collect *to old_vars list* vars shadowed
9129 * within function execution. To that end, restore
9130 * this pointer _after_ function run:
9131 */
9132 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009133 }
9134#endif
9135 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009136 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009137 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009138 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009139 if (n < 0 || !APPLET_IS_NOFORK(n))
9140 goto must_fork;
9141
9142 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009143 /* Collect all variables "shadowed" by helper into old_vars list */
9144 G.shadowed_vars_pp = &old_vars;
9145 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9146 G.shadowed_vars_pp = sv_shadowed;
9147
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009148 if (rcode == 0) {
9149 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9150 argv_expanded[0], argv_expanded[1]);
9151 /*
9152 * Note: signals (^C) can't interrupt here.
9153 * We remember them and they will be acted upon
9154 * after applet returns.
9155 * This makes applets which can run for a long time
9156 * and/or wait for user input ineligible for NOFORK:
9157 * for example, "yes" or "rm" (rm -i waits for input).
9158 */
9159 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009160 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009161 } else
9162 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009163
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009164 restore_redirects(squirrel);
9165 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009166 leave_var_nest_level();
9167 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009168
9169 /*
9170 * Try "usleep 99999999" + ^C + "echo $?"
9171 * with FEATURE_SH_NOFORK=y.
9172 */
9173 if (!funcp) {
9174 /* It was builtin or nofork.
9175 * if this would be a real fork/execed program,
9176 * it should have died if a fatal sig was received.
9177 * But OTOH, there was no separate process,
9178 * the sig was sent to _shell_, not to non-existing
9179 * child.
9180 * Let's just handle ^C only, this one is obvious:
9181 * we aren't ok with exitcode 0 when ^C was pressed
9182 * during builtin/nofork.
9183 */
9184 if (sigismember(&G.pending_set, SIGINT))
9185 rcode = 128 + SIGINT;
9186 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009187 free(argv_expanded);
9188 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9189 debug_leave();
9190 debug_printf_exec("run_pipe return %d\n", rcode);
9191 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009192 }
9193
9194 must_fork:
9195 /* NB: argv_expanded may already be created, and that
9196 * might include `cmd` runs! Do not rerun it! We *must*
9197 * use argv_expanded if it's non-NULL */
9198
9199 /* Going to fork a child per each pipe member */
9200 pi->alive_cmds = 0;
9201 next_infd = 0;
9202
9203 cmd_no = 0;
9204 while (cmd_no < pi->num_cmds) {
9205 struct fd_pair pipefds;
9206#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009207 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009208 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009209 nommu_save.old_vars = NULL;
9210 nommu_save.argv = NULL;
9211 nommu_save.argv_from_re_execing = NULL;
9212#endif
9213 command = &pi->cmds[cmd_no];
9214 cmd_no++;
9215 if (command->argv) {
9216 debug_printf_exec(": pipe member '%s' '%s'...\n",
9217 command->argv[0], command->argv[1]);
9218 } else {
9219 debug_printf_exec(": pipe member with no argv\n");
9220 }
9221
9222 /* pipes are inserted between pairs of commands */
9223 pipefds.rd = 0;
9224 pipefds.wr = 1;
9225 if (cmd_no < pi->num_cmds)
9226 xpiped_pair(pipefds);
9227
Denys Vlasenko5807e182018-02-08 19:19:04 +01009228#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009229 if (G.lineno_var)
9230 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9231#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
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009914#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9915 /* Set (but not export) PS1/2 unless already set */
9916 if (!get_local_var_value("PS1"))
9917 set_local_var_from_halves("PS1", "\\w \\$ ");
9918 if (!get_local_var_value("PS2"))
9919 set_local_var_from_halves("PS2", "> ");
9920#endif
9921
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009922#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009923 /* Set (but not export) HOSTNAME unless already set */
9924 if (!get_local_var_value("HOSTNAME")) {
9925 struct utsname uts;
9926 uname(&uts);
9927 set_local_var_from_halves("HOSTNAME", uts.nodename);
9928 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02009929#endif
9930 /* IFS is not inherited from the parent environment */
9931 set_local_var_from_halves("IFS", defifs);
9932
Denys Vlasenko6db47842009-09-05 20:15:17 +02009933 /* bash also exports SHLVL and _,
9934 * and sets (but doesn't export) the following variables:
9935 * BASH=/bin/bash
9936 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9937 * BASH_VERSION='3.2.0(1)-release'
9938 * HOSTTYPE=i386
9939 * MACHTYPE=i386-pc-linux-gnu
9940 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009941 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009942 * EUID=<NNNNN>
9943 * UID=<NNNNN>
9944 * GROUPS=()
9945 * LINES=<NNN>
9946 * COLUMNS=<NNN>
9947 * BASH_ARGC=()
9948 * BASH_ARGV=()
9949 * BASH_LINENO=()
9950 * BASH_SOURCE=()
9951 * DIRSTACK=()
9952 * PIPESTATUS=([0]="0")
9953 * HISTFILE=/<xxx>/.bash_history
9954 * HISTFILESIZE=500
9955 * HISTSIZE=500
9956 * MAILCHECK=60
9957 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9958 * SHELL=/bin/bash
9959 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9960 * TERM=dumb
9961 * OPTERR=1
9962 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +02009963 * PS4='+ '
9964 */
9965
Denys Vlasenko5807e182018-02-08 19:19:04 +01009966#if ENABLE_HUSH_LINENO_VAR
9967 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009968 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9969 set_local_var(p, /*flags*/ 0);
9970 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9971 }
9972#endif
9973
Denis Vlasenko38f63192007-01-22 09:03:07 +00009974#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009975 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009976#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009977
Eric Andersen94ac2442001-05-22 19:05:18 +00009978 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009979 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009980
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009981 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009982
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009983 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009984 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009985 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009986 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009987 * in order to intercept (more) signals.
9988 */
9989
9990 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009991 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009992 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009993 builtin_argc = 0;
Ron Yorston71df2d32018-11-27 14:34:25 +00009994#if NUM_SCRIPTS > 0
9995 if (argc < 0) {
9996 optarg = get_script_content(-argc - 1);
9997 optind = 0;
9998 argc = string_array_len(argv);
9999 goto run_script;
10000 }
10001#endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010002 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010003 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010004#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010005 "<:$:R:V:"
10006# if ENABLE_HUSH_FUNCTIONS
10007 "F:"
10008# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010009#endif
10010 );
10011 if (opt <= 0)
10012 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010013 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010014 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010015 /* Possibilities:
10016 * sh ... -c 'script'
10017 * sh ... -c 'script' ARG0 [ARG1...]
10018 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +010010019 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010020 * "" needs to be replaced with NULL
10021 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +010010022 * Note: the form without ARG0 never happens:
10023 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010024 */
Ron Yorston71df2d32018-11-27 14:34:25 +000010025#if NUM_SCRIPTS > 0
10026 run_script:
10027#endif
Denys Vlasenkodea47882009-10-09 15:40:49 +020010028 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010029 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010030 G.root_ppid = getppid();
10031 }
Denis Vlasenko87a86552008-07-29 19:43:10 +000010032 G.global_argv = argv + optind;
10033 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010034 if (builtin_argc) {
10035 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10036 const struct built_in_command *x;
10037
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010038 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010039 x = find_builtin(optarg);
10040 if (x) { /* paranoia */
10041 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10042 G.global_argv += builtin_argc;
10043 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +010010044 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +010010045 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010046 }
10047 goto final_return;
10048 }
10049 if (!G.global_argv[0]) {
10050 /* -c 'script' (no params): prevent empty $0 */
10051 G.global_argv--; /* points to argv[i] of 'script' */
10052 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +020010053 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010054 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010055 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010056 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010057 goto final_return;
10058 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010059 /* Well, we cannot just declare interactiveness,
10060 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010061 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010062 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010063 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010064 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010065 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010066 case 'l':
10067 flags |= OPT_login;
10068 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010069#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010070 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010071 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010072 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010073 case '$': {
10074 unsigned long long empty_trap_mask;
10075
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010076 G.root_pid = bb_strtou(optarg, &optarg, 16);
10077 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010078 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10079 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010080 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10081 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010082 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010083 optarg++;
10084 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010085 optarg++;
10086 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10087 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010088 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010089 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010090# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010091 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010092 for (sig = 1; sig < NSIG; sig++) {
10093 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010094 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010095 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010096 }
10097 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010098# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010099 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010100# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010101 optarg++;
10102 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010103# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010104# if ENABLE_HUSH_FUNCTIONS
10105 /* nommu uses re-exec trick for "... | func | ...",
10106 * should allow "return".
10107 * This accidentally allows returns in subshells.
10108 */
10109 G_flag_return_in_progress = -1;
10110# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010111 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010112 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010113 case 'R':
10114 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010115 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010116 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010117# if ENABLE_HUSH_FUNCTIONS
10118 case 'F': {
10119 struct function *funcp = new_function(optarg);
10120 /* funcp->name is already set to optarg */
10121 /* funcp->body is set to NULL. It's a special case. */
10122 funcp->body_as_string = argv[optind];
10123 optind++;
10124 break;
10125 }
10126# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010127#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010128 case 'n':
10129 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010130 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010131 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010132 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010133 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010134#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010135 fprintf(stderr, "Usage: sh [FILE]...\n"
10136 " or: sh -c command [args]...\n\n");
10137 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010138#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010139 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010140#endif
Eric Andersen25f27032001-04-26 23:22:31 +000010141 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010142 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010143
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010144 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10145 G.global_argc = argc - (optind - 1);
10146 G.global_argv = argv + (optind - 1);
10147 G.global_argv[0] = argv[0];
10148
Denys Vlasenkodea47882009-10-09 15:40:49 +020010149 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010150 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010151 G.root_ppid = getppid();
10152 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010153
10154 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010155 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010156 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010157 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010158 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010159 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010160 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010161 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010162 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010163 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010164 /* bash: after sourcing /etc/profile,
10165 * tries to source (in the given order):
10166 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010167 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010168 * bash also sources ~/.bash_logout on exit.
10169 * If called as sh, skips .bash_XXX files.
10170 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010171 }
10172
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010173 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10174 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010175 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010176 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010177 * "bash <script>" (which is never interactive (unless -i?))
10178 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010179 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010180 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010181 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010182 G.global_argc--;
10183 G.global_argv++;
10184 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010185 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010186 input = hfopen(G.global_argv[0]);
10187 if (!input) {
10188 bb_simple_perror_msg_and_die(G.global_argv[0]);
10189 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010190 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010191 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010192 parse_and_run_file(input);
10193#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010194 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010195#endif
10196 goto final_return;
10197 }
10198
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010199 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010200 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010201 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010202
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010203 /* A shell is interactive if the '-i' flag was given,
10204 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010205 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010206 * no arguments remaining or the -s flag given
10207 * standard input is a terminal
10208 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010209 * Refer to Posix.2, the description of the 'sh' utility.
10210 */
10211#if ENABLE_HUSH_JOB
10212 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010213 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10214 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10215 if (G_saved_tty_pgrp < 0)
10216 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010217
10218 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010219 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010220 if (G_interactive_fd < 0) {
10221 /* try to dup to any fd */
10222 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010223 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010224 /* give up */
10225 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010226 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010227 }
10228 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010229// TODO: track & disallow any attempts of user
10230// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010231 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010232 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010233 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010234 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010235
Mike Frysinger38478a62009-05-20 04:48:06 -040010236 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010237 /* If we were run as 'hush &', sleep until we are
10238 * in the foreground (tty pgrp == our pgrp).
10239 * If we get started under a job aware app (like bash),
10240 * make sure we are now in charge so we don't fight over
10241 * who gets the foreground */
10242 while (1) {
10243 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010244 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10245 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010246 break;
10247 /* send TTIN to ourself (should stop us) */
10248 kill(- shell_pgrp, SIGTTIN);
10249 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010250 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010251
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010252 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010253 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010254
Mike Frysinger38478a62009-05-20 04:48:06 -040010255 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010256 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010257 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010258 /* Put ourselves in our own process group
10259 * (bash, too, does this only if ctty is available) */
10260 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10261 /* Grab control of the terminal */
10262 tcsetpgrp(G_interactive_fd, getpid());
10263 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010264 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010265
10266# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10267 {
10268 const char *hp = get_local_var_value("HISTFILE");
10269 if (!hp) {
10270 hp = get_local_var_value("HOME");
10271 if (hp)
10272 hp = concat_path_file(hp, ".hush_history");
10273 } else {
10274 hp = xstrdup(hp);
10275 }
10276 if (hp) {
10277 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010278 //set_local_var(xasprintf("HISTFILE=%s", ...));
10279 }
10280# if ENABLE_FEATURE_SH_HISTFILESIZE
10281 hp = get_local_var_value("HISTFILESIZE");
10282 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10283# endif
10284 }
10285# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010286 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010287 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010288 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010289#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010290 /* No job control compiled in, only prompt/line editing */
10291 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010292 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010293 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010294 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010295 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010296 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010297 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010298 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010299 }
10300 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010301 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010302 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010303 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010304 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010305#else
10306 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010307 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010308#endif
10309 /* bash:
10310 * if interactive but not a login shell, sources ~/.bashrc
10311 * (--norc turns this off, --rcfile <file> overrides)
10312 */
10313
10314 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010315 /* note: ash and hush share this string */
10316 printf("\n\n%s %s\n"
10317 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10318 "\n",
10319 bb_banner,
10320 "hush - the humble shell"
10321 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010322 }
10323
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010324 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010325
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010326 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010327 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010328}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010329
10330
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010331/*
10332 * Built-ins
10333 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010334static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010335{
10336 return 0;
10337}
10338
Denys Vlasenko265062d2017-01-10 15:13:30 +010010339#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010340static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010341{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010342 int argc = string_array_len(argv);
10343 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010344}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010345#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010346#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010347static int FAST_FUNC builtin_test(char **argv)
10348{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010349 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010350}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010351#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010352#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010353static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010354{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010355 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010356}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010357#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010358#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010359static int FAST_FUNC builtin_printf(char **argv)
10360{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010361 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010362}
10363#endif
10364
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010365#if ENABLE_HUSH_HELP
10366static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10367{
10368 const struct built_in_command *x;
10369
10370 printf(
10371 "Built-in commands:\n"
10372 "------------------\n");
10373 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10374 if (x->b_descr)
10375 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10376 }
10377 return EXIT_SUCCESS;
10378}
10379#endif
10380
10381#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10382static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10383{
10384 show_history(G.line_input_state);
10385 return EXIT_SUCCESS;
10386}
10387#endif
10388
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010389static char **skip_dash_dash(char **argv)
10390{
10391 argv++;
10392 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10393 argv++;
10394 return argv;
10395}
10396
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010397static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010398{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010399 const char *newdir;
10400
10401 argv = skip_dash_dash(argv);
10402 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010403 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010404 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010405 * bash says "bash: cd: HOME not set" and does nothing
10406 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010407 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010408 const char *home = get_local_var_value("HOME");
10409 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010410 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010411 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010412 /* Mimic bash message exactly */
10413 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010414 return EXIT_FAILURE;
10415 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010416 /* Read current dir (get_cwd(1) is inside) and set PWD.
10417 * Note: do not enforce exporting. If PWD was unset or unexported,
10418 * set it again, but do not export. bash does the same.
10419 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010420 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010421 return EXIT_SUCCESS;
10422}
10423
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010424static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10425{
10426 puts(get_cwd(0));
10427 return EXIT_SUCCESS;
10428}
10429
10430static int FAST_FUNC builtin_eval(char **argv)
10431{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010432 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010433
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010434 if (!argv[0])
10435 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010436
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010437 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010438 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010439 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010440 /* bash:
10441 * eval "echo Hi; done" ("done" is syntax error):
10442 * "echo Hi" will not execute too.
10443 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010444 parse_and_run_string(argv[0]);
10445 } else {
10446 /* "The eval utility shall construct a command by
10447 * concatenating arguments together, separating
10448 * each with a <space> character."
10449 */
10450 char *str, *p;
10451 unsigned len = 0;
10452 char **pp = argv;
10453 do
10454 len += strlen(*pp) + 1;
10455 while (*++pp);
10456 str = p = xmalloc(len);
10457 pp = argv;
10458 for (;;) {
10459 p = stpcpy(p, *pp);
10460 pp++;
10461 if (!*pp)
10462 break;
10463 *p++ = ' ';
10464 }
10465 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010466 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010467 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010468 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010469 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010470 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010471}
10472
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010473static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010474{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010475 argv = skip_dash_dash(argv);
10476 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010477 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010478
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010479 /* Careful: we can end up here after [v]fork. Do not restore
10480 * tty pgrp then, only top-level shell process does that */
10481 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10482 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10483
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010484 /* Saved-redirect fds, script fds and G_interactive_fd are still
10485 * open here. However, they are all CLOEXEC, and execv below
10486 * closes them. Try interactive "exec ls -l /proc/self/fd",
10487 * it should show no extra open fds in the "ls" process.
10488 * If we'd try to run builtins/NOEXECs, this would need improving.
10489 */
10490 //close_saved_fds_and_FILE_fds();
10491
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010492 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010493 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010494 * and tcsetpgrp, and this is inherently racy.
10495 */
10496 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497}
10498
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010499static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010500{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010501 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010502
10503 /* interactive bash:
10504 * # trap "echo EEE" EXIT
10505 * # exit
10506 * exit
10507 * There are stopped jobs.
10508 * (if there are _stopped_ jobs, running ones don't count)
10509 * # exit
10510 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010511 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010512 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010513 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010514 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010515
10516 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010517 argv = skip_dash_dash(argv);
10518 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010519 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010520 /* mimic bash: exit 123abc == exit 255 + error msg */
10521 xfunc_error_retval = 255;
10522 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010523 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010524}
10525
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010526#if ENABLE_HUSH_TYPE
10527/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10528static int FAST_FUNC builtin_type(char **argv)
10529{
10530 int ret = EXIT_SUCCESS;
10531
10532 while (*++argv) {
10533 const char *type;
10534 char *path = NULL;
10535
10536 if (0) {} /* make conditional compile easier below */
10537 /*else if (find_alias(*argv))
10538 type = "an alias";*/
10539#if ENABLE_HUSH_FUNCTIONS
10540 else if (find_function(*argv))
10541 type = "a function";
10542#endif
10543 else if (find_builtin(*argv))
10544 type = "a shell builtin";
10545 else if ((path = find_in_path(*argv)) != NULL)
10546 type = path;
10547 else {
10548 bb_error_msg("type: %s: not found", *argv);
10549 ret = EXIT_FAILURE;
10550 continue;
10551 }
10552
10553 printf("%s is %s\n", *argv, type);
10554 free(path);
10555 }
10556
10557 return ret;
10558}
10559#endif
10560
10561#if ENABLE_HUSH_READ
10562/* Interruptibility of read builtin in bash
10563 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10564 *
10565 * Empty trap makes read ignore corresponding signal, for any signal.
10566 *
10567 * SIGINT:
10568 * - terminates non-interactive shell;
10569 * - interrupts read in interactive shell;
10570 * if it has non-empty trap:
10571 * - executes trap and returns to command prompt in interactive shell;
10572 * - executes trap and returns to read in non-interactive shell;
10573 * SIGTERM:
10574 * - is ignored (does not interrupt) read in interactive shell;
10575 * - terminates non-interactive shell;
10576 * if it has non-empty trap:
10577 * - executes trap and returns to read;
10578 * SIGHUP:
10579 * - terminates shell (regardless of interactivity);
10580 * if it has non-empty trap:
10581 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010582 * SIGCHLD from children:
10583 * - does not interrupt read regardless of interactivity:
10584 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010585 */
10586static int FAST_FUNC builtin_read(char **argv)
10587{
10588 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010589 struct builtin_read_params params;
10590
10591 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010592
10593 /* "!": do not abort on errors.
10594 * Option string must start with "sr" to match BUILTIN_READ_xxx
10595 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010596 params.read_flags = getopt32(argv,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010597#if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010598 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010599#else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010600 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010601#endif
10602 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010603 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010604 return EXIT_FAILURE;
10605 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010606 params.argv = argv;
10607 params.setvar = set_local_var_from_halves;
10608 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010609
10610 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010611 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010612
10613 if ((uintptr_t)r == 1 && errno == EINTR) {
10614 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010615 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010616 goto again;
10617 }
10618
10619 if ((uintptr_t)r > 1) {
10620 bb_error_msg("%s", r);
10621 r = (char*)(uintptr_t)1;
10622 }
10623
10624 return (uintptr_t)r;
10625}
10626#endif
10627
10628#if ENABLE_HUSH_UMASK
10629static int FAST_FUNC builtin_umask(char **argv)
10630{
10631 int rc;
10632 mode_t mask;
10633
10634 rc = 1;
10635 mask = umask(0);
10636 argv = skip_dash_dash(argv);
10637 if (argv[0]) {
10638 mode_t old_mask = mask;
10639
10640 /* numeric umasks are taken as-is */
10641 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10642 if (!isdigit(argv[0][0]))
10643 mask ^= 0777;
10644 mask = bb_parse_mode(argv[0], mask);
10645 if (!isdigit(argv[0][0]))
10646 mask ^= 0777;
10647 if ((unsigned)mask > 0777) {
10648 mask = old_mask;
10649 /* bash messages:
10650 * bash: umask: 'q': invalid symbolic mode operator
10651 * bash: umask: 999: octal number out of range
10652 */
10653 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10654 rc = 0;
10655 }
10656 } else {
10657 /* Mimic bash */
10658 printf("%04o\n", (unsigned) mask);
10659 /* fall through and restore mask which we set to 0 */
10660 }
10661 umask(mask);
10662
10663 return !rc; /* rc != 0 - success */
10664}
10665#endif
10666
Denys Vlasenko41ade052017-01-08 18:56:24 +010010667#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010668static void print_escaped(const char *s)
10669{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010670 if (*s == '\'')
10671 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010672 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010673 const char *p = strchrnul(s, '\'');
10674 /* print 'xxxx', possibly just '' */
10675 printf("'%.*s'", (int)(p - s), s);
10676 if (*p == '\0')
10677 break;
10678 s = p;
10679 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010680 /* s points to '; print "'''...'''" */
10681 putchar('"');
10682 do putchar('\''); while (*++s == '\'');
10683 putchar('"');
10684 } while (*s);
10685}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010686#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010687
Denys Vlasenko1e660422017-07-17 21:10:50 +020010688#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010689static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010690{
10691 do {
10692 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010693 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010694
10695 /* So far we do not check that name is valid (TODO?) */
10696
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010697 if (*name_end == '\0') {
10698 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010699
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010700 vpp = get_ptr_to_local_var(name, name_end - name);
10701 var = vpp ? *vpp : NULL;
10702
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010703 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010704 /* export -n NAME (without =VALUE) */
10705 if (var) {
10706 var->flg_export = 0;
10707 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10708 unsetenv(name);
10709 } /* else: export -n NOT_EXISTING_VAR: no-op */
10710 continue;
10711 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010712 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010713 /* export NAME (without =VALUE) */
10714 if (var) {
10715 var->flg_export = 1;
10716 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10717 putenv(var->varstr);
10718 continue;
10719 }
10720 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010721 if (flags & SETFLAG_MAKE_RO) {
10722 /* readonly NAME (without =VALUE) */
10723 if (var) {
10724 var->flg_read_only = 1;
10725 continue;
10726 }
10727 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010728# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010729 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010730 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010731 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10732 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010733 /* "local x=abc; ...; local x" - ignore second local decl */
10734 continue;
10735 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010736 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010737# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010738 /* Exporting non-existing variable.
10739 * bash does not put it in environment,
10740 * but remembers that it is exported,
10741 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010742 * We just set it to "" and export.
10743 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010744 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010745 * bash sets the value to "".
10746 */
10747 /* Or, it's "readonly NAME" (without =VALUE).
10748 * bash remembers NAME and disallows its creation
10749 * in the future.
10750 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010751 name = xasprintf("%s=", name);
10752 } else {
10753 /* (Un)exporting/making local NAME=VALUE */
10754 name = xstrdup(name);
10755 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010756 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010757 if (set_local_var(name, flags))
10758 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010759 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010760 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010761}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010762#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010763
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010764#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010765static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010766{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010767 unsigned opt_unexport;
10768
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010769#if ENABLE_HUSH_EXPORT_N
10770 /* "!": do not abort on errors */
10771 opt_unexport = getopt32(argv, "!n");
10772 if (opt_unexport == (uint32_t)-1)
10773 return EXIT_FAILURE;
10774 argv += optind;
10775#else
10776 opt_unexport = 0;
10777 argv++;
10778#endif
10779
10780 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010781 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010782 if (e) {
10783 while (*e) {
10784#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010785 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010786#else
10787 /* ash emits: export VAR='VAL'
10788 * bash: declare -x VAR="VAL"
10789 * we follow ash example */
10790 const char *s = *e++;
10791 const char *p = strchr(s, '=');
10792
10793 if (!p) /* wtf? take next variable */
10794 continue;
10795 /* export var= */
10796 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010797 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010798 putchar('\n');
10799#endif
10800 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010801 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010802 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010803 return EXIT_SUCCESS;
10804 }
10805
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010806 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010807}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010808#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010809
Denys Vlasenko295fef82009-06-03 12:47:26 +020010810#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010811static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010812{
10813 if (G.func_nest_level == 0) {
10814 bb_error_msg("%s: not in a function", argv[0]);
10815 return EXIT_FAILURE; /* bash compat */
10816 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010817 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010818 /* Since all builtins run in a nested variable level,
10819 * need to use level - 1 here. Or else the variable will be removed at once
10820 * after builtin returns.
10821 */
10822 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010823}
10824#endif
10825
Denys Vlasenko1e660422017-07-17 21:10:50 +020010826#if ENABLE_HUSH_READONLY
10827static int FAST_FUNC builtin_readonly(char **argv)
10828{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010829 argv++;
10830 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010831 /* bash: readonly [-p]: list all readonly VARs
10832 * (-p has no effect in bash)
10833 */
10834 struct variable *e;
10835 for (e = G.top_var; e; e = e->next) {
10836 if (e->flg_read_only) {
10837//TODO: quote value: readonly VAR='VAL'
10838 printf("readonly %s\n", e->varstr);
10839 }
10840 }
10841 return EXIT_SUCCESS;
10842 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010843 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010844}
10845#endif
10846
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010847#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010848/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10849static int FAST_FUNC builtin_unset(char **argv)
10850{
10851 int ret;
10852 unsigned opts;
10853
10854 /* "!": do not abort on errors */
10855 /* "+": stop at 1st non-option */
10856 opts = getopt32(argv, "!+vf");
10857 if (opts == (unsigned)-1)
10858 return EXIT_FAILURE;
10859 if (opts == 3) {
10860 bb_error_msg("unset: -v and -f are exclusive");
10861 return EXIT_FAILURE;
10862 }
10863 argv += optind;
10864
10865 ret = EXIT_SUCCESS;
10866 while (*argv) {
10867 if (!(opts & 2)) { /* not -f */
10868 if (unset_local_var(*argv)) {
10869 /* unset <nonexistent_var> doesn't fail.
10870 * Error is when one tries to unset RO var.
10871 * Message was printed by unset_local_var. */
10872 ret = EXIT_FAILURE;
10873 }
10874 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010875# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010876 else {
10877 unset_func(*argv);
10878 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010879# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010880 argv++;
10881 }
10882 return ret;
10883}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010884#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010885
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010886#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010887/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10888 * built-in 'set' handler
10889 * SUSv3 says:
10890 * set [-abCefhmnuvx] [-o option] [argument...]
10891 * set [+abCefhmnuvx] [+o option] [argument...]
10892 * set -- [argument...]
10893 * set -o
10894 * set +o
10895 * Implementations shall support the options in both their hyphen and
10896 * plus-sign forms. These options can also be specified as options to sh.
10897 * Examples:
10898 * Write out all variables and their values: set
10899 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10900 * Turn on the -x and -v options: set -xv
10901 * Unset all positional parameters: set --
10902 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10903 * Set the positional parameters to the expansion of x, even if x expands
10904 * with a leading '-' or '+': set -- $x
10905 *
10906 * So far, we only support "set -- [argument...]" and some of the short names.
10907 */
10908static int FAST_FUNC builtin_set(char **argv)
10909{
10910 int n;
10911 char **pp, **g_argv;
10912 char *arg = *++argv;
10913
10914 if (arg == NULL) {
10915 struct variable *e;
10916 for (e = G.top_var; e; e = e->next)
10917 puts(e->varstr);
10918 return EXIT_SUCCESS;
10919 }
10920
10921 do {
10922 if (strcmp(arg, "--") == 0) {
10923 ++argv;
10924 goto set_argv;
10925 }
10926 if (arg[0] != '+' && arg[0] != '-')
10927 break;
10928 for (n = 1; arg[n]; ++n) {
10929 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10930 goto error;
10931 if (arg[n] == 'o' && argv[1])
10932 argv++;
10933 }
10934 } while ((arg = *++argv) != NULL);
10935 /* Now argv[0] is 1st argument */
10936
10937 if (arg == NULL)
10938 return EXIT_SUCCESS;
10939 set_argv:
10940
10941 /* NB: G.global_argv[0] ($0) is never freed/changed */
10942 g_argv = G.global_argv;
10943 if (G.global_args_malloced) {
10944 pp = g_argv;
10945 while (*++pp)
10946 free(*pp);
10947 g_argv[1] = NULL;
10948 } else {
10949 G.global_args_malloced = 1;
10950 pp = xzalloc(sizeof(pp[0]) * 2);
10951 pp[0] = g_argv[0]; /* retain $0 */
10952 g_argv = pp;
10953 }
10954 /* This realloc's G.global_argv */
10955 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10956
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010957 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010958
10959 return EXIT_SUCCESS;
10960
10961 /* Nothing known, so abort */
10962 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010963 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010964 return EXIT_FAILURE;
10965}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010966#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010967
10968static int FAST_FUNC builtin_shift(char **argv)
10969{
10970 int n = 1;
10971 argv = skip_dash_dash(argv);
10972 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010973 n = bb_strtou(argv[0], NULL, 10);
10974 if (errno || n < 0) {
10975 /* shared string with ash.c */
10976 bb_error_msg("Illegal number: %s", argv[0]);
10977 /*
10978 * ash aborts in this case.
10979 * bash prints error message and set $? to 1.
10980 * Interestingly, for "shift 99999" bash does not
10981 * print error message, but does set $? to 1
10982 * (and does no shifting at all).
10983 */
10984 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010985 }
10986 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010987 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010988 int m = 1;
10989 while (m <= n)
10990 free(G.global_argv[m++]);
10991 }
10992 G.global_argc -= n;
10993 memmove(&G.global_argv[1], &G.global_argv[n+1],
10994 G.global_argc * sizeof(G.global_argv[0]));
10995 return EXIT_SUCCESS;
10996 }
10997 return EXIT_FAILURE;
10998}
10999
Denys Vlasenko74d40582017-08-11 01:32:46 +020011000#if ENABLE_HUSH_GETOPTS
11001static int FAST_FUNC builtin_getopts(char **argv)
11002{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011003/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11004
Denys Vlasenko74d40582017-08-11 01:32:46 +020011005TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011006If a required argument is not found, and getopts is not silent,
11007a question mark (?) is placed in VAR, OPTARG is unset, and a
11008diagnostic message is printed. If getopts is silent, then a
11009colon (:) is placed in VAR and OPTARG is set to the option
11010character found.
11011
11012Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011013
11014"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011015*/
11016 char cbuf[2];
11017 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011018 int c, n, exitcode, my_opterr;
11019 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011020
11021 optstring = *++argv;
11022 if (!optstring || !(var = *++argv)) {
11023 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
11024 return EXIT_FAILURE;
11025 }
11026
Denys Vlasenko238ff982017-08-29 13:38:30 +020011027 if (argv[1])
11028 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11029 else
11030 argv = G.global_argv;
11031 cbuf[1] = '\0';
11032
11033 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011034 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011035 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011036 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011037 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011038 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011039
11040 /* getopts stops on first non-option. Add "+" to force that */
11041 /*if (optstring[0] != '+')*/ {
11042 char *s = alloca(strlen(optstring) + 2);
11043 sprintf(s, "+%s", optstring);
11044 optstring = s;
11045 }
11046
Denys Vlasenko238ff982017-08-29 13:38:30 +020011047 /* Naively, now we should just
11048 * cp = get_local_var_value("OPTIND");
11049 * optind = cp ? atoi(cp) : 0;
11050 * optarg = NULL;
11051 * opterr = my_opterr;
11052 * c = getopt(string_array_len(argv), argv, optstring);
11053 * and be done? Not so fast...
11054 * Unlike normal getopt() usage in C programs, here
11055 * each successive call will (usually) have the same argv[] CONTENTS,
11056 * but not the ADDRESSES. Worse yet, it's possible that between
11057 * invocations of "getopts", there will be calls to shell builtins
11058 * which use getopt() internally. Example:
11059 * while getopts "abc" RES -a -bc -abc de; do
11060 * unset -ff func
11061 * done
11062 * This would not work correctly: getopt() call inside "unset"
11063 * modifies internal libc state which is tracking position in
11064 * multi-option strings ("-abc"). At best, it can skip options
11065 * or return the same option infinitely. With glibc implementation
11066 * of getopt(), it would use outright invalid pointers and return
11067 * garbage even _without_ "unset" mangling internal state.
11068 *
11069 * We resort to resetting getopt() state and calling it N times,
11070 * until we get Nth result (or failure).
11071 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11072 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011073 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011074 count = 0;
11075 n = string_array_len(argv);
11076 do {
11077 optarg = NULL;
11078 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11079 c = getopt(n, argv, optstring);
11080 if (c < 0)
11081 break;
11082 count++;
11083 } while (count <= G.getopt_count);
11084
11085 /* Set OPTIND. Prevent resetting of the magic counter! */
11086 set_local_var_from_halves("OPTIND", utoa(optind));
11087 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011088 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011089
11090 /* Set OPTARG */
11091 /* Always set or unset, never left as-is, even on exit/error:
11092 * "If no option was found, or if the option that was found
11093 * does not have an option-argument, OPTARG shall be unset."
11094 */
11095 cp = optarg;
11096 if (c == '?') {
11097 /* If ":optstring" and unknown option is seen,
11098 * it is stored to OPTARG.
11099 */
11100 if (optstring[1] == ':') {
11101 cbuf[0] = optopt;
11102 cp = cbuf;
11103 }
11104 }
11105 if (cp)
11106 set_local_var_from_halves("OPTARG", cp);
11107 else
11108 unset_local_var("OPTARG");
11109
11110 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011111 exitcode = EXIT_SUCCESS;
11112 if (c < 0) { /* -1: end of options */
11113 exitcode = EXIT_FAILURE;
11114 c = '?';
11115 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011116
Denys Vlasenko238ff982017-08-29 13:38:30 +020011117 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011118 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011119 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011120
Denys Vlasenko74d40582017-08-11 01:32:46 +020011121 return exitcode;
11122}
11123#endif
11124
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011125static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011126{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011127 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011128 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011129 save_arg_t sv;
11130 char *args_need_save;
11131#if ENABLE_HUSH_FUNCTIONS
11132 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011133#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011134
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011135 argv = skip_dash_dash(argv);
11136 filename = argv[0];
11137 if (!filename) {
11138 /* bash says: "bash: .: filename argument required" */
11139 return 2; /* bash compat */
11140 }
11141 arg_path = NULL;
11142 if (!strchr(filename, '/')) {
11143 arg_path = find_in_path(filename);
11144 if (arg_path)
11145 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011146 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011147 errno = ENOENT;
11148 bb_simple_perror_msg(filename);
11149 return EXIT_FAILURE;
11150 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011151 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011152 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011153 free(arg_path);
11154 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011155 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011156 /* POSIX: non-interactive shell should abort here,
11157 * not merely fail. So far no one complained :)
11158 */
11159 return EXIT_FAILURE;
11160 }
11161
11162#if ENABLE_HUSH_FUNCTIONS
11163 sv_flg = G_flag_return_in_progress;
11164 /* "we are inside sourced file, ok to use return" */
11165 G_flag_return_in_progress = -1;
11166#endif
11167 args_need_save = argv[1]; /* used as a boolean variable */
11168 if (args_need_save)
11169 save_and_replace_G_args(&sv, argv);
11170
11171 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11172 G.last_exitcode = 0;
11173 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011174 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011175
11176 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11177 restore_G_args(&sv, argv);
11178#if ENABLE_HUSH_FUNCTIONS
11179 G_flag_return_in_progress = sv_flg;
11180#endif
11181
11182 return G.last_exitcode;
11183}
11184
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011185#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011186static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011187{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011188 int sig;
11189 char *new_cmd;
11190
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011191 if (!G_traps)
11192 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011193
11194 argv++;
11195 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011196 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011197 /* No args: print all trapped */
11198 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011199 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011200 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011201 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011202 /* note: bash adds "SIG", but only if invoked
11203 * as "bash". If called as "sh", or if set -o posix,
11204 * then it prints short signal names.
11205 * We are printing short names: */
11206 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011207 }
11208 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011209 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011210 return EXIT_SUCCESS;
11211 }
11212
11213 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011214 /* If first arg is a number: reset all specified signals */
11215 sig = bb_strtou(*argv, NULL, 10);
11216 if (errno == 0) {
11217 int ret;
11218 process_sig_list:
11219 ret = EXIT_SUCCESS;
11220 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011221 sighandler_t handler;
11222
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011223 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011224 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011225 ret = EXIT_FAILURE;
11226 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011227 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011228 continue;
11229 }
11230
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011231 free(G_traps[sig]);
11232 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011233
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011234 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011235 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011236
11237 /* There is no signal for 0 (EXIT) */
11238 if (sig == 0)
11239 continue;
11240
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011241 if (new_cmd)
11242 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11243 else
11244 /* We are removing trap handler */
11245 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011246 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011247 }
11248 return ret;
11249 }
11250
11251 if (!argv[1]) { /* no second arg */
11252 bb_error_msg("trap: invalid arguments");
11253 return EXIT_FAILURE;
11254 }
11255
11256 /* First arg is "-": reset all specified to default */
11257 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11258 /* Everything else: set arg as signal handler
11259 * (includes "" case, which ignores signal) */
11260 if (argv[0][0] == '-') {
11261 if (argv[0][1] == '\0') { /* "-" */
11262 /* new_cmd remains NULL: "reset these sigs" */
11263 goto reset_traps;
11264 }
11265 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11266 argv++;
11267 }
11268 /* else: "-something", no special meaning */
11269 }
11270 new_cmd = *argv;
11271 reset_traps:
11272 argv++;
11273 goto process_sig_list;
11274}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011275#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011276
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011277#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011278static struct pipe *parse_jobspec(const char *str)
11279{
11280 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011281 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011282
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011283 if (sscanf(str, "%%%u", &jobnum) != 1) {
11284 if (str[0] != '%'
11285 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11286 ) {
11287 bb_error_msg("bad argument '%s'", str);
11288 return NULL;
11289 }
11290 /* It is "%%", "%+" or "%" - current job */
11291 jobnum = G.last_jobid;
11292 if (jobnum == 0) {
11293 bb_error_msg("no current job");
11294 return NULL;
11295 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011296 }
11297 for (pi = G.job_list; pi; pi = pi->next) {
11298 if (pi->jobid == jobnum) {
11299 return pi;
11300 }
11301 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011302 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011303 return NULL;
11304}
11305
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011306static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11307{
11308 struct pipe *job;
11309 const char *status_string;
11310
11311 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11312 for (job = G.job_list; job; job = job->next) {
11313 if (job->alive_cmds == job->stopped_cmds)
11314 status_string = "Stopped";
11315 else
11316 status_string = "Running";
11317
11318 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11319 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011320
11321 clean_up_last_dead_job();
11322
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011323 return EXIT_SUCCESS;
11324}
11325
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011326/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011327static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011328{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011329 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011330 struct pipe *pi;
11331
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011332 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011333 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011334
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011335 /* If they gave us no args, assume they want the last backgrounded task */
11336 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011337 for (pi = G.job_list; pi; pi = pi->next) {
11338 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011339 goto found;
11340 }
11341 }
11342 bb_error_msg("%s: no current job", argv[0]);
11343 return EXIT_FAILURE;
11344 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011345
11346 pi = parse_jobspec(argv[1]);
11347 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011348 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011349 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011350 /* TODO: bash prints a string representation
11351 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011352 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011353 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011354 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011355 }
11356
11357 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011358 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11359 for (i = 0; i < pi->num_cmds; i++) {
11360 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011361 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011362 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011363
11364 i = kill(- pi->pgrp, SIGCONT);
11365 if (i < 0) {
11366 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011367 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011368 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011369 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011370 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011371 }
11372
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011373 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011374 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011375 return checkjobs_and_fg_shell(pi);
11376 }
11377 return EXIT_SUCCESS;
11378}
11379#endif
11380
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011381#if ENABLE_HUSH_KILL
11382static int FAST_FUNC builtin_kill(char **argv)
11383{
11384 int ret = 0;
11385
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011386# if ENABLE_HUSH_JOB
11387 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11388 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011389
11390 do {
11391 struct pipe *pi;
11392 char *dst;
11393 int j, n;
11394
11395 if (argv[i][0] != '%')
11396 continue;
11397 /*
11398 * "kill %N" - job kill
11399 * Converting to pgrp / pid kill
11400 */
11401 pi = parse_jobspec(argv[i]);
11402 if (!pi) {
11403 /* Eat bad jobspec */
11404 j = i;
11405 do {
11406 j++;
11407 argv[j - 1] = argv[j];
11408 } while (argv[j]);
11409 ret = 1;
11410 i--;
11411 continue;
11412 }
11413 /*
11414 * In jobs started under job control, we signal
11415 * entire process group by kill -PGRP_ID.
11416 * This happens, f.e., in interactive shell.
11417 *
11418 * Otherwise, we signal each child via
11419 * kill PID1 PID2 PID3.
11420 * Testcases:
11421 * sh -c 'sleep 1|sleep 1 & kill %1'
11422 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11423 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11424 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011425 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011426 dst = alloca(n * sizeof(int)*4);
11427 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011428 if (G_interactive_fd)
11429 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011430 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011431 struct command *cmd = &pi->cmds[j];
11432 /* Skip exited members of the job */
11433 if (cmd->pid == 0)
11434 continue;
11435 /*
11436 * kill_main has matching code to expect
11437 * leading space. Needed to not confuse
11438 * negative pids with "kill -SIGNAL_NO" syntax
11439 */
11440 dst += sprintf(dst, " %u", (int)cmd->pid);
11441 }
11442 *dst = '\0';
11443 } while (argv[++i]);
11444 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011445# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011446
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011447 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011448 ret = run_applet_main(argv, kill_main);
11449 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011450 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011451 return ret;
11452}
11453#endif
11454
11455#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011456/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011457#if !ENABLE_HUSH_JOB
11458# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11459#endif
11460static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011461{
11462 int ret = 0;
11463 for (;;) {
11464 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011465 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011466
Denys Vlasenko830ea352016-11-08 04:59:11 +010011467 if (!sigisemptyset(&G.pending_set))
11468 goto check_sig;
11469
Denys Vlasenko7e675362016-10-28 21:57:31 +020011470 /* waitpid is not interruptible by SA_RESTARTed
11471 * signals which we use. Thus, this ugly dance:
11472 */
11473
11474 /* Make sure possible SIGCHLD is stored in kernel's
11475 * pending signal mask before we call waitpid.
11476 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011477 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011478 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011479 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011480 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011481
11482 if (!sigisemptyset(&G.pending_set)) {
11483 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011484 goto restore;
11485 }
11486
11487 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011488/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011489 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011490 debug_printf_exec("checkjobs:%d\n", ret);
11491#if ENABLE_HUSH_JOB
11492 if (waitfor_pipe) {
11493 int rcode = job_exited_or_stopped(waitfor_pipe);
11494 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11495 if (rcode >= 0) {
11496 ret = rcode;
11497 sigprocmask(SIG_SETMASK, &oldset, NULL);
11498 break;
11499 }
11500 }
11501#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011502 /* if ECHILD, there are no children (ret is -1 or 0) */
11503 /* if ret == 0, no children changed state */
11504 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011505 if (errno == ECHILD || ret) {
11506 ret--;
11507 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011508 ret = 0;
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011509#if ENABLE_HUSH_BASH_COMPAT
11510 if (waitfor_pid == -1 && errno == ECHILD) {
11511 /* exitcode of "wait -n" with no children is 127, not 0 */
11512 ret = 127;
11513 }
11514#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011515 sigprocmask(SIG_SETMASK, &oldset, NULL);
11516 break;
11517 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011518 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011519 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11520 /* Note: sigsuspend invokes signal handler */
11521 sigsuspend(&oldset);
11522 restore:
11523 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011524 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011525 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011526 sig = check_and_run_traps();
11527 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011528 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011529 ret = 128 + sig;
11530 break;
11531 }
11532 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11533 }
11534 return ret;
11535}
11536
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011537static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011538{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011539 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011540 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011541
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011542 argv = skip_dash_dash(argv);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011543#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011544 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011545 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011546 /* (bash accepts "wait -n PID" too and ignores PID) */
11547 G.dead_job_exitcode = -1;
11548 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011549 }
11550#endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011551 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011552 /* Don't care about wait results */
11553 /* Note 1: must wait until there are no more children */
11554 /* Note 2: must be interruptible */
11555 /* Examples:
11556 * $ sleep 3 & sleep 6 & wait
11557 * [1] 30934 sleep 3
11558 * [2] 30935 sleep 6
11559 * [1] Done sleep 3
11560 * [2] Done sleep 6
11561 * $ sleep 3 & sleep 6 & wait
11562 * [1] 30936 sleep 3
11563 * [2] 30937 sleep 6
11564 * [1] Done sleep 3
11565 * ^C <-- after ~4 sec from keyboard
11566 * $
11567 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011568 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011569 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011570
Denys Vlasenko7e675362016-10-28 21:57:31 +020011571 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011572 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011573 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011574#if ENABLE_HUSH_JOB
11575 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011576 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011577 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011578 wait_pipe = parse_jobspec(*argv);
11579 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011580 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011581 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011582 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011583 } else {
11584 /* waiting on "last dead job" removes it */
11585 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011586 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011587 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011588 /* else: parse_jobspec() already emitted error msg */
11589 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011590 }
11591#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011592 /* mimic bash message */
11593 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011594 ret = EXIT_FAILURE;
11595 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011596 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011597
Denys Vlasenko7e675362016-10-28 21:57:31 +020011598 /* Do we have such child? */
11599 ret = waitpid(pid, &status, WNOHANG);
11600 if (ret < 0) {
11601 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011602 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011603 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011604 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011605 /* "wait $!" but last bg task has already exited. Try:
11606 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11607 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011608 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011609 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011610 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011611 } else {
11612 /* Example: "wait 1". mimic bash message */
11613 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011614 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011615 } else {
11616 /* ??? */
11617 bb_perror_msg("wait %s", *argv);
11618 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011619 continue; /* bash checks all argv[] */
11620 }
11621 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011622 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011623 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011624 } else {
11625 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011626 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011627 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011628 if (WIFSIGNALED(status))
11629 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011630 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011631 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011632
11633 return ret;
11634}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011635#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011636
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011637#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11638static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11639{
11640 if (argv[1]) {
11641 def = bb_strtou(argv[1], NULL, 10);
11642 if (errno || def < def_min || argv[2]) {
11643 bb_error_msg("%s: bad arguments", argv[0]);
11644 def = UINT_MAX;
11645 }
11646 }
11647 return def;
11648}
11649#endif
11650
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011651#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011652static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011653{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011654 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011655 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011656 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011657 /* if we came from builtin_continue(), need to undo "= 1" */
11658 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011659 return EXIT_SUCCESS; /* bash compat */
11660 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011661 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011662
11663 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11664 if (depth == UINT_MAX)
11665 G.flag_break_continue = BC_BREAK;
11666 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011667 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011668
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011669 return EXIT_SUCCESS;
11670}
11671
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011672static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011673{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011674 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11675 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011676}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011677#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011678
11679#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011680static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011681{
11682 int rc;
11683
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011684 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011685 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11686 return EXIT_FAILURE; /* bash compat */
11687 }
11688
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011689 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011690
11691 /* bash:
11692 * out of range: wraps around at 256, does not error out
11693 * non-numeric param:
11694 * f() { false; return qwe; }; f; echo $?
11695 * bash: return: qwe: numeric argument required <== we do this
11696 * 255 <== we also do this
11697 */
11698 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11699 return rc;
11700}
11701#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011702
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011703#if ENABLE_HUSH_TIMES
11704static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11705{
11706 static const uint8_t times_tbl[] ALIGN1 = {
11707 ' ', offsetof(struct tms, tms_utime),
11708 '\n', offsetof(struct tms, tms_stime),
11709 ' ', offsetof(struct tms, tms_cutime),
11710 '\n', offsetof(struct tms, tms_cstime),
11711 0
11712 };
11713 const uint8_t *p;
11714 unsigned clk_tck;
11715 struct tms buf;
11716
11717 clk_tck = bb_clk_tck();
11718
11719 times(&buf);
11720 p = times_tbl;
11721 do {
11722 unsigned sec, frac;
11723 unsigned long t;
11724 t = *(clock_t *)(((char *) &buf) + p[1]);
11725 sec = t / clk_tck;
11726 frac = t % clk_tck;
11727 printf("%um%u.%03us%c",
11728 sec / 60, sec % 60,
11729 (frac * 1000) / clk_tck,
11730 p[0]);
11731 p += 2;
11732 } while (*p);
11733
11734 return EXIT_SUCCESS;
11735}
11736#endif
11737
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011738#if ENABLE_HUSH_MEMLEAK
11739static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11740{
11741 void *p;
11742 unsigned long l;
11743
11744# ifdef M_TRIM_THRESHOLD
11745 /* Optional. Reduces probability of false positives */
11746 malloc_trim(0);
11747# endif
11748 /* Crude attempt to find where "free memory" starts,
11749 * sans fragmentation. */
11750 p = malloc(240);
11751 l = (unsigned long)p;
11752 free(p);
11753 p = malloc(3400);
11754 if (l < (unsigned long)p) l = (unsigned long)p;
11755 free(p);
11756
11757
11758# if 0 /* debug */
11759 {
11760 struct mallinfo mi = mallinfo();
11761 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11762 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11763 }
11764# endif
11765
11766 if (!G.memleak_value)
11767 G.memleak_value = l;
11768
11769 l -= G.memleak_value;
11770 if ((long)l < 0)
11771 l = 0;
11772 l /= 1024;
11773 if (l > 127)
11774 l = 127;
11775
11776 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11777 return l;
11778}
11779#endif