blob: b3ae73b9b626892422c9481eec27e0859ed8abd9 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenkob097a842018-12-28 03:20:17 +010096//config: bool "hush (68 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Ron Yorston060f0a02018-11-09 12:00:39 +0000160//config: bool "Support command substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200360#ifndef O_CLOEXEC
361# define O_CLOEXEC 0
362#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100363#ifndef F_DUPFD_CLOEXEC
364# define F_DUPFD_CLOEXEC F_DUPFD
365#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100366
Ron Yorston71df2d32018-11-27 14:34:25 +0000367#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
368# include "embedded_scripts.h"
369#else
370# define NUM_SCRIPTS 0
371#endif
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000372
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100373/* So far, all bash compat is controlled by one config option */
374/* Separate defines document which part of code implements what */
375#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
376#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100377#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
378#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100379#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200380#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200381#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100382
383
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200384/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000385#define LEAK_HUNTING 0
386#define BUILD_AS_NOMMU 0
387/* Enable/disable sanity checks. Ok to enable in production,
388 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
389 * Keeping 1 for now even in released versions.
390 */
391#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200392/* Slightly bigger (+200 bytes), but faster hush.
393 * So far it only enables a trick with counting SIGCHLDs and forks,
394 * which allows us to do fewer waitpid's.
395 * (we can detect a case where neither forks were done nor SIGCHLDs happened
396 * and therefore waitpid will return the same result as last time)
397 */
398#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200399/* TODO: implement simplified code for users which do not need ${var%...} ops
400 * So far ${var%...} ops are always enabled:
401 */
402#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000403
404
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000405#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000406# undef BB_MMU
407# undef USE_FOR_NOMMU
408# undef USE_FOR_MMU
409# define BB_MMU 0
410# define USE_FOR_NOMMU(...) __VA_ARGS__
411# define USE_FOR_MMU(...)
412#endif
413
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200414#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100415#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000416/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000417# undef CONFIG_FEATURE_SH_STANDALONE
418# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000419# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100420# undef IF_NOT_FEATURE_SH_STANDALONE
421# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000422# define IF_FEATURE_SH_STANDALONE(...)
423# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000424#endif
425
Denis Vlasenko05743d72008-02-10 12:10:08 +0000426#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000427# undef ENABLE_FEATURE_EDITING
428# define ENABLE_FEATURE_EDITING 0
429# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
430# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200431# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
432# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000433#endif
434
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000435/* Do we support ANY keywords? */
436#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000437# define HAS_KEYWORDS 1
438# define IF_HAS_KEYWORDS(...) __VA_ARGS__
439# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000440#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000441# define HAS_KEYWORDS 0
442# define IF_HAS_KEYWORDS(...)
443# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000444#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000445
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000446/* If you comment out one of these below, it will be #defined later
447 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200448#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000449/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200450#define debug_printf_parse(...) do {} while (0)
451#define debug_printf_heredoc(...) do {} while (0)
452#define debug_print_tree(a, b) do {} while (0)
453#define debug_printf_exec(...) do {} while (0)
454#define debug_printf_env(...) do {} while (0)
455#define debug_printf_jobs(...) do {} while (0)
456#define debug_printf_expand(...) do {} while (0)
457#define debug_printf_varexp(...) do {} while (0)
458#define debug_printf_glob(...) do {} while (0)
459#define debug_printf_redir(...) do {} while (0)
460#define debug_printf_list(...) do {} while (0)
461#define debug_printf_subst(...) do {} while (0)
462#define debug_printf_prompt(...) do {} while (0)
463#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000464
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000465#define ERR_PTR ((void*)(long)1)
466
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100467#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000468
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200469#define _SPECIAL_VARS_STR "_*@$!?#"
470#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
471#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100472#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200473/* Support / and // replace ops */
474/* Note that // is stored as \ in "encoded" string representation */
475# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
476# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
477# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
478#else
479# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
480# define VAR_SUBST_OPS "%#:-=+?"
481# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
482#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200483
Denys Vlasenko932b9972018-01-11 12:39:48 +0100484#define SPECIAL_VAR_SYMBOL_STR "\3"
485#define SPECIAL_VAR_SYMBOL 3
486/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
487#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000488
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200489struct variable;
490
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000491static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
492
493/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000494 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000495 */
496#if !BB_MMU
497typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200498 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000499 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000500 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000501} nommu_save_t;
502#endif
503
Denys Vlasenko9b782552010-09-08 13:33:26 +0200504enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000505 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000506#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_IF ,
508 RES_THEN ,
509 RES_ELIF ,
510 RES_ELSE ,
511 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000512#endif
513#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_FOR ,
515 RES_WHILE ,
516 RES_UNTIL ,
517 RES_DO ,
518 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000519#endif
520#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000521 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000522#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523#if ENABLE_HUSH_CASE
524 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200525 /* three pseudo-keywords support contrived "case" syntax: */
526 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
527 RES_MATCH , /* "word)" */
528 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000529 RES_ESAC ,
530#endif
531 RES_XXXX ,
532 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200533};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000534
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000535typedef struct o_string {
536 char *data;
537 int length; /* position where data is appended */
538 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200539 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000540 /* At least some part of the string was inside '' or "",
541 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200542 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000543 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200544 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545} o_string;
546enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200547 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
548 EXP_FLAG_GLOB = 0x2,
549 /* Protect newly added chars against globbing
550 * by prepending \ to *, ?, [, \ */
551 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
552};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000553/* Used for initialization: o_string foo = NULL_O_STRING; */
554#define NULL_O_STRING { NULL }
555
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200556#ifndef debug_printf_parse
557static const char *const assignment_flag[] = {
558 "MAYBE_ASSIGNMENT",
559 "DEFINITELY_ASSIGNMENT",
560 "NOT_ASSIGNMENT",
561 "WORD_IS_KEYWORD",
562};
563#endif
564
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200565/* We almost can use standard FILE api, but we need an ability to move
566 * its fd when redirects coincide with it. No api exists for that
567 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
568 * HFILE is our internal alternative. Only supports reading.
569 * Since we now can, we incorporate linked list of all opened HFILEs
570 * into the struct (used to be a separate mini-list).
571 */
572typedef struct HFILE {
573 char *cur;
574 char *end;
575 struct HFILE *next_hfile;
576 int is_stdin;
577 int fd;
578 char buf[1024];
579} HFILE;
580
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000581typedef struct in_str {
582 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200583 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200584 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200585 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000586} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000587
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200588/* The descrip member of this structure is only used to make
589 * debugging output pretty */
590static const struct {
591 int mode;
592 signed char default_fd;
593 char descrip[3];
594} redir_table[] = {
595 { O_RDONLY, 0, "<" },
596 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
597 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
598 { O_CREAT|O_RDWR, 1, "<>" },
599 { O_RDONLY, 0, "<<" },
600/* Should not be needed. Bogus default_fd helps in debugging */
601/* { O_RDONLY, 77, "<<" }, */
602};
603
Eric Andersen25f27032001-04-26 23:22:31 +0000604struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000605 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000606 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000607 int rd_fd; /* fd to redirect */
608 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
609 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000610 smallint rd_type; /* (enum redir_type) */
611 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000612 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200613 * bit 0: do we need to trim leading tabs?
614 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000615 */
Eric Andersen25f27032001-04-26 23:22:31 +0000616};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000617typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200618 REDIRECT_INPUT = 0,
619 REDIRECT_OVERWRITE = 1,
620 REDIRECT_APPEND = 2,
621 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000622 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200623 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000624
625 REDIRFD_CLOSE = -3,
626 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000627 REDIRFD_TO_FILE = -1,
628 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000629
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000630 HEREDOC_SKIPTABS = 1,
631 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000632} redir_type;
633
Eric Andersen25f27032001-04-26 23:22:31 +0000634
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000635struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000636 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200637 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100638#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100639 unsigned lineno;
640#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200641 smallint cmd_type; /* CMD_xxx */
642#define CMD_NORMAL 0
643#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200644#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
645/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
646 * "export v=t*"
647 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200648# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000649#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200650#if ENABLE_HUSH_FUNCTIONS
651# define CMD_FUNCDEF 3
652#endif
653
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100654 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200655 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
656 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000657#if !BB_MMU
658 char *group_as_string;
659#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660#if ENABLE_HUSH_FUNCTIONS
661 struct function *child_func;
662/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200663 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000664 * When we execute "f1() {a;}" cmd, we create new function and clear
665 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200666 * When we execute "f1() {b;}", we notice that f1 exists,
667 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000668 * we put those fields back into cmd->xxx
669 * (struct function has ->parent_cmd ptr to facilitate that).
670 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
671 * Without this trick, loop would execute a;b;b;b;...
672 * instead of correct sequence a;b;a;b;...
673 * When command is freed, it severs the link
674 * (sets ->child_func->parent_cmd to NULL).
675 */
676#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000677 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000678/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
679 * and on execution these are substituted with their values.
680 * Substitution can make _several_ words out of one argv[n]!
681 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000682 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000683 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000684 struct redir_struct *redirects; /* I/O redirections */
685};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000686/* Is there anything in this command at all? */
687#define IS_NULL_CMD(cmd) \
688 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
689
Eric Andersen25f27032001-04-26 23:22:31 +0000690struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000691 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000692 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000693 int alive_cmds; /* number of commands running (not exited) */
694 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000695#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100696 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000697 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000698 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000699#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000700 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000701 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000702 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
703 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000704};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000705typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100706 PIPE_SEQ = 0,
707 PIPE_AND = 1,
708 PIPE_OR = 2,
709 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000710} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000711/* Is there anything in this pipe at all? */
712#define IS_NULL_PIPE(pi) \
713 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000714
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715/* This holds pointers to the various results of parsing */
716struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000717 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000718 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000719 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000720 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000721 /* last command in pipe (being constructed right now) */
722 struct command *command;
723 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000724 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200725 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000726#if !BB_MMU
727 o_string as_string;
728#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200729 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000730#if HAS_KEYWORDS
731 smallint ctx_res_w;
732 smallint ctx_inverted; /* "! cmd | cmd" */
733#if ENABLE_HUSH_CASE
734 smallint ctx_dsemicolon; /* ";;" seen */
735#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000736 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
737 int old_flag;
738 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000739 * example: "if pipe1; pipe2; then pipe3; fi"
740 * when we see "if" or "then", we malloc and copy current context,
741 * and make ->stack point to it. then we parse pipeN.
742 * when closing "then" / fi" / whatever is found,
743 * we move list_head into ->stack->command->group,
744 * copy ->stack into current context, and delete ->stack.
745 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000746 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000747 struct parse_context *stack;
748#endif
749};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200750enum {
751 MAYBE_ASSIGNMENT = 0,
752 DEFINITELY_ASSIGNMENT = 1,
753 NOT_ASSIGNMENT = 2,
754 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
755 WORD_IS_KEYWORD = 3,
756};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000757
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000758/* On program start, environ points to initial environment.
759 * putenv adds new pointers into it, unsetenv removes them.
760 * Neither of these (de)allocates the strings.
761 * setenv allocates new strings in malloc space and does putenv,
762 * and thus setenv is unusable (leaky) for shell's purposes */
763#define setenv(...) setenv_is_leaky_dont_use()
764struct variable {
765 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000766 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000767 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200768 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000769 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000770 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000771};
772
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000773enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000774 BC_BREAK = 1,
775 BC_CONTINUE = 2,
776};
777
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000778#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000779struct function {
780 struct function *next;
781 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000782 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000783 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200784# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200786# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000787};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000788#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000789
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000790
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100791/* set -/+o OPT support. (TODO: make it optional)
792 * bash supports the following opts:
793 * allexport off
794 * braceexpand on
795 * emacs on
796 * errexit off
797 * errtrace off
798 * functrace off
799 * hashall on
800 * histexpand off
801 * history on
802 * ignoreeof off
803 * interactive-comments on
804 * keyword off
805 * monitor on
806 * noclobber off
807 * noexec off
808 * noglob off
809 * nolog off
810 * notify off
811 * nounset off
812 * onecmd off
813 * physical off
814 * pipefail off
815 * posix off
816 * privileged off
817 * verbose off
818 * vi off
819 * xtrace off
820 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800821static const char o_opt_strings[] ALIGN1 =
822 "pipefail\0"
823 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200824 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800825#if ENABLE_HUSH_MODE_X
826 "xtrace\0"
827#endif
828 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100829enum {
830 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800831 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200832 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800833#if ENABLE_HUSH_MODE_X
834 OPT_O_XTRACE,
835#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100836 NUM_OPT_O
837};
838
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000840/* Sorted roughly by size (smaller offsets == smaller code) */
841struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000842 /* interactive_fd != 0 means we are an interactive shell.
843 * If we are, then saved_tty_pgrp can also be != 0, meaning
844 * that controlling tty is available. With saved_tty_pgrp == 0,
845 * job control still works, but terminal signals
846 * (^C, ^Z, ^Y, ^\) won't work at all, and background
847 * process groups can only be created with "cmd &".
848 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
849 * to give tty to the foreground process group,
850 * and will take it back when the group is stopped (^Z)
851 * or killed (^C).
852 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000853#if ENABLE_HUSH_INTERACTIVE
854 /* 'interactive_fd' is a fd# open to ctty, if we have one
855 * _AND_ if we decided to act interactively */
856 int interactive_fd;
857 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200858 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000859# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000860#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000861# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000862#endif
863#if ENABLE_FEATURE_EDITING
864 line_input_t *line_input_state;
865#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000866 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200867 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000868 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200869#if ENABLE_HUSH_RANDOM_SUPPORT
870 random_t random_gen;
871#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000872#if ENABLE_HUSH_JOB
873 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100874 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000875 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000876 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400877# define G_saved_tty_pgrp (G.saved_tty_pgrp)
878#else
879# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000880#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200881 /* How deeply are we in context where "set -e" is ignored */
882 int errexit_depth;
883 /* "set -e" rules (do we follow them correctly?):
884 * Exit if pipe, list, or compound command exits with a non-zero status.
885 * Shell does not exit if failed command is part of condition in
886 * if/while, part of && or || list except the last command, any command
887 * in a pipe but the last, or if the command's return value is being
888 * inverted with !. If a compound command other than a subshell returns a
889 * non-zero status because a command failed while -e was being ignored, the
890 * shell does not exit. A trap on ERR, if set, is executed before the shell
891 * exits [ERR is a bashism].
892 *
893 * If a compound command or function executes in a context where -e is
894 * ignored, none of the commands executed within are affected by the -e
895 * setting. If a compound command or function sets -e while executing in a
896 * context where -e is ignored, that setting does not have any effect until
897 * the compound command or the command containing the function call completes.
898 */
899
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100900 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100901#if ENABLE_HUSH_MODE_X
902# define G_x_mode (G.o_opt[OPT_O_XTRACE])
903#else
904# define G_x_mode 0
905#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200906#if ENABLE_HUSH_INTERACTIVE
907 smallint promptmode; /* 0: PS1, 1: PS2 */
908#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000909 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000910#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000911 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000912#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000913#if ENABLE_HUSH_FUNCTIONS
914 /* 0: outside of a function (or sourced file)
915 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000916 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000917 */
918 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200919# define G_flag_return_in_progress (G.flag_return_in_progress)
920#else
921# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000922#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000923 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100924 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000925 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200926 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200927 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000929 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000930 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100931# define G_global_args_malloced (G.global_args_malloced)
932#else
933# define G_global_args_malloced 0
934#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100935#if ENABLE_HUSH_BASH_COMPAT
936 int dead_job_exitcode; /* for "wait -n" */
937#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000938 /* how many non-NULL argv's we have. NB: $# + 1 */
939 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000940 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000941#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000942 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000943#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000944#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000945 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000946 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000947#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200948#if ENABLE_HUSH_GETOPTS
949 unsigned getopt_count;
950#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000951 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200952 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000953 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200954 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200955 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200956 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200957 unsigned var_nest_level;
958#if ENABLE_HUSH_FUNCTIONS
959# if ENABLE_HUSH_LOCAL
960 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200961# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200962 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000963#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000964 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200965#if ENABLE_HUSH_FAST
966 unsigned count_SIGCHLD;
967 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200968 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200969#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100970#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100971 unsigned lineno;
972 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100973#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200974 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200975 /* Which signals have non-DFL handler (even with no traps set)?
976 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200977 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200978 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200979 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200980 * Other than these two times, never modified.
981 */
982 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200983#if ENABLE_HUSH_JOB
984 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100985# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200986#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200987# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200988#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100989#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000990 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100991# define G_traps G.traps
992#else
993# define G_traps ((char**)NULL)
994#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200995 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100996#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000997 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100998#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +0200999#if ENABLE_HUSH_MODE_X
1000 unsigned x_mode_depth;
1001 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1002 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1003 * for all subsequent output.
1004 */
1005 int x_mode_fd;
1006 o_string x_mode_buf;
1007#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001008#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001009 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001010#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001011 struct sigaction sa;
Ron Yorstona81700b2019-04-15 10:48:29 +01001012#if BASH_EPOCH_VARS
1013 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1014#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001015#if ENABLE_FEATURE_EDITING
1016 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1017#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001018};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001019#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001020/* Not #defining name to G.name - this quickly gets unwieldy
1021 * (too many defines). Also, I actually prefer to see when a variable
1022 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001023#define INIT_G() do { \
1024 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001025 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1026 sigfillset(&G.sa.sa_mask); \
1027 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001028} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001029
1030
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001031/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001032static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001033#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001034static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001035#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001036static int builtin_eval(char **argv) FAST_FUNC;
1037static int builtin_exec(char **argv) FAST_FUNC;
1038static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001039#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001041#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001042#if ENABLE_HUSH_READONLY
1043static int builtin_readonly(char **argv) FAST_FUNC;
1044#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001045#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001046static int builtin_fg_bg(char **argv) FAST_FUNC;
1047static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001048#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001049#if ENABLE_HUSH_GETOPTS
1050static int builtin_getopts(char **argv) FAST_FUNC;
1051#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001052#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001054#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001055#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001056static int builtin_history(char **argv) FAST_FUNC;
1057#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001058#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001060#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001061#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001063#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001064#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001065static int builtin_printf(char **argv) FAST_FUNC;
1066#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001067static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001068#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001069static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001070#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001071#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001072static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001073#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001074static int builtin_shift(char **argv) FAST_FUNC;
1075static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001076#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001078#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001079#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001080static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001081#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001082#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001083static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001084#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001085#if ENABLE_HUSH_TIMES
1086static int builtin_times(char **argv) FAST_FUNC;
1087#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001088static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001089#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001090static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001091#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001092#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001093static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001094#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001095#if ENABLE_HUSH_KILL
1096static int builtin_kill(char **argv) FAST_FUNC;
1097#endif
1098#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001099static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001100#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001102static int builtin_break(char **argv) FAST_FUNC;
1103static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001105#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001106static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001107#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001108
1109/* Table of built-in functions. They can be forked or not, depending on
1110 * context: within pipes, they fork. As simple commands, they do not.
1111 * When used in non-forking context, they can change global variables
1112 * in the parent shell process. If forked, of course they cannot.
1113 * For example, 'unset foo | whatever' will parse and run, but foo will
1114 * still be set at the end. */
1115struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001116 const char *b_cmd;
1117 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001119 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001120# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001122# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#endif
1124};
1125
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001126static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001127 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001129#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001130 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001131#endif
1132#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001133 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001134#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001139 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1140 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001141 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001142#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001144#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001145#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001146 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001147#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001148#if ENABLE_HUSH_GETOPTS
1149 BLTIN("getopts" , builtin_getopts , NULL),
1150#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001151#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001153#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001154#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001155 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001156#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001157#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001159#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001160#if ENABLE_HUSH_KILL
1161 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1162#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001163#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001164 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001165#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001166#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001168#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001169#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001171#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001172#if ENABLE_HUSH_READONLY
1173 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1174#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001175#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001176 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001177#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001178#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001179 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001180#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001182#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001183 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001184#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001185#if ENABLE_HUSH_TIMES
1186 BLTIN("times" , builtin_times , NULL),
1187#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001188#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001189 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001190#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001191 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001192#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001193 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001194#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001195#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001196 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001197#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001198#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001199 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001200#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001201#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001202 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001203#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001204#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001205 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001206#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001207};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001208/* These builtins won't be used if we are on NOMMU and need to re-exec
1209 * (it's cheaper to run an external program in this case):
1210 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001211static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001212#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001213 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001214#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001215#if BASH_TEST2
1216 BLTIN("[[" , builtin_test , NULL),
1217#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001218#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001219 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001220#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001221#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001222 BLTIN("printf" , builtin_printf , NULL),
1223#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001224 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001225#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001226 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001227#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001228};
1229
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001230
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001231/* Debug printouts.
1232 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001233#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001234/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001235# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001236# define debug_enter() (G.debug_indent++)
1237# define debug_leave() (G.debug_indent--)
1238#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001239# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001240# define debug_enter() ((void)0)
1241# define debug_leave() ((void)0)
1242#endif
1243
1244#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001245# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001246#endif
1247
1248#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001249# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001250#endif
1251
Denys Vlasenko3675c372018-07-23 16:31:21 +02001252#ifndef debug_printf_heredoc
1253# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1254#endif
1255
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001256#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001257#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258#endif
1259
1260#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001261# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001262#endif
1263
1264#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266# define DEBUG_JOBS 1
1267#else
1268# define DEBUG_JOBS 0
1269#endif
1270
1271#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001272# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001273# define DEBUG_EXPAND 1
1274#else
1275# define DEBUG_EXPAND 0
1276#endif
1277
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001278#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001279# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001280#endif
1281
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001282#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284# define DEBUG_GLOB 1
1285#else
1286# define DEBUG_GLOB 0
1287#endif
1288
Denys Vlasenko2db74612017-07-07 22:07:28 +02001289#ifndef debug_printf_redir
1290# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1291#endif
1292
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001293#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001294# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001295#endif
1296
1297#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001298# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001299#endif
1300
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001301#ifndef debug_printf_prompt
1302# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1303#endif
1304
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001305#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001306# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001307# define DEBUG_CLEAN 1
1308#else
1309# define DEBUG_CLEAN 0
1310#endif
1311
1312#if DEBUG_EXPAND
1313static void debug_print_strings(const char *prefix, char **vv)
1314{
1315 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001316 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001317 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001318 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001319}
1320#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001321# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001322#endif
1323
1324
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001325/* Leak hunting. Use hush_leaktool.sh for post-processing.
1326 */
1327#if LEAK_HUNTING
1328static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001329{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001330 void *ptr = xmalloc((size + 0xff) & ~0xff);
1331 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1332 return ptr;
1333}
1334static void *xxrealloc(int lineno, void *ptr, size_t size)
1335{
1336 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1337 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1338 return ptr;
1339}
1340static char *xxstrdup(int lineno, const char *str)
1341{
1342 char *ptr = xstrdup(str);
1343 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1344 return ptr;
1345}
1346static void xxfree(void *ptr)
1347{
1348 fdprintf(2, "free %p\n", ptr);
1349 free(ptr);
1350}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001351# define xmalloc(s) xxmalloc(__LINE__, s)
1352# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1353# define xstrdup(s) xxstrdup(__LINE__, s)
1354# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001355#endif
1356
1357
1358/* Syntax and runtime errors. They always abort scripts.
1359 * In interactive use they usually discard unparsed and/or unexecuted commands
1360 * and return to the prompt.
1361 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1362 */
1363#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001364# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001365# define syntax_error(lineno, msg) syntax_error(msg)
1366# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1367# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1368# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1369# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001370#endif
1371
Denys Vlasenko39701202017-08-02 19:44:05 +02001372static void die_if_script(void)
1373{
1374 if (!G_interactive_fd) {
1375 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1376 xfunc_error_retval = G.last_exitcode;
1377 xfunc_die();
1378 }
1379}
1380
1381static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001382{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001383 va_list p;
1384
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001385#if HUSH_DEBUG >= 2
1386 bb_error_msg("hush.c:%u", lineno);
1387#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001388 va_start(p, fmt);
1389 bb_verror_msg(fmt, p, NULL);
1390 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001391 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001392}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001393
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001394static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001395{
1396 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001397 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001398 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001399 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001400 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001401}
1402
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001403static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001404{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001405 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001406 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001407}
1408
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001409static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001410{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001411 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001412//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1413// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001414}
1415
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001416static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001417{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001418 char msg[2] = { ch, '\0' };
1419 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001420}
1421
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001422static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001423{
1424 char msg[2];
1425 msg[0] = ch;
1426 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001427#if HUSH_DEBUG >= 2
1428 bb_error_msg("hush.c:%u", lineno);
1429#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001430 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001431 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001432}
1433
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001434#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001435# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001436# undef syntax_error
1437# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001438# undef syntax_error_unterm_ch
1439# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001440# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001441#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001442# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001443# define syntax_error(msg) syntax_error(__LINE__, msg)
1444# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1445# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1446# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1447# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001448#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001449
Denis Vlasenko552433b2009-04-04 19:29:21 +00001450
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001451#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001452static void cmdedit_update_prompt(void);
1453#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001454# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001455#endif
1456
1457
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001458/* Utility functions
1459 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001460/* Replace each \x with x in place, return ptr past NUL. */
1461static char *unbackslash(char *src)
1462{
Denys Vlasenko71885402009-09-24 01:44:13 +02001463 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001464 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001465 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001466 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001467 if (*src != '\0') {
1468 /* \x -> x */
1469 *dst++ = *src++;
1470 continue;
1471 }
1472 /* else: "\<nul>". Do not delete this backslash.
1473 * Testcase: eval 'echo ok\'
1474 */
1475 *dst++ = '\\';
1476 /* fallthrough */
1477 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001478 if ((*dst++ = *src++) == '\0')
1479 break;
1480 }
1481 return dst;
1482}
1483
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001484static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001485{
1486 int i;
1487 unsigned count1;
1488 unsigned count2;
1489 char **v;
1490
1491 v = strings;
1492 count1 = 0;
1493 if (v) {
1494 while (*v) {
1495 count1++;
1496 v++;
1497 }
1498 }
1499 count2 = 0;
1500 v = add;
1501 while (*v) {
1502 count2++;
1503 v++;
1504 }
1505 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1506 v[count1 + count2] = NULL;
1507 i = count2;
1508 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001509 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001510 return v;
1511}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001512#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001513static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1514{
1515 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1516 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1517 return ptr;
1518}
1519#define add_strings_to_strings(strings, add, need_to_dup) \
1520 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1521#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001522
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001523/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001524static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001525{
1526 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001527 v[0] = add;
1528 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001529 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001530}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001531#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001532static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1533{
1534 char **ptr = add_string_to_strings(strings, add);
1535 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1536 return ptr;
1537}
1538#define add_string_to_strings(strings, add) \
1539 xx_add_string_to_strings(__LINE__, strings, add)
1540#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001541
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001542static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001543{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001544 char **v;
1545
1546 if (!strings)
1547 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001548 v = strings;
1549 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001550 free(*v);
1551 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001552 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001553 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001554}
1555
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001556static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001557{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001558 int newfd;
1559 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001560 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1561 if (newfd >= 0) {
1562 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1563 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1564 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001565 if (errno == EBUSY)
1566 goto repeat;
1567 if (errno == EINTR)
1568 goto repeat;
1569 }
1570 return newfd;
1571}
1572
Denys Vlasenko657e9002017-07-30 23:34:04 +02001573static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001574{
1575 int newfd;
1576 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001577 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001578 if (newfd < 0) {
1579 if (errno == EBUSY)
1580 goto repeat;
1581 if (errno == EINTR)
1582 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001583 /* fd was not open? */
1584 if (errno == EBADF)
1585 return fd;
1586 xfunc_die();
1587 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001588 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1589 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001590 close(fd);
1591 return newfd;
1592}
1593
1594
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001595/* Manipulating HFILEs */
1596static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001597{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001598 HFILE *fp;
1599 int fd;
1600
1601 fd = STDIN_FILENO;
1602 if (name) {
1603 fd = open(name, O_RDONLY | O_CLOEXEC);
1604 if (fd < 0)
1605 return NULL;
1606 if (O_CLOEXEC == 0) /* ancient libc */
1607 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001608 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001609
1610 fp = xmalloc(sizeof(*fp));
1611 fp->is_stdin = (name == NULL);
1612 fp->fd = fd;
1613 fp->cur = fp->end = fp->buf;
1614 fp->next_hfile = G.HFILE_list;
1615 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001616 return fp;
1617}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001618static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001621 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001622 HFILE *cur = *pp;
1623 if (cur == fp) {
1624 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001625 break;
1626 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001627 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001629 if (fp->fd >= 0)
1630 close(fp->fd);
1631 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001632}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001633static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001634{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001635 int n;
1636
1637 if (fp->fd < 0) {
1638 /* Already saw EOF */
1639 return EOF;
1640 }
1641 /* Try to buffer more input */
1642 fp->cur = fp->buf;
1643 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1644 if (n < 0) {
1645 bb_perror_msg("read error");
1646 n = 0;
1647 }
1648 fp->end = fp->buf + n;
1649 if (n == 0) {
1650 /* EOF/error */
1651 close(fp->fd);
1652 fp->fd = -1;
1653 return EOF;
1654 }
1655 return (unsigned char)(*fp->cur++);
1656}
1657/* Inlined for common case of non-empty buffer.
1658 */
1659static ALWAYS_INLINE int hfgetc(HFILE *fp)
1660{
1661 if (fp->cur < fp->end)
1662 return (unsigned char)(*fp->cur++);
1663 /* Buffer empty */
1664 return refill_HFILE_and_getc(fp);
1665}
1666static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1667{
1668 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001669 while (fl) {
1670 if (fd == fl->fd) {
1671 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001672 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001673 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001674 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001675 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001676 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001677 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001678#if ENABLE_HUSH_MODE_X
1679 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1680 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1681 return 1; /* "found and moved" */
1682 }
1683#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001684 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001685}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001686#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001687static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001688{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001689 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001690 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001691 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001692 * It is disastrous if we share memory with a vforked parent.
1693 * I'm not sure we never come here after vfork.
1694 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001695 *
1696 * ">" instead of ">=": we don't close fd#0,
1697 * interactive shell uses hfopen(NULL) as stdin input
1698 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1699 * If we'd close it here, then e.g. interactive "set | sort"
1700 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001701 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001702 if (fl->fd > 0)
1703 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001704 close(fl->fd);
1705 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001706 }
1707}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001708#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001709static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001710{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001711 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001712 while (fl) {
1713 if (fl->fd == fd)
1714 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001715 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001716 }
1717 return 0;
1718}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001719
1720
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001721/* Helpers for setting new $n and restoring them back
1722 */
1723typedef struct save_arg_t {
1724 char *sv_argv0;
1725 char **sv_g_argv;
1726 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001727 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001728} save_arg_t;
1729
1730static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1731{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001732 sv->sv_argv0 = argv[0];
1733 sv->sv_g_argv = G.global_argv;
1734 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001735 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001736
1737 argv[0] = G.global_argv[0]; /* retain $0 */
1738 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001739 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001740
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001741 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001742}
1743
1744static void restore_G_args(save_arg_t *sv, char **argv)
1745{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001746#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001747 if (G.global_args_malloced) {
1748 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001749 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001750 while (*++pp) /* note: does not free $0 */
1751 free(*pp);
1752 free(G.global_argv);
1753 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001754#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001755 argv[0] = sv->sv_argv0;
1756 G.global_argv = sv->sv_g_argv;
1757 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001758 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001759}
1760
1761
Denis Vlasenkod5762932009-03-31 11:22:57 +00001762/* Basic theory of signal handling in shell
1763 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001764 * This does not describe what hush does, rather, it is current understanding
1765 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001766 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1767 *
1768 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1769 * is finished or backgrounded. It is the same in interactive and
1770 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001771 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001772 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001773 * backgrounds (i.e. stops) or kills all members of currently running
1774 * pipe.
1775 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001776 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001777 * or by SIGINT in interactive shell.
1778 *
1779 * Trap handlers will execute even within trap handlers. (right?)
1780 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001781 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1782 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001783 *
1784 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001785 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001786 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001787 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001788 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001789 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001790 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001791 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001792 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001793 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001794 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001795 *
1796 * SIGQUIT: ignore
1797 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001798 * SIGHUP (interactive):
1799 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001800 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001801 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1802 * that all pipe members are stopped. Try this in bash:
1803 * while :; do :; done - ^Z does not background it
1804 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001805 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001806 * of the command line, show prompt. NB: ^C does not send SIGINT
1807 * to interactive shell while shell is waiting for a pipe,
1808 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001809 * Example 1: this waits 5 sec, but does not execute ls:
1810 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1811 * Example 2: this does not wait and does not execute ls:
1812 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1813 * Example 3: this does not wait 5 sec, but executes ls:
1814 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001815 * Example 4: this does not wait and does not execute ls:
1816 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 *
1818 * (What happens to signals which are IGN on shell start?)
1819 * (What happens with signal mask on shell start?)
1820 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001821 * Old implementation
1822 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001823 * We use in-kernel pending signal mask to determine which signals were sent.
1824 * We block all signals which we don't want to take action immediately,
1825 * i.e. we block all signals which need to have special handling as described
1826 * above, and all signals which have traps set.
1827 * After each pipe execution, we extract any pending signals via sigtimedwait()
1828 * and act on them.
1829 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001830 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001831 * sigset_t blocked_set: current blocked signal set
1832 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001833 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001834 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001835 * "trap 'cmd' SIGxxx":
1836 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001837 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001838 * unblock signals with special interactive handling
1839 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001840 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001841 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001842 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001843 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001844 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001845 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001846 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001847 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001848 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001849 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001850 * Standard says "When a subshell is entered, traps that are not being ignored
1851 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001852 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001853 *
1854 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001855 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001856 * masked signals are not visible!
1857 *
1858 * New implementation
1859 * ==================
1860 * We record each signal we are interested in by installing signal handler
1861 * for them - a bit like emulating kernel pending signal mask in userspace.
1862 * We are interested in: signals which need to have special handling
1863 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001864 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001865 * After each pipe execution, we extract any pending signals
1866 * and act on them.
1867 *
1868 * unsigned special_sig_mask: a mask of shell-special signals.
1869 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1870 * char *traps[sig] if trap for sig is set (even if it's '').
1871 * sigset_t pending_set: set of sigs we received.
1872 *
1873 * "trap - SIGxxx":
1874 * if sig is in special_sig_mask, set handler back to:
1875 * record_pending_signo, or to IGN if it's a tty stop signal
1876 * if sig is in fatal_sig_mask, set handler back to sigexit.
1877 * else: set handler back to SIG_DFL
1878 * "trap 'cmd' SIGxxx":
1879 * set handler to record_pending_signo.
1880 * "trap '' SIGxxx":
1881 * set handler to SIG_IGN.
1882 * after [v]fork, if we plan to be a shell:
1883 * set signals with special interactive handling to SIG_DFL
1884 * (because child shell is not interactive),
1885 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1886 * after [v]fork, if we plan to exec:
1887 * POSIX says fork clears pending signal mask in child - no need to clear it.
1888 *
1889 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1890 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1891 *
1892 * Note (compat):
1893 * Standard says "When a subshell is entered, traps that are not being ignored
1894 * are set to the default actions". bash interprets it so that traps which
1895 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001896 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001897enum {
1898 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001899 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001900 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001901 | (1 << SIGHUP)
1902 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001904#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001905 | (1 << SIGTTIN)
1906 | (1 << SIGTTOU)
1907 | (1 << SIGTSTP)
1908#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001909 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001910};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001911
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001913{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001914 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001915#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001916 if (sig == SIGCHLD) {
1917 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001918//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001919 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001920#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001921}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001922
Denys Vlasenko0806e402011-05-12 23:06:20 +02001923static sighandler_t install_sighandler(int sig, sighandler_t handler)
1924{
1925 struct sigaction old_sa;
1926
1927 /* We could use signal() to install handlers... almost:
1928 * except that we need to mask ALL signals while handlers run.
1929 * I saw signal nesting in strace, race window isn't small.
1930 * SA_RESTART is also needed, but in Linux, signal()
1931 * sets SA_RESTART too.
1932 */
1933 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1934 /* sigfillset(&G.sa.sa_mask); - already done */
1935 /* G.sa.sa_flags = SA_RESTART; - already done */
1936 G.sa.sa_handler = handler;
1937 sigaction(sig, &G.sa, &old_sa);
1938 return old_sa.sa_handler;
1939}
1940
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001941static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001942
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001943static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001944static void restore_ttypgrp_and__exit(void)
1945{
1946 /* xfunc has failed! die die die */
1947 /* no EXIT traps, this is an escape hatch! */
1948 G.exiting = 1;
1949 hush_exit(xfunc_error_retval);
1950}
1951
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001952#if ENABLE_HUSH_JOB
1953
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001954/* Needed only on some libc:
1955 * It was observed that on exit(), fgetc'ed buffered data
1956 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1957 * With the net effect that even after fork(), not vfork(),
1958 * exit() in NOEXECed applet in "sh SCRIPT":
1959 * noexec_applet_here
1960 * echo END_OF_SCRIPT
1961 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1962 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001963 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001964 * and in `cmd` handling.
1965 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1966 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001967static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001968static void fflush_and__exit(void)
1969{
1970 fflush_all();
1971 _exit(xfunc_error_retval);
1972}
1973
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001974/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001975# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001976/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001977# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001978
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001979/* Restores tty foreground process group, and exits.
1980 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001981 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001982 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001983 * We also call it if xfunc is exiting.
1984 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001985static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001986static void sigexit(int sig)
1987{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001988 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001989 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001990 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1991 /* Disable all signals: job control, SIGPIPE, etc.
1992 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1993 */
1994 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001995 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001996 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001997
1998 /* Not a signal, just exit */
1999 if (sig <= 0)
2000 _exit(- sig);
2001
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002002 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002003}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002004#else
2005
Denys Vlasenko8391c482010-05-22 17:50:43 +02002006# define disable_restore_tty_pgrp_on_exit() ((void)0)
2007# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002008
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002009#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002010
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002011static sighandler_t pick_sighandler(unsigned sig)
2012{
2013 sighandler_t handler = SIG_DFL;
2014 if (sig < sizeof(unsigned)*8) {
2015 unsigned sigmask = (1 << sig);
2016
2017#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002018 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002019 if (G_fatal_sig_mask & sigmask)
2020 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002021 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002022#endif
2023 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002024 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002025 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002026 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002027 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002028 * in an endless loop when we try to do some
2029 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002030 */
2031 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2032 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002033 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002034 }
2035 return handler;
2036}
2037
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002038/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002039static void hush_exit(int exitcode)
2040{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002041#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2042 save_history(G.line_input_state);
2043#endif
2044
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002045 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002046 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002047 char *argv[3];
2048 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002049 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002050 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002051 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002052 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002053 * "trap" will still show it, if executed
2054 * in the handler */
2055 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002056 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002057
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002058#if ENABLE_FEATURE_CLEAN_UP
2059 {
2060 struct variable *cur_var;
2061 if (G.cwd != bb_msg_unknown)
2062 free((char*)G.cwd);
2063 cur_var = G.top_var;
2064 while (cur_var) {
2065 struct variable *tmp = cur_var;
2066 if (!cur_var->max_len)
2067 free(cur_var->varstr);
2068 cur_var = cur_var->next;
2069 free(tmp);
2070 }
2071 }
2072#endif
2073
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002074 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002075#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002076 sigexit(- (exitcode & 0xff));
2077#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002078 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002079#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002080}
2081
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002082
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002083//TODO: return a mask of ALL handled sigs?
2084static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002085{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002086 int last_sig = 0;
2087
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002088 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002089 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002090
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002091 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002092 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002093 sig = 0;
2094 do {
2095 sig++;
2096 if (sigismember(&G.pending_set, sig)) {
2097 sigdelset(&G.pending_set, sig);
2098 goto got_sig;
2099 }
2100 } while (sig < NSIG);
2101 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002102 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002103 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002104 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002105 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002106 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002107 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002108 char *argv[3];
2109 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002110 argv[1] = xstrdup(G_traps[sig]);
2111 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002112 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002113 save_rcode = G.last_exitcode;
2114 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002115 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002116//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002117 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002118 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002119 } /* else: "" trap, ignoring signal */
2120 continue;
2121 }
2122 /* not a trap: special action */
2123 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002124 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002125 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002126 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002127 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002128 break;
2129#if ENABLE_HUSH_JOB
2130 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002131//TODO: why are we doing this? ash and dash don't do this,
2132//they have no handler for SIGHUP at all,
2133//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002134 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002135 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002136 /* bash is observed to signal whole process groups,
2137 * not individual processes */
2138 for (job = G.job_list; job; job = job->next) {
2139 if (job->pgrp <= 0)
2140 continue;
2141 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2142 if (kill(- job->pgrp, SIGHUP) == 0)
2143 kill(- job->pgrp, SIGCONT);
2144 }
2145 sigexit(SIGHUP);
2146 }
2147#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002148#if ENABLE_HUSH_FAST
2149 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002150 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002151 G.count_SIGCHLD++;
2152//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2153 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002154 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002155 * This simplifies wait builtin a bit.
2156 */
2157 break;
2158#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002159 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002160 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002161 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002162 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002163 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002164 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002165 * in interactive shell, because TERM is ignored.
2166 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002167 break;
2168 }
2169 }
2170 return last_sig;
2171}
2172
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002173
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002174static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002175{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002176 if (force || G.cwd == NULL) {
2177 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2178 * we must not try to free(bb_msg_unknown) */
2179 if (G.cwd == bb_msg_unknown)
2180 G.cwd = NULL;
2181 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2182 if (!G.cwd)
2183 G.cwd = bb_msg_unknown;
2184 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002185 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002186}
2187
Denis Vlasenko83506862007-11-23 13:11:42 +00002188
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002189/*
2190 * Shell and environment variable support
2191 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002192static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002193{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002194 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002195 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002196
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002197 pp = &G.top_var;
2198 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002200 return pp;
2201 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 }
2203 return NULL;
2204}
2205
Denys Vlasenko03dad222010-01-12 23:29:57 +01002206static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002207{
Denys Vlasenko29082232010-07-16 13:52:32 +02002208 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002209 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002210
2211 if (G.expanded_assignments) {
2212 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002213 while (*cpp) {
2214 char *cp = *cpp;
2215 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2216 return cp + len + 1;
2217 cpp++;
2218 }
2219 }
2220
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002221 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002222 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002223 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002224
Denys Vlasenkodea47882009-10-09 15:40:49 +02002225 if (strcmp(name, "PPID") == 0)
2226 return utoa(G.root_ppid);
2227 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002228#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002229 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002230 return utoa(next_random(&G.random_gen));
2231#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002232#if BASH_EPOCH_VARS
2233 {
2234 const char *fmt = NULL;
2235 if (strcmp(name, "EPOCHSECONDS") == 0)
2236 fmt = "%lu";
2237 else if (strcmp(name, "EPOCHREALTIME") == 0)
2238 fmt = "%lu.%06u";
2239 if (fmt) {
2240 struct timeval tv;
2241 gettimeofday(&tv, NULL);
2242 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2243 (unsigned)tv.tv_usec);
2244 return G.epoch_buf;
2245 }
2246 }
2247#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248 return NULL;
2249}
2250
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002251static void handle_changed_special_names(const char *name, unsigned name_len)
2252{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002253 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2254 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2255 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002256 cmdedit_update_prompt();
2257 return;
2258 }
2259
2260 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2261 && name_len == 6
2262 ) {
2263#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002264 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002265 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002266 return;
2267 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002268#endif
2269#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002270 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002271 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002272 return;
2273 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002274#endif
2275 }
2276}
2277
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002278/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002279 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002280 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002281#define SETFLAG_EXPORT (1 << 0)
2282#define SETFLAG_UNEXPORT (1 << 1)
2283#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002284#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002285static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002286{
Denys Vlasenko61407802018-04-04 21:14:28 +02002287 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002288 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002289 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002290 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002292 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002293
Denis Vlasenko950bd722009-04-21 11:23:56 +00002294 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002295 if (HUSH_DEBUG && !eq_sign)
2296 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002297
Denis Vlasenko950bd722009-04-21 11:23:56 +00002298 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002299 cur_pp = &G.top_var;
2300 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002301 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002302 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002303 continue;
2304 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002305
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002306 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002307 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002308 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002309 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002310//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2311//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002312 return -1;
2313 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002314 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002315 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2316 *eq_sign = '\0';
2317 unsetenv(str);
2318 *eq_sign = '=';
2319 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002320 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002321 /* bash 3.2.33(1) and exported vars:
2322 * # export z=z
2323 * # f() { local z=a; env | grep ^z; }
2324 * # f
2325 * z=a
2326 * # env | grep ^z
2327 * z=z
2328 */
2329 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002330 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002331 /* New variable is local ("local VAR=VAL" or
2332 * "VAR=VAL cmd")
2333 * and existing one is global, or local
2334 * on a lower level that new one.
2335 * Remove it from global variable list:
2336 */
2337 *cur_pp = cur->next;
2338 if (G.shadowed_vars_pp) {
2339 /* Save in "shadowed" list */
2340 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2341 cur->flg_export ? "exported " : "",
2342 cur->varstr, cur->var_nest_level, str, local_lvl
2343 );
2344 cur->next = *G.shadowed_vars_pp;
2345 *G.shadowed_vars_pp = cur;
2346 } else {
2347 /* Came from pseudo_exec_argv(), no need to save: delete it */
2348 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2349 cur->flg_export ? "exported " : "",
2350 cur->varstr, cur->var_nest_level, str, local_lvl
2351 );
2352 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2353 free_me = cur->varstr; /* then free it later */
2354 free(cur);
2355 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002356 break;
2357 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002358
Denis Vlasenko950bd722009-04-21 11:23:56 +00002359 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002360 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002361 free_and_exp:
2362 free(str);
2363 goto exp;
2364 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002365
2366 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002367 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002368 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002369 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002370 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002371 strcpy(cur->varstr, str);
2372 goto free_and_exp;
2373 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002374 /* Can't reuse */
2375 cur->max_len = 0;
2376 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002377 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002378 /* max_len == 0 signifies "malloced" var, which we can
2379 * (and have to) free. But we can't free(cur->varstr) here:
2380 * if cur->flg_export is 1, it is in the environment.
2381 * We should either unsetenv+free, or wait until putenv,
2382 * then putenv(new)+free(old).
2383 */
2384 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002385 goto set_str_and_exp;
2386 }
2387
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002388 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002389 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002390 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002391 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002392 cur->next = *cur_pp;
2393 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002394
2395 set_str_and_exp:
2396 cur->varstr = str;
2397 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002398#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002399 if (flags & SETFLAG_MAKE_RO) {
2400 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002401 }
2402#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002403 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002404 cur->flg_export = 1;
2405 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002406 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002407 cur->flg_export = 0;
2408 /* unsetenv was already done */
2409 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002410 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002411 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002412 i = putenv(cur->varstr);
2413 /* only now we can free old exported malloced string */
2414 free(free_me);
2415 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002416 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002417 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002418 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002419
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002420 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002421
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002422 return 0;
2423}
2424
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002425static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2426{
2427 char *var = xasprintf("%s=%s", name, val);
2428 set_local_var(var, /*flag:*/ 0);
2429}
2430
Denys Vlasenko6db47842009-09-05 20:15:17 +02002431/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002432static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002433{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002434 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002435}
2436
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002437#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002438static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002439{
2440 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002441 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002442
Denys Vlasenko61407802018-04-04 21:14:28 +02002443 cur_pp = &G.top_var;
2444 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002445 if (strncmp(cur->varstr, name, name_len) == 0
2446 && cur->varstr[name_len] == '='
2447 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002448 if (cur->flg_read_only) {
2449 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002450 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002452
Denys Vlasenko61407802018-04-04 21:14:28 +02002453 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002454 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2455 bb_unsetenv(cur->varstr);
2456 if (!cur->max_len)
2457 free(cur->varstr);
2458 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002459
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002460 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002461 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002462 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002464
2465 /* Handle "unset PS1" et al even if did not find the variable to unset */
2466 handle_changed_special_names(name, name_len);
2467
Mike Frysingerd690f682009-03-30 06:50:54 +00002468 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002469}
2470
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002471static int unset_local_var(const char *name)
2472{
2473 return unset_local_var_len(name, strlen(name));
2474}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002475#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002476
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002477
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002478/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002479 * Helpers for "var1=val1 var2=val2 cmd" feature
2480 */
2481static void add_vars(struct variable *var)
2482{
2483 struct variable *next;
2484
2485 while (var) {
2486 next = var->next;
2487 var->next = G.top_var;
2488 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002489 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002490 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002491 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002492 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002493 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002494 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002495 var = next;
2496 }
2497}
2498
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002499/* We put strings[i] into variable table and possibly putenv them.
2500 * If variable is read only, we can free the strings[i]
2501 * which attempts to overwrite it.
2502 * The strings[] vector itself is freed.
2503 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002504static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002505{
2506 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002507
2508 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002509 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002510
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002511 s = strings;
2512 while (*s) {
2513 struct variable *var_p;
2514 struct variable **var_pp;
2515 char *eq;
2516
2517 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002518 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002519 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002520 var_pp = get_ptr_to_local_var(*s, eq - *s);
2521 if (var_pp) {
2522 var_p = *var_pp;
2523 if (var_p->flg_read_only) {
2524 char **p;
2525 bb_error_msg("%s: readonly variable", *s);
2526 /*
2527 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2528 * If VAR is readonly, leaving it in the list
2529 * after asssignment error (msg above)
2530 * causes doubled error message later, on unset.
2531 */
2532 debug_printf_env("removing/freeing '%s' element\n", *s);
2533 free(*s);
2534 p = s;
2535 do { *p = p[1]; p++; } while (*p);
2536 goto next;
2537 }
2538 /* below, set_local_var() with nest level will
2539 * "shadow" (remove) this variable from
2540 * global linked list.
2541 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002542 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002543 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2544 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002545 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002546 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002547 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002548 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002549}
2550
2551
2552/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002553 * Unicode helper
2554 */
2555static void reinit_unicode_for_hush(void)
2556{
2557 /* Unicode support should be activated even if LANG is set
2558 * _during_ shell execution, not only if it was set when
2559 * shell was started. Therefore, re-check LANG every time:
2560 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002561 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2562 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002563 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002564 const char *s = get_local_var_value("LC_ALL");
2565 if (!s) s = get_local_var_value("LC_CTYPE");
2566 if (!s) s = get_local_var_value("LANG");
2567 reinit_unicode(s);
2568 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002569}
2570
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002571/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002572 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002573 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002574
2575#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002576/* To test correct lineedit/interactive behavior, type from command line:
2577 * echo $P\
2578 * \
2579 * AT\
2580 * H\
2581 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002582 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002583 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002584# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002585static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002586{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002587 G.PS1 = get_local_var_value("PS1");
2588 if (G.PS1 == NULL)
2589 G.PS1 = "";
2590 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002591 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002592 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002594# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002595static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002596{
2597 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002598
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002599 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002600
2601 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2602 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002603 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002604 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2605 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002606 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002607 /* bash uses $PWD value, even if it is set by user.
2608 * It uses current dir only if PWD is unset.
2609 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002610 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002611 }
2612 prompt_str = G.PS1;
2613 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002614 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002615 return prompt_str;
2616}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002617static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002618{
2619 int r;
2620 const char *prompt_str;
2621
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002622 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002623# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002624 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002625 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002626 if (G.flag_SIGINT) {
2627 /* There was ^C'ed, make it look prettier: */
2628 bb_putchar('\n');
2629 G.flag_SIGINT = 0;
2630 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002631 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002632 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002633 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002634 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002635 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002636 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002637 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002638 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002639 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002640 if (r != 0 && !G.flag_SIGINT)
2641 break;
2642 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002643 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2644 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002645 G.last_exitcode = 128 + SIGINT;
2646 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002647 if (r < 0) {
2648 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002649 i->p = NULL;
2650 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002651 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002653 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002654 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002655# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002656 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002657 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002658 if (i->last_char == '\0' || i->last_char == '\n') {
2659 /* Why check_and_run_traps here? Try this interactively:
2660 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2661 * $ <[enter], repeatedly...>
2662 * Without check_and_run_traps, handler never runs.
2663 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002664 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002665 fputs(prompt_str, stdout);
2666 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002667 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002668//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002669 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002670 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2671 * no ^C masking happens during fgetc, no special code for ^C:
2672 * it generates SIGINT as usual.
2673 */
2674 check_and_run_traps();
2675 if (G.flag_SIGINT)
2676 G.last_exitcode = 128 + SIGINT;
2677 if (r != '\0')
2678 break;
2679 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002680 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002681# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002682}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002683/* This is the magic location that prints prompts
2684 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002685static int fgetc_interactive(struct in_str *i)
2686{
2687 int ch;
2688 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002689 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002690 /* Returns first char (or EOF), the rest is in i->p[] */
2691 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002692 G.promptmode = 1; /* PS2 */
2693 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002694 } else {
2695 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002696 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002697 }
2698 return ch;
2699}
2700#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002701static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002702{
2703 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002704 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002705 return ch;
2706}
2707#endif /* INTERACTIVE */
2708
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002709static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002710{
2711 int ch;
2712
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002713 if (!i->file) {
2714 /* string-based in_str */
2715 ch = (unsigned char)*i->p;
2716 if (ch != '\0') {
2717 i->p++;
2718 i->last_char = ch;
2719 return ch;
2720 }
2721 return EOF;
2722 }
2723
2724 /* FILE-based in_str */
2725
Denys Vlasenko4074d492016-09-30 01:49:53 +02002726#if ENABLE_FEATURE_EDITING
2727 /* This can be stdin, check line editing char[] buffer */
2728 if (i->p && *i->p != '\0') {
2729 ch = (unsigned char)*i->p++;
2730 goto out;
2731 }
2732#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002733 /* peek_buf[] is an int array, not char. Can contain EOF. */
2734 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002735 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002736 int ch2 = i->peek_buf[1];
2737 i->peek_buf[0] = ch2;
2738 if (ch2 == 0) /* very likely, avoid redundant write */
2739 goto out;
2740 i->peek_buf[1] = 0;
2741 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002742 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002743
Denys Vlasenko4074d492016-09-30 01:49:53 +02002744 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002745 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002746 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002747 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002748#if ENABLE_HUSH_LINENO_VAR
2749 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002750 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002751 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2752 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002753#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002754 return ch;
2755}
2756
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002757static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002758{
2759 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002760
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002761 if (!i->file) {
2762 /* string-based in_str */
2763 /* Doesn't report EOF on NUL. None of the callers care. */
2764 return (unsigned char)*i->p;
2765 }
2766
2767 /* FILE-based in_str */
2768
Denys Vlasenko4074d492016-09-30 01:49:53 +02002769#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002770 /* This can be stdin, check line editing char[] buffer */
2771 if (i->p && *i->p != '\0')
2772 return (unsigned char)*i->p;
2773#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002774 /* peek_buf[] is an int array, not char. Can contain EOF. */
2775 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002776 if (ch != 0)
2777 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002778
Denys Vlasenko4074d492016-09-30 01:49:53 +02002779 /* Need to get a new char */
2780 ch = fgetc_interactive(i);
2781 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2782
2783 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2784#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2785 if (i->p) {
2786 i->p -= 1;
2787 return ch;
2788 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002789#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002790 i->peek_buf[0] = ch;
2791 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002792 return ch;
2793}
2794
Denys Vlasenko4074d492016-09-30 01:49:53 +02002795/* Only ever called if i_peek() was called, and did not return EOF.
2796 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2797 * not end-of-line. Therefore we never need to read a new editing line here.
2798 */
2799static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002800{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002801 int ch;
2802
2803 /* There are two cases when i->p[] buffer exists.
2804 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002805 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002806 * In both cases, we know that i->p[0] exists and not NUL, and
2807 * the peek2 result is in i->p[1].
2808 */
2809 if (i->p)
2810 return (unsigned char)i->p[1];
2811
2812 /* Now we know it is a file-based in_str. */
2813
2814 /* peek_buf[] is an int array, not char. Can contain EOF. */
2815 /* Is there 2nd char? */
2816 ch = i->peek_buf[1];
2817 if (ch == 0) {
2818 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002819 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002820 i->peek_buf[1] = ch;
2821 }
2822
2823 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2824 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002825}
2826
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002827static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2828{
2829 for (;;) {
2830 int ch, ch2;
2831
2832 ch = i_getch(input);
2833 if (ch != '\\')
2834 return ch;
2835 ch2 = i_peek(input);
2836 if (ch2 != '\n')
2837 return ch;
2838 /* backslash+newline, skip it */
2839 i_getch(input);
2840 }
2841}
2842
2843/* Note: this function _eats_ \<newline> pairs, safe to use plain
2844 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2845 */
2846static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2847{
2848 for (;;) {
2849 int ch, ch2;
2850
2851 ch = i_peek(input);
2852 if (ch != '\\')
2853 return ch;
2854 ch2 = i_peek2(input);
2855 if (ch2 != '\n')
2856 return ch;
2857 /* backslash+newline, skip it */
2858 i_getch(input);
2859 i_getch(input);
2860 }
2861}
2862
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002863static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002864{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002865 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002866 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002867 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002868}
2869
2870static void setup_string_in_str(struct in_str *i, const char *s)
2871{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002872 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002873 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002874 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002875}
2876
2877
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002878/*
2879 * o_string support
2880 */
2881#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002882
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002883static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002884{
2885 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002886 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002887 if (o->data)
2888 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002889}
2890
Denys Vlasenko18567402018-07-20 17:51:31 +02002891static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002892{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002893 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002894 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002895}
2896
Denys Vlasenko18567402018-07-20 17:51:31 +02002897static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002898{
2899 free(o->data);
2900}
2901
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002902static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002903{
2904 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002905 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002906 o->data = xrealloc(o->data, 1 + o->maxlen);
2907 }
2908}
2909
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002910static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002911{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002912 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002913 if (o->length < o->maxlen) {
2914 /* likely. avoid o_grow_by() call */
2915 add:
2916 o->data[o->length] = ch;
2917 o->length++;
2918 o->data[o->length] = '\0';
2919 return;
2920 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002921 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002922 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002923}
2924
Denys Vlasenko657086a2016-09-29 18:07:42 +02002925#if 0
2926/* Valid only if we know o_string is not empty */
2927static void o_delchr(o_string *o)
2928{
2929 o->length--;
2930 o->data[o->length] = '\0';
2931}
2932#endif
2933
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002934static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002935{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002936 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002937 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002938 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002939}
2940
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002941static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002942{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002943 o_addblock(o, str, strlen(str));
2944}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002945
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002946static void o_addstr_with_NUL(o_string *o, const char *str)
2947{
2948 o_addblock(o, str, strlen(str) + 1);
2949}
2950
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002951#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002952static void nommu_addchr(o_string *o, int ch)
2953{
2954 if (o)
2955 o_addchr(o, ch);
2956}
2957#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002958# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002959#endif
2960
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002961#if ENABLE_HUSH_MODE_X
2962static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002963{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002964 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002965}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002966static void x_mode_addstr(const char *str)
2967{
2968 o_addstr(&G.x_mode_buf, str);
2969}
2970static void x_mode_addblock(const char *str, int len)
2971{
2972 o_addblock(&G.x_mode_buf, str, len);
2973}
2974static void x_mode_prefix(void)
2975{
2976 int n = G.x_mode_depth;
2977 do x_mode_addchr('+'); while (--n >= 0);
2978}
2979static void x_mode_flush(void)
2980{
2981 int len = G.x_mode_buf.length;
2982 if (len <= 0)
2983 return;
2984 if (G.x_mode_fd > 0) {
2985 G.x_mode_buf.data[len] = '\n';
2986 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2987 }
2988 G.x_mode_buf.length = 0;
2989}
2990#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002991
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002992/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002993 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002994 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2995 * Apparently, on unquoted $v bash still does globbing
2996 * ("v='*.txt'; echo $v" prints all .txt files),
2997 * but NOT brace expansion! Thus, there should be TWO independent
2998 * quoting mechanisms on $v expansion side: one protects
2999 * $v from brace expansion, and other additionally protects "$v" against globbing.
3000 * We have only second one.
3001 */
3002
Denys Vlasenko9e800222010-10-03 14:28:04 +02003003#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003004# define MAYBE_BRACES "{}"
3005#else
3006# define MAYBE_BRACES ""
3007#endif
3008
Eric Andersen25f27032001-04-26 23:22:31 +00003009/* My analysis of quoting semantics tells me that state information
3010 * is associated with a destination, not a source.
3011 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003012static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003013{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003014 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003015 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003016 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003017 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003018 o_grow_by(o, sz);
3019 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003020 o->data[o->length] = '\\';
3021 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003022 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003023 o->data[o->length] = ch;
3024 o->length++;
3025 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003026}
3027
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003028static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003029{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003030 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003031 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3032 && strchr("*?[\\" MAYBE_BRACES, ch)
3033 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003034 sz++;
3035 o->data[o->length] = '\\';
3036 o->length++;
3037 }
3038 o_grow_by(o, sz);
3039 o->data[o->length] = ch;
3040 o->length++;
3041 o->data[o->length] = '\0';
3042}
3043
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003044static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003045{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003046 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003047 char ch;
3048 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003049 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003050 if (ordinary_cnt > len) /* paranoia */
3051 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003052 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003053 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003054 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003055 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003056 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003057
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003058 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003059 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003060 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003061 sz++;
3062 o->data[o->length] = '\\';
3063 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003064 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003065 o_grow_by(o, sz);
3066 o->data[o->length] = ch;
3067 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003068 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003069 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003070}
3071
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003072static void o_addQblock(o_string *o, const char *str, int len)
3073{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003074 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003075 o_addblock(o, str, len);
3076 return;
3077 }
3078 o_addqblock(o, str, len);
3079}
3080
Denys Vlasenko38292b62010-09-05 14:49:40 +02003081static void o_addQstr(o_string *o, const char *str)
3082{
3083 o_addQblock(o, str, strlen(str));
3084}
3085
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003086/* A special kind of o_string for $VAR and `cmd` expansion.
3087 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003088 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003089 * list[i] contains an INDEX (int!) into this string data.
3090 * It means that if list[] needs to grow, data needs to be moved higher up
3091 * but list[i]'s need not be modified.
3092 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003093 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003094 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3095 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003096#if DEBUG_EXPAND || DEBUG_GLOB
3097static void debug_print_list(const char *prefix, o_string *o, int n)
3098{
3099 char **list = (char**)o->data;
3100 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3101 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003102
3103 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003104 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 +02003105 prefix, list, n, string_start, o->length, o->maxlen,
3106 !!(o->o_expflags & EXP_FLAG_GLOB),
3107 o->has_quoted_part,
3108 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003109 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003110 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003111 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3112 o->data + (int)(uintptr_t)list[i] + string_start,
3113 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003114 i++;
3115 }
3116 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003117 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003118 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003119 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003120 }
3121}
3122#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003123# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003124#endif
3125
3126/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3127 * in list[n] so that it points past last stored byte so far.
3128 * It returns n+1. */
3129static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003130{
3131 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003132 int string_start;
3133 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003134
3135 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003136 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3137 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003138 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003139 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003140 /* list[n] points to string_start, make space for 16 more pointers */
3141 o->maxlen += 0x10 * sizeof(list[0]);
3142 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003143 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003144 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003145 /*
3146 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3147 * check. (grep for -prev-ifs-check-).
3148 * Ensure that argv[-1][last] is not garbage
3149 * but zero bytes, to save index check there.
3150 */
3151 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003152 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003153 } else {
3154 debug_printf_list("list[%d]=%d string_start=%d\n",
3155 n, string_len, string_start);
3156 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003157 } else {
3158 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003159 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3160 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003161 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3162 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003163 o->has_empty_slot = 0;
3164 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003165 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003166 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003167 return n + 1;
3168}
3169
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003170/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003171static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003172{
3173 char **list = (char**)o->data;
3174 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3175
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003176 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003177}
3178
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003179/*
3180 * Globbing routines.
3181 *
3182 * Most words in commands need to be globbed, even ones which are
3183 * (single or double) quoted. This stems from the possiblity of
3184 * constructs like "abc"* and 'abc'* - these should be globbed.
3185 * Having a different code path for fully-quoted strings ("abc",
3186 * 'abc') would only help performance-wise, but we still need
3187 * code for partially-quoted strings.
3188 *
3189 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003190 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003191 * to a string, then globbed, and if globbing does not match anything,
3192 * it is used verbatim". Here are two examples where it fails:
3193 *
3194 * echo 'b\*'?
3195 *
3196 * The globbing can't be avoided (because of '?' at the end).
3197 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3198 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003199 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003200 * Now, look at this:
3201 *
3202 * v='\\\*'; echo b$v?
3203 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003204 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003205 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003206 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003207 *
3208 * ash implements this by having an encoded representation of the word
3209 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3210 * Glob pattern is derived from it. If glob fails, the decision what result
3211 * should be is made using that encoded representation. Not glob pattern.
3212 */
3213
Denys Vlasenko9e800222010-10-03 14:28:04 +02003214#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003215/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3216 * first, it processes even {a} (no commas), second,
3217 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003218 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003219 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003220
3221/* Helper */
3222static int glob_needed(const char *s)
3223{
3224 while (*s) {
3225 if (*s == '\\') {
3226 if (!s[1])
3227 return 0;
3228 s += 2;
3229 continue;
3230 }
3231 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3232 return 1;
3233 s++;
3234 }
3235 return 0;
3236}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003237/* Return pointer to next closing brace or to comma */
3238static const char *next_brace_sub(const char *cp)
3239{
3240 unsigned depth = 0;
3241 cp++;
3242 while (*cp != '\0') {
3243 if (*cp == '\\') {
3244 if (*++cp == '\0')
3245 break;
3246 cp++;
3247 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003248 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003249 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003250 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003251 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003252 depth++;
3253 }
3254
3255 return *cp != '\0' ? cp : NULL;
3256}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003257/* Recursive brace globber. Note: may garble pattern[]. */
3258static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003259{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003260 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003261 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003262 const char *next;
3263 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003264 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003265 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003266
3267 debug_printf_glob("glob_brace('%s')\n", pattern);
3268
3269 begin = pattern;
3270 while (1) {
3271 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003272 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003273 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003274 /* Find the first sub-pattern and at the same time
3275 * find the rest after the closing brace */
3276 next = next_brace_sub(begin);
3277 if (next == NULL) {
3278 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003279 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003280 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003281 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003282 /* "{abc}" with no commas - illegal
3283 * brace expr, disregard and skip it */
3284 begin = next + 1;
3285 continue;
3286 }
3287 break;
3288 }
3289 if (*begin == '\\' && begin[1] != '\0')
3290 begin++;
3291 begin++;
3292 }
3293 debug_printf_glob("begin:%s\n", begin);
3294 debug_printf_glob("next:%s\n", next);
3295
3296 /* Now find the end of the whole brace expression */
3297 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003298 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003299 rest = next_brace_sub(rest);
3300 if (rest == NULL) {
3301 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003302 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003303 }
3304 debug_printf_glob("rest:%s\n", rest);
3305 }
3306 rest_len = strlen(++rest) + 1;
3307
3308 /* We are sure the brace expression is well-formed */
3309
3310 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003311 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003312
3313 /* We have a brace expression. BEGIN points to the opening {,
3314 * NEXT points past the terminator of the first element, and REST
3315 * points past the final }. We will accumulate result names from
3316 * recursive runs for each brace alternative in the buffer using
3317 * GLOB_APPEND. */
3318
3319 p = begin + 1;
3320 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003321 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003322 memcpy(
3323 mempcpy(
3324 mempcpy(new_pattern_buf,
3325 /* We know the prefix for all sub-patterns */
3326 pattern, begin - pattern),
3327 p, next - p),
3328 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003329
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003330 /* Note: glob_brace() may garble new_pattern_buf[].
3331 * That's why we re-copy prefix every time (1st memcpy above).
3332 */
3333 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003334 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003335 /* We saw the last entry */
3336 break;
3337 }
3338 p = next + 1;
3339 next = next_brace_sub(next);
3340 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003341 free(new_pattern_buf);
3342 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003343
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003344 simple_glob:
3345 {
3346 int gr;
3347 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003348
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003349 memset(&globdata, 0, sizeof(globdata));
3350 gr = glob(pattern, 0, NULL, &globdata);
3351 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3352 if (gr != 0) {
3353 if (gr == GLOB_NOMATCH) {
3354 globfree(&globdata);
3355 /* NB: garbles parameter */
3356 unbackslash(pattern);
3357 o_addstr_with_NUL(o, pattern);
3358 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3359 return o_save_ptr_helper(o, n);
3360 }
3361 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003362 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003363 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3364 * but we didn't specify it. Paranoia again. */
3365 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3366 }
3367 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3368 char **argv = globdata.gl_pathv;
3369 while (1) {
3370 o_addstr_with_NUL(o, *argv);
3371 n = o_save_ptr_helper(o, n);
3372 argv++;
3373 if (!*argv)
3374 break;
3375 }
3376 }
3377 globfree(&globdata);
3378 }
3379 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003380}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003381/* Performs globbing on last list[],
3382 * saving each result as a new list[].
3383 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003384static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003385{
3386 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003387
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003388 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003389 if (!o->data)
3390 return o_save_ptr_helper(o, n);
3391 pattern = o->data + o_get_last_ptr(o, n);
3392 debug_printf_glob("glob pattern '%s'\n", pattern);
3393 if (!glob_needed(pattern)) {
3394 /* unbackslash last string in o in place, fix length */
3395 o->length = unbackslash(pattern) - o->data;
3396 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3397 return o_save_ptr_helper(o, n);
3398 }
3399
3400 copy = xstrdup(pattern);
3401 /* "forget" pattern in o */
3402 o->length = pattern - o->data;
3403 n = glob_brace(copy, o, n);
3404 free(copy);
3405 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003406 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003407 return n;
3408}
3409
Denys Vlasenko238081f2010-10-03 14:26:26 +02003410#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003411
3412/* Helper */
3413static int glob_needed(const char *s)
3414{
3415 while (*s) {
3416 if (*s == '\\') {
3417 if (!s[1])
3418 return 0;
3419 s += 2;
3420 continue;
3421 }
3422 if (*s == '*' || *s == '[' || *s == '?')
3423 return 1;
3424 s++;
3425 }
3426 return 0;
3427}
3428/* Performs globbing on last list[],
3429 * saving each result as a new list[].
3430 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003431static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003432{
3433 glob_t globdata;
3434 int gr;
3435 char *pattern;
3436
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003437 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003438 if (!o->data)
3439 return o_save_ptr_helper(o, n);
3440 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003441 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003442 if (!glob_needed(pattern)) {
3443 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003444 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003445 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003446 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003447 return o_save_ptr_helper(o, n);
3448 }
3449
3450 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003451 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3452 * If we glob "*.\*" and don't find anything, we need
3453 * to fall back to using literal "*.*", but GLOB_NOCHECK
3454 * will return "*.\*"!
3455 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003456 gr = glob(pattern, 0, NULL, &globdata);
3457 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003458 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003459 if (gr == GLOB_NOMATCH) {
3460 globfree(&globdata);
3461 goto literal;
3462 }
3463 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003464 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003465 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3466 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003467 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003468 }
3469 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3470 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003471 /* "forget" pattern in o */
3472 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003473 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003474 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003475 n = o_save_ptr_helper(o, n);
3476 argv++;
3477 if (!*argv)
3478 break;
3479 }
3480 }
3481 globfree(&globdata);
3482 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003483 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003484 return n;
3485}
3486
Denys Vlasenko238081f2010-10-03 14:26:26 +02003487#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003488
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003489/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003490 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003491static int o_save_ptr(o_string *o, int n)
3492{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003493 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003494 /* If o->has_empty_slot, list[n] was already globbed
3495 * (if it was requested back then when it was filled)
3496 * so don't do that again! */
3497 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003498 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003499 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003500 return o_save_ptr_helper(o, n);
3501}
3502
3503/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003504static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003505{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003506 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003507 int string_start;
3508
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003509 if (DEBUG_EXPAND)
3510 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003511 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003512 list = (char**)o->data;
3513 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3514 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003515 while (n) {
3516 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003517 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003518 }
3519 return list;
3520}
3521
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003522static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003523
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003524/* Returns pi->next - next pipe in the list */
3525static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003526{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003527 struct pipe *next;
3528 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003529
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003530 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003531 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003532 struct command *command;
3533 struct redir_struct *r, *rnext;
3534
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003535 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003536 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003537 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003538 if (DEBUG_CLEAN) {
3539 int a;
3540 char **p;
3541 for (a = 0, p = command->argv; *p; a++, p++) {
3542 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3543 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003544 }
3545 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003546 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003547 }
3548 /* not "else if": on syntax error, we may have both! */
3549 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003550 debug_printf_clean(" begin group (cmd_type:%d)\n",
3551 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003552 free_pipe_list(command->group);
3553 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003554 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003555 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003556 /* else is crucial here.
3557 * If group != NULL, child_func is meaningless */
3558#if ENABLE_HUSH_FUNCTIONS
3559 else if (command->child_func) {
3560 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3561 command->child_func->parent_cmd = NULL;
3562 }
3563#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003564#if !BB_MMU
3565 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003566 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003567#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003569 debug_printf_clean(" redirect %d%s",
3570 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003571 /* guard against the case >$FOO, where foo is unset or blank */
3572 if (r->rd_filename) {
3573 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3574 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003575 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003577 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003578 rnext = r->next;
3579 free(r);
3580 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003581 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003582 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003583 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003584 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003585#if ENABLE_HUSH_JOB
3586 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003587 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003588#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003589
3590 next = pi->next;
3591 free(pi);
3592 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003593}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003594
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003595static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003596{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003597 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003598#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003599 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003600#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003601 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003602 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003603 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003604}
3605
3606
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003607/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003608
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003609#ifndef debug_print_tree
3610static void debug_print_tree(struct pipe *pi, int lvl)
3611{
3612 static const char *const PIPE[] = {
3613 [PIPE_SEQ] = "SEQ",
3614 [PIPE_AND] = "AND",
3615 [PIPE_OR ] = "OR" ,
3616 [PIPE_BG ] = "BG" ,
3617 };
3618 static const char *RES[] = {
3619 [RES_NONE ] = "NONE" ,
3620# if ENABLE_HUSH_IF
3621 [RES_IF ] = "IF" ,
3622 [RES_THEN ] = "THEN" ,
3623 [RES_ELIF ] = "ELIF" ,
3624 [RES_ELSE ] = "ELSE" ,
3625 [RES_FI ] = "FI" ,
3626# endif
3627# if ENABLE_HUSH_LOOPS
3628 [RES_FOR ] = "FOR" ,
3629 [RES_WHILE] = "WHILE",
3630 [RES_UNTIL] = "UNTIL",
3631 [RES_DO ] = "DO" ,
3632 [RES_DONE ] = "DONE" ,
3633# endif
3634# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3635 [RES_IN ] = "IN" ,
3636# endif
3637# if ENABLE_HUSH_CASE
3638 [RES_CASE ] = "CASE" ,
3639 [RES_CASE_IN ] = "CASE_IN" ,
3640 [RES_MATCH] = "MATCH",
3641 [RES_CASE_BODY] = "CASE_BODY",
3642 [RES_ESAC ] = "ESAC" ,
3643# endif
3644 [RES_XXXX ] = "XXXX" ,
3645 [RES_SNTX ] = "SNTX" ,
3646 };
3647 static const char *const CMDTYPE[] = {
3648 "{}",
3649 "()",
3650 "[noglob]",
3651# if ENABLE_HUSH_FUNCTIONS
3652 "func()",
3653# endif
3654 };
3655
3656 int pin, prn;
3657
3658 pin = 0;
3659 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003660 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3661 lvl*2, "",
3662 pin,
3663 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3664 RES[pi->res_word],
3665 pi->followup, PIPE[pi->followup]
3666 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003667 prn = 0;
3668 while (prn < pi->num_cmds) {
3669 struct command *command = &pi->cmds[prn];
3670 char **argv = command->argv;
3671
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003672 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003673 lvl*2, "", prn,
3674 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003675#if ENABLE_HUSH_LINENO_VAR
3676 fdprintf(2, " LINENO:%u", command->lineno);
3677#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003678 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003679 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003680 CMDTYPE[command->cmd_type],
3681 argv
3682# if !BB_MMU
3683 , " group_as_string:", command->group_as_string
3684# else
3685 , "", ""
3686# endif
3687 );
3688 debug_print_tree(command->group, lvl+1);
3689 prn++;
3690 continue;
3691 }
3692 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003693 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003694 argv++;
3695 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003696 if (command->redirects)
3697 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003698 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003699 prn++;
3700 }
3701 pi = pi->next;
3702 pin++;
3703 }
3704}
3705#endif /* debug_print_tree */
3706
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003707static struct pipe *new_pipe(void)
3708{
Eric Andersen25f27032001-04-26 23:22:31 +00003709 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003710 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003711 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003712 return pi;
3713}
3714
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003715/* Command (member of a pipe) is complete, or we start a new pipe
3716 * if ctx->command is NULL.
3717 * No errors possible here.
3718 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003719static int done_command(struct parse_context *ctx)
3720{
3721 /* The command is really already in the pipe structure, so
3722 * advance the pipe counter and make a new, null command. */
3723 struct pipe *pi = ctx->pipe;
3724 struct command *command = ctx->command;
3725
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003726#if 0 /* Instead we emit error message at run time */
3727 if (ctx->pending_redirect) {
3728 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003729 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003730 ctx->pending_redirect = NULL;
3731 }
3732#endif
3733
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003734 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003735 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003736 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003737 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003738 }
3739 pi->num_cmds++;
3740 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003741 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003742 } else {
3743 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3744 }
3745
3746 /* Only real trickiness here is that the uncommitted
3747 * command structure is not counted in pi->num_cmds. */
3748 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003749 ctx->command = command = &pi->cmds[pi->num_cmds];
3750 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003751 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003752#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003753 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003754 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003755#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003756 return pi->num_cmds; /* used only for 0/nonzero check */
3757}
3758
3759static void done_pipe(struct parse_context *ctx, pipe_style type)
3760{
3761 int not_null;
3762
3763 debug_printf_parse("done_pipe entered, followup %d\n", type);
3764 /* Close previous command */
3765 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003766#if HAS_KEYWORDS
3767 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3768 ctx->ctx_inverted = 0;
3769 ctx->pipe->res_word = ctx->ctx_res_w;
3770#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003771 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3772 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003773 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3774 * in a backgrounded subshell.
3775 */
3776 struct pipe *pi;
3777 struct command *command;
3778
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003779 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003780 pi = ctx->list_head;
3781 while (pi != ctx->pipe) {
3782 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3783 goto no_conv;
3784 pi = pi->next;
3785 }
3786
3787 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3788 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3789 pi = xzalloc(sizeof(*pi));
3790 pi->followup = PIPE_BG;
3791 pi->num_cmds = 1;
3792 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3793 command = &pi->cmds[0];
3794 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3795 command->cmd_type = CMD_NORMAL;
3796 command->group = ctx->list_head;
3797#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003798 command->group_as_string = xstrndup(
3799 ctx->as_string.data,
3800 ctx->as_string.length - 1 /* do not copy last char, "&" */
3801 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003802#endif
3803 /* Replace all pipes in ctx with one newly created */
3804 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003805 } else {
3806 no_conv:
3807 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003808 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003809
3810 /* Without this check, even just <enter> on command line generates
3811 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003812 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003813 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003814#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003815 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003816#endif
3817#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003818 || ctx->ctx_res_w == RES_DONE
3819 || ctx->ctx_res_w == RES_FOR
3820 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003821#endif
3822#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003823 || ctx->ctx_res_w == RES_ESAC
3824#endif
3825 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003826 struct pipe *new_p;
3827 debug_printf_parse("done_pipe: adding new pipe: "
3828 "not_null:%d ctx->ctx_res_w:%d\n",
3829 not_null, ctx->ctx_res_w);
3830 new_p = new_pipe();
3831 ctx->pipe->next = new_p;
3832 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003833 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003834 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003835 * This is used to control execution.
3836 * RES_FOR and RES_IN are NOT sticky (needed to support
3837 * cases where variable or value happens to match a keyword):
3838 */
3839#if ENABLE_HUSH_LOOPS
3840 if (ctx->ctx_res_w == RES_FOR
3841 || ctx->ctx_res_w == RES_IN)
3842 ctx->ctx_res_w = RES_NONE;
3843#endif
3844#if ENABLE_HUSH_CASE
3845 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003846 ctx->ctx_res_w = RES_CASE_BODY;
3847 if (ctx->ctx_res_w == RES_CASE)
3848 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003849#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003850 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003851 /* Create the memory for command, roughly:
3852 * ctx->pipe->cmds = new struct command;
3853 * ctx->command = &ctx->pipe->cmds[0];
3854 */
3855 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003856 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003857 }
3858 debug_printf_parse("done_pipe return\n");
3859}
3860
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003861static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003862{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003863 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003864 if (MAYBE_ASSIGNMENT != 0)
3865 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003866 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003867 /* Create the memory for command, roughly:
3868 * ctx->pipe->cmds = new struct command;
3869 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003870 */
3871 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003872}
3873
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003874/* If a reserved word is found and processed, parse context is modified
3875 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003876 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003877#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003878struct reserved_combo {
3879 char literal[6];
3880 unsigned char res;
3881 unsigned char assignment_flag;
3882 int flag;
3883};
3884enum {
3885 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003886# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003887 FLAG_IF = (1 << RES_IF ),
3888 FLAG_THEN = (1 << RES_THEN ),
3889 FLAG_ELIF = (1 << RES_ELIF ),
3890 FLAG_ELSE = (1 << RES_ELSE ),
3891 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003892# endif
3893# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003894 FLAG_FOR = (1 << RES_FOR ),
3895 FLAG_WHILE = (1 << RES_WHILE),
3896 FLAG_UNTIL = (1 << RES_UNTIL),
3897 FLAG_DO = (1 << RES_DO ),
3898 FLAG_DONE = (1 << RES_DONE ),
3899 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003900# endif
3901# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003902 FLAG_MATCH = (1 << RES_MATCH),
3903 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003904# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003905 FLAG_START = (1 << RES_XXXX ),
3906};
3907
3908static const struct reserved_combo* match_reserved_word(o_string *word)
3909{
Eric Andersen25f27032001-04-26 23:22:31 +00003910 /* Mostly a list of accepted follow-up reserved words.
3911 * FLAG_END means we are done with the sequence, and are ready
3912 * to turn the compound list into a command.
3913 * FLAG_START means the word must start a new compound list.
3914 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003915 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003916# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003917 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3918 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3919 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3920 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3921 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3922 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003923# endif
3924# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003925 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3926 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3927 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3928 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3929 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3930 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003931# endif
3932# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003933 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3934 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003935# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003936 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003937 const struct reserved_combo *r;
3938
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003939 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003940 if (strcmp(word->data, r->literal) == 0)
3941 return r;
3942 }
3943 return NULL;
3944}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003945/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003946 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003947static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003948{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003949# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003950 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003951 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003952 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003953# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003954 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003955
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003956 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003957 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003958 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003959 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003960 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003961
3962 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003963# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003964 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3965 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003966 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003967 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003968# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003969 if (r->flag == 0) { /* '!' */
3970 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003971 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003972 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003973 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003974 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003975 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003976 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003977 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003978 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003979
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003980 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003981 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003982 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003983 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003984 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003985 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003986 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003987 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003988 } else {
3989 /* "{...} fi" is ok. "{...} if" is not
3990 * Example:
3991 * if { echo foo; } then { echo bar; } fi */
3992 if (ctx->command->group)
3993 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003994 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003995
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003996 ctx->ctx_res_w = r->res;
3997 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003998 ctx->is_assignment = r->assignment_flag;
3999 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004000
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004001 if (ctx->old_flag & FLAG_END) {
4002 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004003
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004004 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004005 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004006 old = ctx->stack;
4007 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004008 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004009# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004010 /* At this point, the compound command's string is in
4011 * ctx->as_string... except for the leading keyword!
4012 * Consider this example: "echo a | if true; then echo a; fi"
4013 * ctx->as_string will contain "true; then echo a; fi",
4014 * with "if " remaining in old->as_string!
4015 */
4016 {
4017 char *str;
4018 int len = old->as_string.length;
4019 /* Concatenate halves */
4020 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004021 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004022 /* Find where leading keyword starts in first half */
4023 str = old->as_string.data + len;
4024 if (str > old->as_string.data)
4025 str--; /* skip whitespace after keyword */
4026 while (str > old->as_string.data && isalpha(str[-1]))
4027 str--;
4028 /* Ugh, we're done with this horrid hack */
4029 old->command->group_as_string = xstrdup(str);
4030 debug_printf_parse("pop, remembering as:'%s'\n",
4031 old->command->group_as_string);
4032 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004033# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004034 *ctx = *old; /* physical copy */
4035 free(old);
4036 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004037 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004038}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004039#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004040
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004041/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004042 * Normal return is 0. Syntax errors return 1.
4043 * Note: on return, word is reset, but not o_free'd!
4044 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004045static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004046{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004047 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004048
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004049 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4050 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004051 debug_printf_parse("done_word return 0: true null, ignored\n");
4052 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004053 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004054
Eric Andersen25f27032001-04-26 23:22:31 +00004055 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004056 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4057 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004058 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004059 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004060 * If the redirection operator is "<<" or "<<-", the word
4061 * that follows the redirection operator shall be
4062 * subjected to quote removal; it is unspecified whether
4063 * any of the other expansions occur. For the other
4064 * redirection operators, the word that follows the
4065 * redirection operator shall be subjected to tilde
4066 * expansion, parameter expansion, command substitution,
4067 * arithmetic expansion, and quote removal.
4068 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004069 * on the word by a non-interactive shell; an interactive
4070 * shell may perform it, but shall do so only when
4071 * the expansion would result in one word."
4072 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004073//bash does not do parameter/command substitution or arithmetic expansion
4074//for _heredoc_ redirection word: these constructs look for exact eof marker
4075// as written:
4076// <<EOF$t
4077// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004078// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4079
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004080 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004081 /* Cater for >\file case:
4082 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4083 * Same with heredocs:
4084 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4085 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004086 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4087 unbackslash(ctx->pending_redirect->rd_filename);
4088 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004089 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004090 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4091 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004092 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004093 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004094 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004095 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004096#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004097# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004098 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004099 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004100 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004101 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004102 /* ctx->ctx_res_w = RES_MATCH; */
4103 ctx->ctx_dsemicolon = 0;
4104 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004105# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004106 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004107# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004108 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4109 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004110# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004111# if ENABLE_HUSH_CASE
4112 && ctx->ctx_res_w != RES_CASE
4113# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004114 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004115 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004116 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004117 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004118 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004119# if ENABLE_HUSH_LINENO_VAR
4120/* Case:
4121 * "while ...; do
4122 * cmd ..."
4123 * If we don't close the pipe _now_, immediately after "do", lineno logic
4124 * sees "cmd" as starting at "do" - i.e., at the previous line.
4125 */
4126 if (0
4127 IF_HUSH_IF(|| reserved->res == RES_THEN)
4128 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4129 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4130 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4131 ) {
4132 done_pipe(ctx, PIPE_SEQ);
4133 }
4134# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004135 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004136 debug_printf_parse("done_word return %d\n",
4137 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004138 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004139 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004140# if defined(CMD_SINGLEWORD_NOGLOB)
4141 if (0
4142# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004143 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004144# endif
4145 /* In bash, local/export/readonly are special, args
4146 * are assignments and therefore expansion of them
4147 * should be "one-word" expansion:
4148 * $ export i=`echo 'a b'` # one arg: "i=a b"
4149 * compare with:
4150 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4151 * ls: cannot access i=a: No such file or directory
4152 * ls: cannot access b: No such file or directory
4153 * Note: bash 3.2.33(1) does this only if export word
4154 * itself is not quoted:
4155 * $ export i=`echo 'aaa bbb'`; echo "$i"
4156 * aaa bbb
4157 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4158 * aaa
4159 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004160 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4161 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4162 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004163 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004164 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4165 }
4166 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004167# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004168 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004169#endif /* HAS_KEYWORDS */
4170
Denis Vlasenkobb929512009-04-16 10:59:40 +00004171 if (command->group) {
4172 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004173 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004174 debug_printf_parse("done_word return 1: syntax error, "
4175 "groups and arglists don't mix\n");
4176 return 1;
4177 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004178
4179 /* If this word wasn't an assignment, next ones definitely
4180 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004181 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4182 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004183 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004184 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004185 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004186 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004187 command->assignment_cnt++;
4188 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4189 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004190 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4191 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004192 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004193 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4194 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004195 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004196 }
Eric Andersen25f27032001-04-26 23:22:31 +00004197
Denis Vlasenko06810332007-05-21 23:30:54 +00004198#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004199 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004200 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004201 || !is_well_formed_var_name(command->argv[0], '\0')
4202 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004203 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004204 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004205 return 1;
4206 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004207 /* Force FOR to have just one word (variable name) */
4208 /* NB: basically, this makes hush see "for v in ..."
4209 * syntax as if it is "for v; in ...". FOR and IN become
4210 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004211 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004212 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004213#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004214#if ENABLE_HUSH_CASE
4215 /* Force CASE to have just one word */
4216 if (ctx->ctx_res_w == RES_CASE) {
4217 done_pipe(ctx, PIPE_SEQ);
4218 }
4219#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004220
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004221 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004222
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004223 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004224 return 0;
4225}
4226
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004227
4228/* Peek ahead in the input to find out if we have a "&n" construct,
4229 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004230 * Return:
4231 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4232 * REDIRFD_SYNTAX_ERR if syntax error,
4233 * REDIRFD_TO_FILE if no & was seen,
4234 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004235 */
4236#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004237#define parse_redir_right_fd(as_string, input) \
4238 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004239#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004240static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004241{
4242 int ch, d, ok;
4243
4244 ch = i_peek(input);
4245 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004246 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004247
4248 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250 ch = i_peek(input);
4251 if (ch == '-') {
4252 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004253 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004254 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004255 }
4256 d = 0;
4257 ok = 0;
4258 while (ch != EOF && isdigit(ch)) {
4259 d = d*10 + (ch-'0');
4260 ok = 1;
4261 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004262 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004263 ch = i_peek(input);
4264 }
4265 if (ok) return d;
4266
4267//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4268
4269 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004270 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004271}
4272
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004273/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004274 */
4275static int parse_redirect(struct parse_context *ctx,
4276 int fd,
4277 redir_type style,
4278 struct in_str *input)
4279{
4280 struct command *command = ctx->command;
4281 struct redir_struct *redir;
4282 struct redir_struct **redirp;
4283 int dup_num;
4284
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004285 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004286 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004287 /* Check for a '>&1' type redirect */
4288 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4289 if (dup_num == REDIRFD_SYNTAX_ERR)
4290 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004291 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004292 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004293 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004294 if (dup_num) { /* <<-... */
4295 ch = i_getch(input);
4296 nommu_addchr(&ctx->as_string, ch);
4297 ch = i_peek(input);
4298 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004299 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004300
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004301 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004302 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303 if (ch == '|') {
4304 /* >|FILE redirect ("clobbering" >).
4305 * Since we do not support "set -o noclobber" yet,
4306 * >| and > are the same for now. Just eat |.
4307 */
4308 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004309 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004310 }
4311 }
4312
4313 /* Create a new redir_struct and append it to the linked list */
4314 redirp = &command->redirects;
4315 while ((redir = *redirp) != NULL) {
4316 redirp = &(redir->next);
4317 }
4318 *redirp = redir = xzalloc(sizeof(*redir));
4319 /* redir->next = NULL; */
4320 /* redir->rd_filename = NULL; */
4321 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004322 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004323
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004324 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4325 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004327 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004328 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329 /* Erik had a check here that the file descriptor in question
4330 * is legit; I postpone that to "run time"
4331 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004332 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4333 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004334 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004335#if 0 /* Instead we emit error message at run time */
4336 if (ctx->pending_redirect) {
4337 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004338 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004339 }
4340#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004341 /* Set ctx->pending_redirect, so we know what to do at the
4342 * end of the next parsed word. */
4343 ctx->pending_redirect = redir;
4344 }
4345 return 0;
4346}
4347
Eric Andersen25f27032001-04-26 23:22:31 +00004348/* If a redirect is immediately preceded by a number, that number is
4349 * supposed to tell which file descriptor to redirect. This routine
4350 * looks for such preceding numbers. In an ideal world this routine
4351 * needs to handle all the following classes of redirects...
4352 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4353 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4354 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4355 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004356 *
4357 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4358 * "2.7 Redirection
4359 * ... If n is quoted, the number shall not be recognized as part of
4360 * the redirection expression. For example:
4361 * echo \2>a
4362 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004363 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004364 *
4365 * A -1 return means no valid number was found,
4366 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004367 */
4368static int redirect_opt_num(o_string *o)
4369{
4370 int num;
4371
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004372 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004373 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004374 num = bb_strtou(o->data, NULL, 10);
4375 if (errno || num < 0)
4376 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004377 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004378 return num;
4379}
4380
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004381#if BB_MMU
4382#define fetch_till_str(as_string, input, word, skip_tabs) \
4383 fetch_till_str(input, word, skip_tabs)
4384#endif
4385static char *fetch_till_str(o_string *as_string,
4386 struct in_str *input,
4387 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004388 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004389{
4390 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004391 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004392 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004393 int ch;
4394
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004395 /* Starting with "" is necessary for this case:
4396 * cat <<EOF
4397 *
4398 * xxx
4399 * EOF
4400 */
4401 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4402
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004403 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004404
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004405 while (1) {
4406 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004407 if (ch != EOF)
4408 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004409 if (ch == '\n' || ch == EOF) {
4410 check_heredoc_end:
4411 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004412 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004413 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4414 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004415 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004416 return heredoc.data;
4417 }
4418 if (ch == '\n') {
4419 /* This is a new line.
4420 * Remember position and backslash-escaping status.
4421 */
4422 o_addchr(&heredoc, ch);
4423 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004424 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004425 past_EOL = heredoc.length;
4426 /* Get 1st char of next line, possibly skipping leading tabs */
4427 do {
4428 ch = i_getch(input);
4429 if (ch != EOF)
4430 nommu_addchr(as_string, ch);
4431 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4432 /* If this immediately ended the line,
4433 * go back to end-of-line checks.
4434 */
4435 if (ch == '\n')
4436 goto check_heredoc_end;
4437 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004438 } else {
4439 /* Backslash-line continuation in an unquoted
4440 * heredoc. This does not need special handling
4441 * for heredoc body (unquoted heredocs are
4442 * expanded on "execution" and that would take
4443 * care of this case too), but not the case
4444 * of line continuation *in terminator*:
4445 * cat <<EOF
4446 * Ok1
4447 * EO\
4448 * F
4449 */
4450 heredoc.data[--heredoc.length] = '\0';
4451 prev = 0; /* not '\' */
4452 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004453 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004454 }
4455 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004456 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004457 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004458 }
4459 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004460 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004461 if (prev == '\\' && ch == '\\')
4462 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004463 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004464 else
4465 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004466 }
4467}
4468
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004469/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4470 * and load them all. There should be exactly heredoc_cnt of them.
4471 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004472#if BB_MMU
4473#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4474 fetch_heredocs(pi, heredoc_cnt, input)
4475#endif
4476static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004477{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004478 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004479 int i;
4480 struct command *cmd = pi->cmds;
4481
Denys Vlasenko3675c372018-07-23 16:31:21 +02004482 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004483 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004484 cmd->argv ? cmd->argv[0] : "NONE"
4485 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004486 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004487 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004488
Denys Vlasenko3675c372018-07-23 16:31:21 +02004489 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004490 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004491 while (redir) {
4492 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004493 char *p;
4494
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004495 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004496 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004497 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004498 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004499 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004500 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004501 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004502 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004503 free(redir->rd_filename);
4504 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004505 heredoc_cnt--;
4506 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004507 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004508 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004509 if (cmd->group) {
4510 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4511 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4512 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4513 if (heredoc_cnt < 0)
4514 return heredoc_cnt; /* error */
4515 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004516 cmd++;
4517 }
4518 pi = pi->next;
4519 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004520 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004521}
4522
4523
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004524static int run_list(struct pipe *pi);
4525#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004526#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4527 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004528#endif
4529static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004530 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004531 struct in_str *input,
4532 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004533
Denys Vlasenko474cb202018-07-24 13:03:03 +02004534/* Returns number of heredocs not yet consumed,
4535 * or -1 on error.
4536 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004537static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004538 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004539{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004540 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004541 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004542 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004543#if BB_MMU
4544# define as_string NULL
4545#else
4546 char *as_string = NULL;
4547#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004548 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004549 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004550 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004551 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004552
4553 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004554#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004555 if (ch == '(' && !ctx->word.has_quoted_part) {
4556 if (ctx->word.length)
4557 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004558 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004559 if (!command->argv)
4560 goto skip; /* (... */
4561 if (command->argv[1]) { /* word word ... (... */
4562 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004563 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004564 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004565 /* it is "word(..." or "word (..." */
4566 do
4567 ch = i_getch(input);
4568 while (ch == ' ' || ch == '\t');
4569 if (ch != ')') {
4570 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004571 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004572 }
4573 nommu_addchr(&ctx->as_string, ch);
4574 do
4575 ch = i_getch(input);
4576 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004577 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004578 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004579 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004580 }
4581 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004582 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004583 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004584 }
4585#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004586
4587#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004588 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004589 || ctx->word.length /* word{... */
4590 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004591 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004592 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004593 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004594 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004595 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004596 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004597#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004598
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004599 IF_HUSH_FUNCTIONS(skip:)
4600
Denis Vlasenko240c2552009-04-03 03:45:05 +00004601 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004602 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004603 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004604 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4605 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004606 } else {
4607 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004608 ch = i_peek(input);
4609 if (ch != ' ' && ch != '\t' && ch != '\n'
4610 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4611 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004612 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004613 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004614 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004615 if (ch != '(') {
4616 ch = i_getch(input);
4617 nommu_addchr(&ctx->as_string, ch);
4618 }
Eric Andersen25f27032001-04-26 23:22:31 +00004619 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004620
Denys Vlasenko474cb202018-07-24 13:03:03 +02004621 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4622 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4623 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004624#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004625 if (as_string)
4626 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004627#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004628
4629 /* empty ()/{} or parse error? */
4630 if (!pipe_list || pipe_list == ERR_PTR) {
4631 /* parse_stream already emitted error msg */
4632 if (!BB_MMU)
4633 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004634 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004635 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004636 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004637 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004638#if !BB_MMU
4639 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4640 command->group_as_string = as_string;
4641 debug_printf_parse("end of group, remembering as:'%s'\n",
4642 command->group_as_string);
4643#endif
4644
4645#if ENABLE_HUSH_FUNCTIONS
4646 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4647 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4648 struct command *cmd2;
4649
4650 cmd2 = xzalloc(sizeof(*cmd2));
4651 cmd2->cmd_type = CMD_SUBSHELL;
4652 cmd2->group = pipe_list;
4653# if !BB_MMU
4654//UNTESTED!
4655 cmd2->group_as_string = command->group_as_string;
4656 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4657# endif
4658
4659 pipe_list = new_pipe();
4660 pipe_list->cmds = cmd2;
4661 pipe_list->num_cmds = 1;
4662 }
4663#endif
4664
4665 command->group = pipe_list;
4666
Denys Vlasenko474cb202018-07-24 13:03:03 +02004667 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4668 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004669 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004670#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004671}
4672
Denys Vlasenko0b883582016-12-23 16:49:07 +01004673#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004674/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004675/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004676static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004677{
4678 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004679 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004680 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004681 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004682 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004683 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004684 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004685 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004686 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004687 }
4688}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004689static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4690{
4691 while (1) {
4692 int ch = i_getch(input);
4693 if (ch == EOF) {
4694 syntax_error_unterm_ch('\'');
4695 return 0;
4696 }
4697 if (ch == '\'')
4698 return 1;
4699 o_addqchr(dest, ch);
4700 }
4701}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004702/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004703static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004704static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004705{
4706 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004707 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004708 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004709 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004710 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004711 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004712 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004713 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004714 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004715 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004716 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004717 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004718 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004719 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004720 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4721 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004722 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004723 continue;
4724 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004725 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004726 }
4727}
4728/* Process `cmd` - copy contents until "`" is seen. Complicated by
4729 * \` quoting.
4730 * "Within the backquoted style of command substitution, backslash
4731 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4732 * The search for the matching backquote shall be satisfied by the first
4733 * backquote found without a preceding backslash; during this search,
4734 * if a non-escaped backquote is encountered within a shell comment,
4735 * a here-document, an embedded command substitution of the $(command)
4736 * form, or a quoted string, undefined results occur. A single-quoted
4737 * or double-quoted string that begins, but does not end, within the
4738 * "`...`" sequence produces undefined results."
4739 * Example Output
4740 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4741 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004742static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004743{
4744 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004745 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004746 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004747 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004748 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004749 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4750 ch = i_getch(input);
4751 if (ch != '`'
4752 && ch != '$'
4753 && ch != '\\'
4754 && (!in_dquote || ch != '"')
4755 ) {
4756 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004757 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004758 }
4759 if (ch == EOF) {
4760 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004761 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004762 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004763 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004764 }
4765}
4766/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4767 * quoting and nested ()s.
4768 * "With the $(command) style of command substitution, all characters
4769 * following the open parenthesis to the matching closing parenthesis
4770 * constitute the command. Any valid shell script can be used for command,
4771 * except a script consisting solely of redirections which produces
4772 * unspecified results."
4773 * Example Output
4774 * echo $(echo '(TEST)' BEST) (TEST) BEST
4775 * echo $(echo 'TEST)' BEST) TEST) BEST
4776 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004777 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004778 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004779 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004780 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4781 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004782 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004783#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004784static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004785{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004786 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004787 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004788# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004789 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004790# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004791 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4792
Denys Vlasenko817a2022018-06-26 15:35:17 +02004793#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004794 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004795#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004796 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4797
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004798 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004799 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004800 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004801 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004802 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004803 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004804 if (ch == end_ch
4805# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004806 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004807# endif
4808 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004809 if (!dbl)
4810 break;
4811 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004812 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004813 i_getch(input); /* eat second ')' */
4814 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004815 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004816 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004817 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004818 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004819 if (ch == '(' || ch == '{') {
4820 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004821 if (!add_till_closing_bracket(dest, input, ch))
4822 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004823 o_addchr(dest, ch);
4824 continue;
4825 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004826 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004827 if (!add_till_single_quote(dest, input))
4828 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004829 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004830 continue;
4831 }
4832 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004833 if (!add_till_double_quote(dest, input))
4834 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004835 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004836 continue;
4837 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004838 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004839 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4840 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004841 o_addchr(dest, ch);
4842 continue;
4843 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004844 if (ch == '\\') {
4845 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004846 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004847 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004848 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004849 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004850 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004851#if 0
4852 if (ch == '\n') {
4853 /* "backslash+newline", ignore both */
4854 o_delchr(dest); /* undo insertion of '\' */
4855 continue;
4856 }
4857#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004858 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004859 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004860 continue;
4861 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004862 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004863 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004864 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004865}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004866#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004867
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004868/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004869#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004870#define parse_dollar(as_string, dest, input, quote_mask) \
4871 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004872#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004873#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004874static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004875 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004876 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004877{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004878 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004879
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004880 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004881 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004882 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004883 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004884 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004885 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004886 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004887 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004888 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004889 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004890 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004891 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004892 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004893 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004894 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004895 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004896 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004897 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004898 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004899 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004900 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004901 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004902 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004903 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004904 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004905 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004906 o_addchr(dest, ch | quote_mask);
4907 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004908 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004909 case '$': /* pid */
4910 case '!': /* last bg pid */
4911 case '?': /* last exit code */
4912 case '#': /* number of args */
4913 case '*': /* args */
4914 case '@': /* args */
4915 goto make_one_char_var;
4916 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004917 char len_single_ch;
4918
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004919 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4920
Denys Vlasenko74369502010-05-21 19:52:01 +02004921 ch = i_getch(input); /* eat '{' */
4922 nommu_addchr(as_string, ch);
4923
Denys Vlasenko46e64982016-09-29 19:50:55 +02004924 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004925 /* It should be ${?}, or ${#var},
4926 * or even ${?+subst} - operator acting on a special variable,
4927 * or the beginning of variable name.
4928 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004929 if (ch == EOF
4930 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4931 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004932 bad_dollar_syntax:
4933 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004934 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4935 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004936 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004937 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004938 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004939 ch |= quote_mask;
4940
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004941 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004942 * However, this regresses some of our testsuite cases
4943 * which check invalid constructs like ${%}.
4944 * Oh well... let's check that the var name part is fine... */
4945
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004946 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004947 unsigned pos;
4948
Denys Vlasenko74369502010-05-21 19:52:01 +02004949 o_addchr(dest, ch);
4950 debug_printf_parse(": '%c'\n", ch);
4951
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004952 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004953 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004954 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004955 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004956
Denys Vlasenko74369502010-05-21 19:52:01 +02004957 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004958 unsigned end_ch;
4959 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004960 /* handle parameter expansions
4961 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4962 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004963 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4964 if (len_single_ch != '#'
4965 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4966 || i_peek(input) != '}'
4967 ) {
4968 goto bad_dollar_syntax;
4969 }
4970 /* else: it's "length of C" ${#C} op,
4971 * where C is a single char
4972 * special var name, e.g. ${#!}.
4973 */
4974 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004975 /* Eat everything until closing '}' (or ':') */
4976 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004977 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004978 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004979 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004980 ) {
4981 /* It's ${var:N[:M]} thing */
4982 end_ch = '}' * 0x100 + ':';
4983 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004984 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004985 && ch == '/'
4986 ) {
4987 /* It's ${var/[/]pattern[/repl]} thing */
4988 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4989 i_getch(input);
4990 nommu_addchr(as_string, '/');
4991 ch = '\\';
4992 }
4993 end_ch = '}' * 0x100 + '/';
4994 }
4995 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02004996 /* The pattern can't be empty.
4997 * IOW: if the first char after "${v//" is a slash,
4998 * it does not terminate the pattern - it's the first char of the pattern:
4999 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5000 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5001 */
5002 if (i_peek(input) == '/') {
5003 o_addchr(dest, i_getch(input));
5004 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005005 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005006 if (!BB_MMU)
5007 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005008#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005009 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005010 if (last_ch == 0) /* error? */
5011 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005012#else
5013#error Simple code to only allow ${var} is not implemented
5014#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005015 if (as_string) {
5016 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005017 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005018 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005019
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005020 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5021 && (end_ch & 0xff00)
5022 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005023 /* close the first block: */
5024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005025 /* while parsing N from ${var:N[:M]}
5026 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005027 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005028 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005029 end_ch = '}';
5030 goto again;
5031 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005032 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005033 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005034 /* it's ${var:N} - emulate :999999999 */
5035 o_addstr(dest, "999999999");
5036 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005037 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005038 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005039 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005040 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005041 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005042 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5043 break;
5044 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005045#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005046 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005047 unsigned pos;
5048
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005049 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005050 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005051# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005052 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005053 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005054 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005055 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5056 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005057 if (!BB_MMU)
5058 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005059 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5060 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005061 if (as_string) {
5062 o_addstr(as_string, dest->data + pos);
5063 o_addchr(as_string, ')');
5064 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005065 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005066 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005067 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005068 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005069# endif
5070# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005071 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5072 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005073 if (!BB_MMU)
5074 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005075 if (!add_till_closing_bracket(dest, input, ')'))
5076 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005077 if (as_string) {
5078 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005079 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005080 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005081 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005082# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005083 break;
5084 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005085#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005086 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005087 goto make_var;
5088#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005089 /* TODO: $_ and $-: */
5090 /* $_ Shell or shell script name; or last argument of last command
5091 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5092 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005093 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005094 ch = i_getch(input);
5095 nommu_addchr(as_string, ch);
5096 ch = i_peek_and_eat_bkslash_nl(input);
5097 if (isalnum(ch)) { /* it's $_name or $_123 */
5098 ch = '_';
5099 goto make_var1;
5100 }
5101 /* else: it's $_ */
5102#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005103 default:
5104 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005105 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005106 debug_printf_parse("parse_dollar return 1 (ok)\n");
5107 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005108#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005109}
5110
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005111#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005112#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005113 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005114#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005115#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005116static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005117 o_string *dest,
5118 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005119 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005120{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005121 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005122 int next;
5123
5124 again:
5125 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005126 if (ch != EOF)
5127 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005128 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005129 debug_printf_parse("encode_string return 1 (ok)\n");
5130 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005131 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005132 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005133 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005134 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005135 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005136 }
5137 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005138 if (ch != '\n') {
5139 next = i_peek(input);
5140 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005141 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005142 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005143 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005144 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005145 /* Testcase: in interactive shell a file with
5146 * echo "unterminated string\<eof>
5147 * is sourced.
5148 */
5149 syntax_error_unterm_ch('"');
5150 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005151 }
5152 /* bash:
5153 * "The backslash retains its special meaning [in "..."]
5154 * only when followed by one of the following characters:
5155 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005156 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005157 * NB: in (unquoted) heredoc, above does not apply to ",
5158 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005159 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005160 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005161 ch = i_getch(input); /* eat next */
5162 if (ch == '\n')
5163 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005164 } /* else: ch remains == '\\', and we double it below: */
5165 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005166 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005167 goto again;
5168 }
5169 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005170 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5171 debug_printf_parse("encode_string return 0: "
5172 "parse_dollar returned 0 (error)\n");
5173 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005174 }
5175 goto again;
5176 }
5177#if ENABLE_HUSH_TICK
5178 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005179 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005180 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5181 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005182 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5183 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005184 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5185 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005186 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005187 }
5188#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005189 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005190 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005191#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005192}
5193
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005194/*
5195 * Scan input until EOF or end_trigger char.
5196 * Return a list of pipes to execute, or NULL on EOF
5197 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005198 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005199 * reset parsing machinery and start parsing anew,
5200 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005201 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005202static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005203 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005204 struct in_str *input,
5205 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005206{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005207 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005208 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005209
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005210 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005211 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005212 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005213 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005214 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005215 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005216
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005217 initialize_context(&ctx);
5218
5219 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5220 * Preventing this:
5221 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005222 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005223
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005224 /* We used to separate words on $IFS here. This was wrong.
5225 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005226 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005227 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005228
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005229 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005230 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005231 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005232 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005233 int ch;
5234 int next;
5235 int redir_fd;
5236 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005237
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005238 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005239 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005240 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005241 if (ch == EOF) {
5242 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005243
5244 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005245 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005246 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005247 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005248 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005249 syntax_error_unterm_ch('(');
5250 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005251 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005252 if (end_trigger == '}') {
5253 syntax_error_unterm_ch('{');
5254 goto parse_error;
5255 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005256
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005257 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005258 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005259 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005260 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005261 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005262 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005263 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005264 /* (this makes bare "&" cmd a no-op.
5265 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005266 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005267 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005268 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005269 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005270 pi = NULL;
5271 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005272#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005273 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005274 if (pstring)
5275 *pstring = ctx.as_string.data;
5276 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005277 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005278#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005279 // heredoc_cnt must be 0 here anyway
5280 //if (heredoc_cnt_ptr)
5281 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005282 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005283 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005284 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005285 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005286 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005287
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005288 /* Handle "'" and "\" first, as they won't play nice with
5289 * i_peek_and_eat_bkslash_nl() anyway:
5290 * echo z\\
5291 * and
5292 * echo '\
5293 * '
5294 * would break.
5295 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005296 if (ch == '\\') {
5297 ch = i_getch(input);
5298 if (ch == '\n')
5299 continue; /* drop \<newline>, get next char */
5300 nommu_addchr(&ctx.as_string, '\\');
5301 o_addchr(&ctx.word, '\\');
5302 if (ch == EOF) {
5303 /* Testcase: eval 'echo Ok\' */
5304 /* bash-4.3.43 was removing backslash,
5305 * but 4.4.19 retains it, most other shells too
5306 */
5307 continue; /* get next char */
5308 }
5309 /* Example: echo Hello \2>file
5310 * we need to know that word 2 is quoted
5311 */
5312 ctx.word.has_quoted_part = 1;
5313 nommu_addchr(&ctx.as_string, ch);
5314 o_addchr(&ctx.word, ch);
5315 continue; /* get next char */
5316 }
5317 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005318 if (ch == '\'') {
5319 ctx.word.has_quoted_part = 1;
5320 next = i_getch(input);
5321 if (next == '\'' && !ctx.pending_redirect)
5322 goto insert_empty_quoted_str_marker;
5323
5324 ch = next;
5325 while (1) {
5326 if (ch == EOF) {
5327 syntax_error_unterm_ch('\'');
5328 goto parse_error;
5329 }
5330 nommu_addchr(&ctx.as_string, ch);
5331 if (ch == '\'')
5332 break;
5333 if (ch == SPECIAL_VAR_SYMBOL) {
5334 /* Convert raw ^C to corresponding special variable reference */
5335 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5336 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5337 }
5338 o_addqchr(&ctx.word, ch);
5339 ch = i_getch(input);
5340 }
5341 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005342 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005343
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005344 next = '\0';
5345 if (ch != '\n')
5346 next = i_peek_and_eat_bkslash_nl(input);
5347
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005348 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005349 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005350 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005351 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005352 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005353 || ctx.word.length /* word{... - non-special */
5354 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005355 || (next != ';' /* }; - special */
5356 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005357 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005358 && next != '&' /* }& and }&& ... - special */
5359 && next != '|' /* }|| ... - special */
5360 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005361 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005362 ) {
5363 /* They are not special, skip "{}" */
5364 is_special += 2;
5365 }
5366 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005367 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005368
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005369 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005370 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005371 o_addQchr(&ctx.word, ch);
5372 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5373 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005374 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005375 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005376 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005377 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5378 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005379 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005380 continue;
5381 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005382
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005383 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005384#if ENABLE_HUSH_LINENO_VAR
5385/* Case:
5386 * "while ...; do<whitespace><newline>
5387 * cmd ..."
5388 * would think that "cmd" starts in <whitespace> -
5389 * i.e., at the previous line.
5390 * We need to skip all whitespace before newlines.
5391 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005392 while (ch != '\n') {
5393 next = i_peek(input);
5394 if (next != ' ' && next != '\t' && next != '\n')
5395 break; /* next char is not ws */
5396 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005397 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005398 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005399#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005400 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005401 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005402 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005403 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005404 /* Is this a case when newline is simply ignored?
5405 * Some examples:
5406 * "cmd | <newline> cmd ..."
5407 * "case ... in <newline> word) ..."
5408 */
5409 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005410 && ctx.word.length == 0
5411 && !ctx.word.has_quoted_part
5412 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005413 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005414 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005415 * Without check #1, interactive shell
5416 * ignores even bare <newline>,
5417 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005418 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005419 * ps2> _ <=== wrong, should be ps1
5420 * Without check #2, "cmd & <newline>"
5421 * is similarly mistreated.
5422 * (BTW, this makes "cmd & cmd"
5423 * and "cmd && cmd" non-orthogonal.
5424 * Really, ask yourself, why
5425 * "cmd && <newline>" doesn't start
5426 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005427 * The only reason is that it might be
5428 * a "cmd1 && <nl> cmd2 &" construct,
5429 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005430 */
5431 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005432 if (pi->num_cmds != 0 /* check #1 */
5433 && pi->followup != PIPE_BG /* check #2 */
5434 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005435 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005436 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005437 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005438 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005439 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005440 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005441 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005442 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5443 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005444 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005445 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005446 ctx.is_assignment = MAYBE_ASSIGNMENT;
5447 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005448 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005449 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005450 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005451 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005452 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005453
5454 /* "cmd}" or "cmd }..." without semicolon or &:
5455 * } is an ordinary char in this case, even inside { cmd; }
5456 * Pathological example: { ""}; } should exec "}" cmd
5457 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005458 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005459 if (ctx.word.length != 0 /* word} */
5460 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005461 ) {
5462 goto ordinary_char;
5463 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005464 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5465 /* Generally, there should be semicolon: "cmd; }"
5466 * However, bash allows to omit it if "cmd" is
5467 * a group. Examples:
5468 * { { echo 1; } }
5469 * {(echo 1)}
5470 * { echo 0 >&2 | { echo 1; } }
5471 * { while false; do :; done }
5472 * { case a in b) ;; esac }
5473 */
5474 if (ctx.command->group)
5475 goto term_group;
5476 goto ordinary_char;
5477 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005478 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005479 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005480 goto skip_end_trigger;
5481 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005482 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005483 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005484 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005485 && (ch != ';' || heredoc_cnt == 0)
5486#if ENABLE_HUSH_CASE
5487 && (ch != ')'
5488 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005489 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005490 )
5491#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005492 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005493 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005494 goto parse_error;
5495 }
5496 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005497 ctx.is_assignment = MAYBE_ASSIGNMENT;
5498 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005499 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005500 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005501 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005502 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005503 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005504#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005505 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005506 if (pstring)
5507 *pstring = ctx.as_string.data;
5508 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005509 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005510#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005511 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5512 /* Example: bare "{ }", "()" */
5513 G.last_exitcode = 2; /* bash compat */
5514 syntax_error_unexpected_ch(ch);
5515 goto parse_error2;
5516 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005517 if (heredoc_cnt_ptr)
5518 *heredoc_cnt_ptr = heredoc_cnt;
5519 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005520 debug_printf_parse("parse_stream return %p: "
5521 "end_trigger char found\n",
5522 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005523 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005524 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005525 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005526 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005527
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005528 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005529 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005530
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005531 /* Catch <, > before deciding whether this word is
5532 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5533 switch (ch) {
5534 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005535 redir_fd = redirect_opt_num(&ctx.word);
5536 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005537 goto parse_error;
5538 }
5539 redir_style = REDIRECT_OVERWRITE;
5540 if (next == '>') {
5541 redir_style = REDIRECT_APPEND;
5542 ch = i_getch(input);
5543 nommu_addchr(&ctx.as_string, ch);
5544 }
5545#if 0
5546 else if (next == '(') {
5547 syntax_error(">(process) not supported");
5548 goto parse_error;
5549 }
5550#endif
5551 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5552 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005553 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005554 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005555 redir_fd = redirect_opt_num(&ctx.word);
5556 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005557 goto parse_error;
5558 }
5559 redir_style = REDIRECT_INPUT;
5560 if (next == '<') {
5561 redir_style = REDIRECT_HEREDOC;
5562 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005563 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005564 ch = i_getch(input);
5565 nommu_addchr(&ctx.as_string, ch);
5566 } else if (next == '>') {
5567 redir_style = REDIRECT_IO;
5568 ch = i_getch(input);
5569 nommu_addchr(&ctx.as_string, ch);
5570 }
5571#if 0
5572 else if (next == '(') {
5573 syntax_error("<(process) not supported");
5574 goto parse_error;
5575 }
5576#endif
5577 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5578 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005579 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005580 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005581 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005582 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005583 /* note: we do not add it to &ctx.as_string */
5584/* TODO: in bash:
5585 * comment inside $() goes to the next \n, even inside quoted string (!):
5586 * cmd "$(cmd2 #comment)" - syntax error
5587 * cmd "`cmd2 #comment`" - ok
5588 * We accept both (comment ends where command subst ends, in both cases).
5589 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005590 while (1) {
5591 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005592 if (ch == '\n') {
5593 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005594 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005595 }
5596 ch = i_getch(input);
5597 if (ch == EOF)
5598 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005599 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005600 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005601 }
5602 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005603 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005604 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005605
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005606 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005607 /* check that we are not in word in "a=1 2>word b=1": */
5608 && !ctx.pending_redirect
5609 ) {
5610 /* ch is a special char and thus this word
5611 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005612 ctx.is_assignment = NOT_ASSIGNMENT;
5613 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005614 }
5615
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005616 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5617
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005618 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005619 case SPECIAL_VAR_SYMBOL:
5620 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005621 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5622 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005623 /* fall through */
5624 case '#':
5625 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005626 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005627 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005628 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005629 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005630 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005631 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005632 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005633 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005634 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005635 case '"':
5636 ctx.word.has_quoted_part = 1;
5637 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005638 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005639 insert_empty_quoted_str_marker:
5640 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005641 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5642 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005643 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005644 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005645 if (ctx.is_assignment == NOT_ASSIGNMENT)
5646 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005647 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005648 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005649 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005650 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005651#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005652 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005653 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005654
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005655 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5656 o_addchr(&ctx.word, '`');
5657 USE_FOR_NOMMU(pos = ctx.word.length;)
5658 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005659 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005660# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005661 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005662 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005663# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005664 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5665 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005666 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005667 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005668#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005669 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005670#if ENABLE_HUSH_CASE
5671 case_semi:
5672#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005673 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005674 goto parse_error;
5675 }
5676 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005677#if ENABLE_HUSH_CASE
5678 /* Eat multiple semicolons, detect
5679 * whether it means something special */
5680 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005681 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005682 if (ch != ';')
5683 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005684 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005685 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005686 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005687 ctx.ctx_dsemicolon = 1;
5688 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005689 break;
5690 }
5691 }
5692#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005693 new_cmd:
5694 /* We just finished a cmd. New one may start
5695 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005696 ctx.is_assignment = MAYBE_ASSIGNMENT;
5697 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005698 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005699 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005700 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005701 goto parse_error;
5702 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005703 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005704 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005705 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005706 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005707 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005708 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005709 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005710 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005711 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005712 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005713 goto parse_error;
5714 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005715#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005716 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005717 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005718#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005719 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005720 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005721 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005722 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005723 } else {
5724 /* we could pick up a file descriptor choice here
5725 * with redirect_opt_num(), but bash doesn't do it.
5726 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005727 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005728 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005729 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005730 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005731#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005732 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005733 if (ctx.ctx_res_w == RES_MATCH
5734 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005735 && ctx.word.length == 0 /* not word(... */
5736 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005737 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005738 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005739 }
5740#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005741 /* fall through */
5742 case '{': {
5743 int n = parse_group(&ctx, input, ch);
5744 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005745 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005746 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005747 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5748 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005749 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005750 }
Eric Andersen25f27032001-04-26 23:22:31 +00005751 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005752#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005753 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005754 goto case_semi;
5755#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005756
Eric Andersen25f27032001-04-26 23:22:31 +00005757 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005758 /* proper use of this character is caught by end_trigger:
5759 * if we see {, we call parse_group(..., end_trigger='}')
5760 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005761 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005762 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005763 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005764 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005765 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005766 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005767 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005768 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005769
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005770 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005771 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005772 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005773 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005774 struct parse_context *pctx;
5775 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005776
5777 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005778 * Sample for finding leaks on syntax error recovery path.
5779 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005780 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005781 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005782 * while if (true | { true;}); then echo ok; fi; do break; done
5783 * 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 +00005784 */
5785 pctx = &ctx;
5786 do {
5787 /* Update pipe/command counts,
5788 * otherwise freeing may miss some */
5789 done_pipe(pctx, PIPE_SEQ);
5790 debug_printf_clean("freeing list %p from ctx %p\n",
5791 pctx->list_head, pctx);
5792 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005793 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005794 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005795#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005796 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005797#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005798 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005799 if (pctx != &ctx) {
5800 free(pctx);
5801 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005802 IF_HAS_KEYWORDS(pctx = p2;)
5803 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005804
Denys Vlasenko474cb202018-07-24 13:03:03 +02005805 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005806#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005807 if (pstring)
5808 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005809#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005810 debug_leave();
5811 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005812 }
Eric Andersen25f27032001-04-26 23:22:31 +00005813}
5814
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005815
5816/*** Execution routines ***/
5817
5818/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005819#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005820#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005821 expand_string_to_string(str)
5822#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005823static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005824#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005825static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005826#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005827static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828
5829/* expand_strvec_to_strvec() takes a list of strings, expands
5830 * all variable references within and returns a pointer to
5831 * a list of expanded strings, possibly with larger number
5832 * of strings. (Think VAR="a b"; echo $VAR).
5833 * This new list is allocated as a single malloc block.
5834 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005835 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005836 * Caller can deallocate entire list by single free(list). */
5837
Denys Vlasenko238081f2010-10-03 14:26:26 +02005838/* A horde of its helpers come first: */
5839
5840static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5841{
5842 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005843 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005844
Denys Vlasenko9e800222010-10-03 14:28:04 +02005845#if ENABLE_HUSH_BRACE_EXPANSION
5846 if (c == '{' || c == '}') {
5847 /* { -> \{, } -> \} */
5848 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005849 /* And now we want to add { or } and continue:
5850 * o_addchr(o, c);
5851 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005852 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005853 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005854 }
5855#endif
5856 o_addchr(o, c);
5857 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005858 /* \z -> \\\z; \<eol> -> \\<eol> */
5859 o_addchr(o, '\\');
5860 if (len) {
5861 len--;
5862 o_addchr(o, '\\');
5863 o_addchr(o, *str++);
5864 }
5865 }
5866 }
5867}
5868
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005869/* Store given string, finalizing the word and starting new one whenever
5870 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005871 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005872 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005873 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5874 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005875static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005876{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005877 int last_is_ifs = 0;
5878
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005879 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005880 int word_len;
5881
5882 if (!*str) /* EOL - do not finalize word */
5883 break;
5884 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005885 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005886 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005887 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005888 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005889 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005890 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005891 * Example: "v='\*'; echo b$v" prints "b\*"
5892 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005893 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005894 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005895 /*/ Why can't we do it easier? */
5896 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5897 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5898 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005899 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005900 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005901 if (!*str) /* EOL - do not finalize word */
5902 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005903 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005904
5905 /* We know str here points to at least one IFS char */
5906 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005907 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005908 if (!*str) /* EOL - do not finalize word */
5909 break;
5910
Denys Vlasenko96786362018-04-11 16:02:58 +02005911 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5912 && strchr(G.ifs, *str) /* the second check would fail */
5913 ) {
5914 /* This is a non-whitespace $IFS char */
5915 /* Skip it and IFS whitespace chars, start new word */
5916 str++;
5917 str += strspn(str, G.ifs_whitespace);
5918 goto new_word;
5919 }
5920
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005921 /* Start new word... but not always! */
5922 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005923 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005924 /*
5925 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005926 * here nothing precedes the space in $v expansion,
5927 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005928 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005929 * It's okay if this accesses the byte before first argv[]:
5930 * past call to o_save_ptr() cleared it to zero byte
5931 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005932 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005933 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005934 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005935 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005936 o_addchr(output, '\0');
5937 debug_print_list("expand_on_ifs", output, n);
5938 n = o_save_ptr(output, n);
5939 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005940 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005941
Denys Vlasenko168579a2018-07-19 13:45:54 +02005942 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005943 debug_print_list("expand_on_ifs[1]", output, n);
5944 return n;
5945}
5946
5947/* Helper to expand $((...)) and heredoc body. These act as if
5948 * they are in double quotes, with the exception that they are not :).
5949 * Just the rules are similar: "expand only $var and `cmd`"
5950 *
5951 * Returns malloced string.
5952 * As an optimization, we return NULL if expansion is not needed.
5953 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005954static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005955{
5956 char *exp_str;
5957 struct in_str input;
5958 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005959 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005960
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005961 cp = str;
5962 for (;;) {
5963 if (!*cp) return NULL; /* string has no special chars */
5964 if (*cp == '$') break;
5965 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005966#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005967 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005968#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005969 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005970 }
5971
5972 /* We need to expand. Example:
5973 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5974 */
5975 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005976 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005977//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005978 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005979 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005980 EXP_FLAG_ESC_GLOB_CHARS,
5981 /*unbackslash:*/ 1
5982 );
5983 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005984 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005985 return exp_str;
5986}
5987
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005988static const char *first_special_char_in_vararg(const char *cp)
5989{
5990 for (;;) {
5991 if (!*cp) return NULL; /* string has no special chars */
5992 if (*cp == '$') return cp;
5993 if (*cp == '\\') return cp;
5994 if (*cp == '\'') return cp;
5995 if (*cp == '"') return cp;
5996#if ENABLE_HUSH_TICK
5997 if (*cp == '`') return cp;
5998#endif
5999 /* dquoted "${x:+ARG}" should not glob, therefore
6000 * '*' et al require some non-literal processing: */
6001 if (*cp == '*') return cp;
6002 if (*cp == '?') return cp;
6003 if (*cp == '[') return cp;
6004 cp++;
6005 }
6006}
6007
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006008/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6009 * These can contain single- and double-quoted strings,
6010 * and treated as if the ARG string is initially unquoted. IOW:
6011 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6012 * a dquoted string: "${var#"zz"}"), the difference only comes later
6013 * (word splitting and globbing of the ${var...} result).
6014 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006015#if !BASH_PATTERN_SUBST
6016#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6017 encode_then_expand_vararg(str, handle_squotes)
6018#endif
6019static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6020{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006021#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006022 const int do_unbackslash = 0;
6023#endif
6024 char *exp_str;
6025 struct in_str input;
6026 o_string dest = NULL_O_STRING;
6027
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006028 if (!first_special_char_in_vararg(str)) {
6029 /* string has no special chars */
6030 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006031 }
6032
Denys Vlasenkob762c782018-07-17 14:21:38 +02006033 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006034 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006035 exp_str = NULL;
6036
6037 for (;;) {
6038 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006039
6040 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006041 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6042 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006043
6044 if (!dest.o_expflags) {
6045 if (ch == EOF)
6046 break;
6047 if (handle_squotes && ch == '\'') {
6048 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006049 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006050 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006051 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006052 }
6053 if (ch == EOF) {
6054 syntax_error_unterm_ch('"');
6055 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006056 }
6057 if (ch == '"') {
6058 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6059 continue;
6060 }
6061 if (ch == '\\') {
6062 ch = i_getch(&input);
6063 if (ch == EOF) {
6064//example? error message? syntax_error_unterm_ch('"');
6065 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6066 goto ret;
6067 }
6068 o_addqchr(&dest, ch);
6069 continue;
6070 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006071 if (ch == '$') {
6072 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6073 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6074 goto ret;
6075 }
6076 continue;
6077 }
6078#if ENABLE_HUSH_TICK
6079 if (ch == '`') {
6080 //unsigned pos = dest->length;
6081 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6082 o_addchr(&dest, 0x80 | '`');
6083 if (!add_till_backquote(&dest, &input,
6084 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6085 )
6086 ) {
6087 goto ret; /* error */
6088 }
6089 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6090 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6091 continue;
6092 }
6093#endif
6094 o_addQchr(&dest, ch);
6095 } /* for (;;) */
6096
6097 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6098 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006099 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6100 do_unbackslash
6101 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006102 ret:
6103 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006104 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006105 return exp_str;
6106}
6107
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006108/* Expanding ARG in ${var+ARG}, ${var-ARG}
6109 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006110static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006111 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006112{
6113 struct in_str input;
6114 o_string dest = NULL_O_STRING;
6115
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006116 if (!first_special_char_in_vararg(str)
6117 && '\0' == str[strcspn(str, G.ifs)]
6118 ) {
6119 /* string has no special chars
6120 * && string has no $IFS chars
6121 */
6122 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006123 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006124
Denys Vlasenko294eb462018-07-20 16:18:59 +02006125 setup_string_in_str(&input, str);
6126
6127 for (;;) {
6128 int ch;
6129
6130 ch = i_getch(&input);
6131 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6132 __func__, ch, ch, dest.o_expflags);
6133
6134 if (!dest.o_expflags) {
6135 if (ch == EOF)
6136 break;
6137 if (!dquoted && strchr(G.ifs, ch)) {
6138 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6139 * do not assume we are at the start of the word (PREFIX above).
6140 */
6141 if (dest.data) {
6142 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006143 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006144 o_addchr(output, '\0');
6145 n = o_save_ptr(output, n); /* create next word */
6146 } else
6147 if (output->length != o_get_last_ptr(output, n)
6148 || output->has_quoted_part
6149 ) {
6150 /* For these cases:
6151 * f() { for i; do echo "|$i|"; done; }; x=x
6152 * f a${x:+ }b # 1st condition
6153 * |a|
6154 * |b|
6155 * f ""${x:+ }b # 2nd condition
6156 * ||
6157 * |b|
6158 */
6159 o_addchr(output, '\0');
6160 n = o_save_ptr(output, n); /* create next word */
6161 }
6162 continue;
6163 }
6164 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006165 if (!add_till_single_quote_dquoted(&dest, &input))
6166 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006167 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6168 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006169 continue;
6170 }
6171 }
6172 if (ch == EOF) {
6173 syntax_error_unterm_ch('"');
6174 goto ret; /* error */
6175 }
6176 if (ch == '"') {
6177 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006178 if (dest.o_expflags) {
6179 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6180 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6181 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006182 continue;
6183 }
6184 if (ch == '\\') {
6185 ch = i_getch(&input);
6186 if (ch == EOF) {
6187//example? error message? syntax_error_unterm_ch('"');
6188 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6189 goto ret;
6190 }
6191 o_addqchr(&dest, ch);
6192 continue;
6193 }
6194 if (ch == '$') {
6195 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6196 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6197 goto ret;
6198 }
6199 continue;
6200 }
6201#if ENABLE_HUSH_TICK
6202 if (ch == '`') {
6203 //unsigned pos = dest->length;
6204 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6205 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6206 if (!add_till_backquote(&dest, &input,
6207 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6208 )
6209 ) {
6210 goto ret; /* error */
6211 }
6212 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6213 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6214 continue;
6215 }
6216#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006217 if (dquoted) {
6218 /* Always glob-protect if in dquotes:
6219 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6220 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6221 */
6222 o_addqchr(&dest, ch);
6223 } else {
6224 /* Glob-protect only if char is quoted:
6225 * x=x; echo ${x:+/bin/c*} - prints many filenames
6226 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6227 */
6228 o_addQchr(&dest, ch);
6229 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006230 } /* for (;;) */
6231
6232 if (dest.data) {
6233 n = expand_vars_to_list(output, n, dest.data);
6234 }
6235 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006236 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006237 return n;
6238}
6239
Denys Vlasenko0b883582016-12-23 16:49:07 +01006240#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006241static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006242{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006243 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006244 arith_t res;
6245 char *exp_str;
6246
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006247 math_state.lookupvar = get_local_var_value;
6248 math_state.setvar = set_local_var_from_halves;
6249 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006250 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006251 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006252 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006253 if (errmsg_p)
6254 *errmsg_p = math_state.errmsg;
6255 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006256 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006257 return res;
6258}
6259#endif
6260
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006261#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006262/* ${var/[/]pattern[/repl]} helpers */
6263static char *strstr_pattern(char *val, const char *pattern, int *size)
6264{
6265 while (1) {
6266 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6267 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6268 if (end) {
6269 *size = end - val;
6270 return val;
6271 }
6272 if (*val == '\0')
6273 return NULL;
6274 /* Optimization: if "*pat" did not match the start of "string",
6275 * we know that "tring", "ring" etc will not match too:
6276 */
6277 if (pattern[0] == '*')
6278 return NULL;
6279 val++;
6280 }
6281}
6282static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6283{
6284 char *result = NULL;
6285 unsigned res_len = 0;
6286 unsigned repl_len = strlen(repl);
6287
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006288 /* Null pattern never matches, including if "var" is empty */
6289 if (!pattern[0])
6290 return result; /* NULL, no replaces happened */
6291
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006292 while (1) {
6293 int size;
6294 char *s = strstr_pattern(val, pattern, &size);
6295 if (!s)
6296 break;
6297
6298 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006299 strcpy(mempcpy(result + res_len, val, s - val), repl);
6300 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006301 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6302
6303 val = s + size;
6304 if (exp_op == '/')
6305 break;
6306 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006307 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006308 result = xrealloc(result, res_len + strlen(val) + 1);
6309 strcpy(result + res_len, val);
6310 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6311 }
6312 debug_printf_varexp("result:'%s'\n", result);
6313 return result;
6314}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006315#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316
Denys Vlasenko168579a2018-07-19 13:45:54 +02006317static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006318 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006319{
6320 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6321 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6322 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6323 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006324 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006325 } else { /* quoted "$VAR" */
6326 output->has_quoted_part = 1;
6327 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6328 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6329 if (val && val[0])
6330 o_addQstr(output, val);
6331 }
6332 return n;
6333}
6334
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006335/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006336 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006337static NOINLINE int expand_one_var(o_string *output, int n,
6338 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006339{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006340 const char *val;
6341 char *to_be_freed;
6342 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006344 char exp_op;
6345 char exp_save = exp_save; /* for compiler */
6346 char *exp_saveptr; /* points to expansion operator */
6347 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006348 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006350 val = NULL;
6351 to_be_freed = NULL;
6352 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006353 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006354 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006356 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006357 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006358 exp_op = 0;
6359
Denys Vlasenkob762c782018-07-17 14:21:38 +02006360 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006361 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6362 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6363 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006364 ) {
6365 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006366 var++;
6367 exp_op = 'L';
6368 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006369 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006370 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006371 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006372 ) {
6373 /* ${?:0}, ${#[:]%0} etc */
6374 exp_saveptr = var + 1;
6375 } else {
6376 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6377 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6378 }
6379 exp_op = exp_save = *exp_saveptr;
6380 if (exp_op) {
6381 exp_word = exp_saveptr + 1;
6382 if (exp_op == ':') {
6383 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006384//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006385 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006386 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006387 ) {
6388 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6389 exp_op = ':';
6390 exp_word--;
6391 }
6392 }
6393 *exp_saveptr = '\0';
6394 } /* else: it's not an expansion op, but bare ${var} */
6395 }
6396
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006397 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006398 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006399 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006400 int nn = xatoi_positive(var);
6401 if (nn < G.global_argc)
6402 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403 /* else val remains NULL: $N with too big N */
6404 } else {
6405 switch (var[0]) {
6406 case '$': /* pid */
6407 val = utoa(G.root_pid);
6408 break;
6409 case '!': /* bg pid */
6410 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6411 break;
6412 case '?': /* exitcode */
6413 val = utoa(G.last_exitcode);
6414 break;
6415 case '#': /* argc */
6416 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6417 break;
6418 default:
6419 val = get_local_var_value(var);
6420 }
6421 }
6422
6423 /* Handle any expansions */
6424 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006425 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006426 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006427 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006428 debug_printf_expand("%s\n", val);
6429 } else if (exp_op) {
6430 if (exp_op == '%' || exp_op == '#') {
6431 /* Standard-mandated substring removal ops:
6432 * ${parameter%word} - remove smallest suffix pattern
6433 * ${parameter%%word} - remove largest suffix pattern
6434 * ${parameter#word} - remove smallest prefix pattern
6435 * ${parameter##word} - remove largest prefix pattern
6436 *
6437 * Word is expanded to produce a glob pattern.
6438 * Then var's value is matched to it and matching part removed.
6439 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006440//FIXME: ${x#...${...}...}
6441//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6442//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006443 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006444 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006445 char *exp_exp_word;
6446 char *loc;
6447 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006448 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006449 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006450 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006451 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006452 if (exp_exp_word)
6453 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006454 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6455 /*
6456 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006457 * G.global_argv and results of utoa and get_local_var_value
6458 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006459 * scan_and_match momentarily stores NULs there.
6460 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006461 t = (char*)val;
6462 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006463 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 +02006464 free(exp_exp_word);
6465 if (loc) { /* match was found */
6466 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006467 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006468 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006469 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006470 }
6471 }
6472 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006473#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006474 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006475 /* It's ${var/[/]pattern[/repl]} thing.
6476 * Note that in encoded form it has TWO parts:
6477 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006478 * and if // is used, it is encoded as \:
6479 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006480 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006481 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006482 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006483 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006484 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006485 * >az >bz
6486 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6487 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6488 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6489 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006490 * (note that a*z _pattern_ is never globbed!)
6491 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006492 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006493 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006494 if (!pattern)
6495 pattern = xstrdup(exp_word);
6496 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6497 *p++ = SPECIAL_VAR_SYMBOL;
6498 exp_word = p;
6499 p = strchr(p, SPECIAL_VAR_SYMBOL);
6500 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006501 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006502 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6503 /* HACK ALERT. We depend here on the fact that
6504 * G.global_argv and results of utoa and get_local_var_value
6505 * are actually in writable memory:
6506 * replace_pattern momentarily stores NULs there. */
6507 t = (char*)val;
6508 to_be_freed = replace_pattern(t,
6509 pattern,
6510 (repl ? repl : exp_word),
6511 exp_op);
6512 if (to_be_freed) /* at least one replace happened */
6513 val = to_be_freed;
6514 free(pattern);
6515 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006516 } else {
6517 /* Empty variable always gives nothing */
6518 // "v=''; echo ${v/*/w}" prints "", not "w"
6519 /* Just skip "replace" part */
6520 *p++ = SPECIAL_VAR_SYMBOL;
6521 p = strchr(p, SPECIAL_VAR_SYMBOL);
6522 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006523 }
6524 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006525#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006527#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006528 /* It's ${var:N[:M]} bashism.
6529 * Note that in encoded form it has TWO parts:
6530 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6531 */
6532 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006533 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006534
Denys Vlasenko063847d2010-09-15 13:33:02 +02006535 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6536 if (errmsg)
6537 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006538 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6539 *p++ = SPECIAL_VAR_SYMBOL;
6540 exp_word = p;
6541 p = strchr(p, SPECIAL_VAR_SYMBOL);
6542 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006543 len = expand_and_evaluate_arith(exp_word, &errmsg);
6544 if (errmsg)
6545 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006546 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006547 if (beg < 0) {
6548 /* negative beg counts from the end */
6549 beg = (arith_t)strlen(val) + beg;
6550 if (beg < 0) /* ${v: -999999} is "" */
6551 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006552 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006553 debug_printf_varexp("from val:'%s'\n", val);
6554 if (len < 0) {
6555 /* in bash, len=-n means strlen()-n */
6556 len = (arith_t)strlen(val) - beg + len;
6557 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006558 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006559 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006560 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006561 arith_err:
6562 val = NULL;
6563 } else {
6564 /* Paranoia. What if user entered 9999999999999
6565 * which fits in arith_t but not int? */
6566 if (len >= INT_MAX)
6567 len = INT_MAX;
6568 val = to_be_freed = xstrndup(val + beg, len);
6569 }
6570 debug_printf_varexp("val:'%s'\n", val);
6571#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006572 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006573 val = NULL;
6574#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006575 } else { /* one of "-=+?" */
6576 /* Standard-mandated substitution ops:
6577 * ${var?word} - indicate error if unset
6578 * If var is unset, word (or a message indicating it is unset
6579 * if word is null) is written to standard error
6580 * and the shell exits with a non-zero exit status.
6581 * Otherwise, the value of var is substituted.
6582 * ${var-word} - use default value
6583 * If var is unset, word is substituted.
6584 * ${var=word} - assign and use default value
6585 * If var is unset, word is assigned to var.
6586 * In all cases, final value of var is substituted.
6587 * ${var+word} - use alternative value
6588 * If var is unset, null is substituted.
6589 * Otherwise, word is substituted.
6590 *
6591 * Word is subjected to tilde expansion, parameter expansion,
6592 * command substitution, and arithmetic expansion.
6593 * If word is not needed, it is not expanded.
6594 *
6595 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6596 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006597 *
6598 * Word-splitting and single quote behavior:
6599 *
6600 * $ f() { for i; do echo "|$i|"; done; };
6601 *
6602 * $ x=; f ${x:?'x y' z}
6603 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6604 * $ x=; f "${x:?'x y' z}"
6605 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6606 *
6607 * $ x=; f ${x:='x y' z}
6608 * |x|
6609 * |y|
6610 * |z|
6611 * $ x=; f "${x:='x y' z}"
6612 * |'x y' z|
6613 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006614 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006615 * |x y|
6616 * |z|
6617 * $ x=x; f "${x:+'x y' z}"
6618 * |'x y' z|
6619 *
6620 * $ x=; f ${x:-'x y' z}
6621 * |x y|
6622 * |z|
6623 * $ x=; f "${x:-'x y' z}"
6624 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006625 */
6626 int use_word = (!val || ((exp_save == ':') && !val[0]));
6627 if (exp_op == '+')
6628 use_word = !use_word;
6629 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6630 (exp_save == ':') ? "true" : "false", use_word);
6631 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006632 if (exp_op == '+' || exp_op == '-') {
6633 /* ${var+word} - use alternative value */
6634 /* ${var-word} - use default value */
6635 n = encode_then_append_var_plusminus(output, n, exp_word,
6636 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006637 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006638 val = NULL;
6639 } else {
6640 /* ${var?word} - indicate error if unset */
6641 /* ${var=word} - assign and use default value */
6642 to_be_freed = encode_then_expand_vararg(exp_word,
6643 /*handle_squotes:*/ !(arg0 & 0x80),
6644 /*unbackslash:*/ 0
6645 );
6646 if (to_be_freed)
6647 exp_word = to_be_freed;
6648 if (exp_op == '?') {
6649 /* mimic bash message */
6650 msg_and_die_if_script("%s: %s",
6651 var,
6652 exp_word[0]
6653 ? exp_word
6654 : "parameter null or not set"
6655 /* ash has more specific messages, a-la: */
6656 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6657 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006658//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006659//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006660// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6661// bash: x: x y z
6662// $
6663// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006664 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006665 val = exp_word;
6666 }
6667 if (exp_op == '=') {
6668 /* ${var=[word]} or ${var:=[word]} */
6669 if (isdigit(var[0]) || var[0] == '#') {
6670 /* mimic bash message */
6671 msg_and_die_if_script("$%s: cannot assign in this way", var);
6672 val = NULL;
6673 } else {
6674 char *new_var = xasprintf("%s=%s", var, val);
6675 set_local_var(new_var, /*flag:*/ 0);
6676 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006677 }
6678 }
6679 }
6680 } /* one of "-=+?" */
6681
6682 *exp_saveptr = exp_save;
6683 } /* if (exp_op) */
6684
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006685 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006686 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006687
Denys Vlasenko168579a2018-07-19 13:45:54 +02006688 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006689
6690 free(to_be_freed);
6691 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006692}
6693
6694/* Expand all variable references in given string, adding words to list[]
6695 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6696 * to be filled). This routine is extremely tricky: has to deal with
6697 * variables/parameters with whitespace, $* and $@, and constructs like
6698 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006699static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006700{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006701 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006702 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006703 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006704 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006705 char *p;
6706
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006707 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6708 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006709 debug_print_list("expand_vars_to_list[0]", output, n);
6710
6711 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6712 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006713#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 char arith_buf[sizeof(arith_t)*3 + 2];
6715#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006716
Denys Vlasenko168579a2018-07-19 13:45:54 +02006717 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006718 o_addchr(output, '\0');
6719 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006720 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006721 }
6722
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006723 o_addblock(output, arg, p - arg);
6724 debug_print_list("expand_vars_to_list[1]", output, n);
6725 arg = ++p;
6726 p = strchr(p, SPECIAL_VAR_SYMBOL);
6727
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006728 /* Fetch special var name (if it is indeed one of them)
6729 * and quote bit, force the bit on if singleword expansion -
6730 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006731 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006732
6733 /* Is this variable quoted and thus expansion can't be null?
6734 * "$@" is special. Even if quoted, it can still
6735 * expand to nothing (not even an empty string),
6736 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006737 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006738 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006739
6740 switch (first_ch & 0x7f) {
6741 /* Highest bit in first_ch indicates that var is double-quoted */
6742 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006743 case '@': {
6744 int i;
6745 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006746 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006747 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006748 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006749 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006750 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006751 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006752 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6753 if (G.global_argv[i++][0] && G.global_argv[i]) {
6754 /* this argv[] is not empty and not last:
6755 * put terminating NUL, start new word */
6756 o_addchr(output, '\0');
6757 debug_print_list("expand_vars_to_list[2]", output, n);
6758 n = o_save_ptr(output, n);
6759 debug_print_list("expand_vars_to_list[3]", output, n);
6760 }
6761 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006763 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006764 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006765 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006766 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006767 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006768 while (1) {
6769 o_addQstr(output, G.global_argv[i]);
6770 if (++i >= G.global_argc)
6771 break;
6772 o_addchr(output, '\0');
6773 debug_print_list("expand_vars_to_list[4]", output, n);
6774 n = o_save_ptr(output, n);
6775 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006776 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006777 while (1) {
6778 o_addQstr(output, G.global_argv[i]);
6779 if (!G.global_argv[++i])
6780 break;
6781 if (G.ifs[0])
6782 o_addchr(output, G.ifs[0]);
6783 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006784 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006785 }
6786 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006787 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006788 case SPECIAL_VAR_SYMBOL: {
6789 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006790 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006791 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006792 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006793 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006794 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006795 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006796 case SPECIAL_VAR_QUOTED_SVS:
6797 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006798 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006799 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006800 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006801 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006802#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006803 case '`': {
6804 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006805 o_string subst_result = NULL_O_STRING;
6806
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006807 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006808 arg++;
6809 /* Can't just stuff it into output o_string,
6810 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006811 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006812 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6813 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006814 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006815 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006816 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006817 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006818 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006819 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006820#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006821#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006822 case '+': {
6823 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006824 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006825
6826 arg++; /* skip '+' */
6827 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6828 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006829 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006830 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6831 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006832 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006833 break;
6834 }
6835#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006836 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006837 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006838 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006839 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006840 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6841
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006842 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6843 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844 if (*p != SPECIAL_VAR_SYMBOL)
6845 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006846 arg = ++p;
6847 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6848
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006849 if (*arg) {
6850 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006851 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006852 o_addchr(output, '\0');
6853 n = o_save_ptr(output, n);
6854 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006855 debug_print_list("expand_vars_to_list[a]", output, n);
6856 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006857 * if needed (much earlier), do not use o_addQstr here!
6858 */
6859 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006860 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006861 } else
6862 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006863 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6864 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006865 ) {
6866 n--;
6867 /* allow to reuse list[n] later without re-growth */
6868 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006869 }
6870
6871 return n;
6872}
6873
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006874static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006875{
6876 int n;
6877 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006878 o_string output = NULL_O_STRING;
6879
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006880 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006881
6882 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006883 for (;;) {
6884 /* go to next list[n] */
6885 output.ended_in_ifs = 0;
6886 n = o_save_ptr(&output, n);
6887
6888 if (!*argv)
6889 break;
6890
6891 /* expand argv[i] */
6892 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006893 /* if (!output->has_empty_slot) -- need this?? */
6894 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006895 }
6896 debug_print_list("expand_variables", &output, n);
6897
6898 /* output.data (malloced in one block) gets returned in "list" */
6899 list = o_finalize_list(&output, n);
6900 debug_print_strings("expand_variables[1]", list);
6901 return list;
6902}
6903
6904static char **expand_strvec_to_strvec(char **argv)
6905{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006906 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006907}
6908
Denys Vlasenko11752d42018-04-03 08:20:58 +02006909#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006910static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6911{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006912 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913}
6914#endif
6915
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006916/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006917 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006918 *
6919 * NB: should NOT do globbing!
6920 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6921 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006922static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006923{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006924#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006925 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006926 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006927#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006928 char *argv[2], **list;
6929
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006930 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006931 /* This is generally an optimization, but it also
6932 * handles "", which otherwise trips over !list[0] check below.
6933 * (is this ever happens that we actually get str="" here?)
6934 */
6935 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6936 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006937 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006938 return xstrdup(str);
6939 }
6940
6941 argv[0] = (char*)str;
6942 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006943 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006944 if (!list[0]) {
6945 /* Example where it happens:
6946 * x=; echo ${x:-"$@"}
6947 */
6948 ((char*)list)[0] = '\0';
6949 } else {
6950 if (HUSH_DEBUG)
6951 if (list[1])
6952 bb_error_msg_and_die("BUG in varexp2");
6953 /* actually, just move string 2*sizeof(char*) bytes back */
6954 overlapping_strcpy((char*)list, list[0]);
6955 if (do_unbackslash)
6956 unbackslash((char*)list);
6957 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006958 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006959 return (char*)list;
6960}
6961
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006962#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006963static char* expand_strvec_to_string(char **argv)
6964{
6965 char **list;
6966
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006967 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006968 /* Convert all NULs to spaces */
6969 if (list[0]) {
6970 int n = 1;
6971 while (list[n]) {
6972 if (HUSH_DEBUG)
6973 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6974 bb_error_msg_and_die("BUG in varexp3");
6975 /* bash uses ' ' regardless of $IFS contents */
6976 list[n][-1] = ' ';
6977 n++;
6978 }
6979 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006980 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006981 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6982 return (char*)list;
6983}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006984#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006985
6986static char **expand_assignments(char **argv, int count)
6987{
6988 int i;
6989 char **p;
6990
6991 G.expanded_assignments = p = NULL;
6992 /* Expand assignments into one string each */
6993 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006994 p = add_string_to_strings(p,
6995 expand_string_to_string(argv[i],
6996 EXP_FLAG_ESC_GLOB_CHARS,
6997 /*unbackslash:*/ 1
6998 )
6999 );
7000 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007001 }
7002 G.expanded_assignments = NULL;
7003 return p;
7004}
7005
7006
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007007static void switch_off_special_sigs(unsigned mask)
7008{
7009 unsigned sig = 0;
7010 while ((mask >>= 1) != 0) {
7011 sig++;
7012 if (!(mask & 1))
7013 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007014#if ENABLE_HUSH_TRAP
7015 if (G_traps) {
7016 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007017 /* trap is '', has to remain SIG_IGN */
7018 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007019 free(G_traps[sig]);
7020 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007021 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007022#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007023 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007024 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007025 }
7026}
7027
Denys Vlasenkob347df92011-08-09 22:49:15 +02007028#if BB_MMU
7029/* never called */
7030void re_execute_shell(char ***to_free, const char *s,
7031 char *g_argv0, char **g_argv,
7032 char **builtin_argv) NORETURN;
7033
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007034static void reset_traps_to_defaults(void)
7035{
7036 /* This function is always called in a child shell
7037 * after fork (not vfork, NOMMU doesn't use this function).
7038 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007039 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007040 unsigned mask;
7041
7042 /* Child shells are not interactive.
7043 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7044 * Testcase: (while :; do :; done) + ^Z should background.
7045 * Same goes for SIGTERM, SIGHUP, SIGINT.
7046 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007047 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007048 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007049 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007050
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007051 /* Switch off special sigs */
7052 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007053# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007054 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007055# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007056 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007057 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7058 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007059
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007060# if ENABLE_HUSH_TRAP
7061 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007062 return;
7063
7064 /* Reset all sigs to default except ones with empty traps */
7065 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007066 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007067 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007068 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007069 continue; /* empty trap: has to remain SIG_IGN */
7070 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007071 free(G_traps[sig]);
7072 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007073 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007074 if (sig == 0)
7075 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007076 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007077 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007078# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079}
7080
7081#else /* !BB_MMU */
7082
7083static void re_execute_shell(char ***to_free, const char *s,
7084 char *g_argv0, char **g_argv,
7085 char **builtin_argv) NORETURN;
7086static void re_execute_shell(char ***to_free, const char *s,
7087 char *g_argv0, char **g_argv,
7088 char **builtin_argv)
7089{
7090# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7091 /* delims + 2 * (number of bytes in printed hex numbers) */
7092 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7093 char *heredoc_argv[4];
7094 struct variable *cur;
7095# if ENABLE_HUSH_FUNCTIONS
7096 struct function *funcp;
7097# endif
7098 char **argv, **pp;
7099 unsigned cnt;
7100 unsigned long long empty_trap_mask;
7101
7102 if (!g_argv0) { /* heredoc */
7103 argv = heredoc_argv;
7104 argv[0] = (char *) G.argv0_for_re_execing;
7105 argv[1] = (char *) "-<";
7106 argv[2] = (char *) s;
7107 argv[3] = NULL;
7108 pp = &argv[3]; /* used as pointer to empty environment */
7109 goto do_exec;
7110 }
7111
7112 cnt = 0;
7113 pp = builtin_argv;
7114 if (pp) while (*pp++)
7115 cnt++;
7116
7117 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007118 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007119 int sig;
7120 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007121 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007122 empty_trap_mask |= 1LL << sig;
7123 }
7124 }
7125
7126 sprintf(param_buf, NOMMU_HACK_FMT
7127 , (unsigned) G.root_pid
7128 , (unsigned) G.root_ppid
7129 , (unsigned) G.last_bg_pid
7130 , (unsigned) G.last_exitcode
7131 , cnt
7132 , empty_trap_mask
7133 IF_HUSH_LOOPS(, G.depth_of_loop)
7134 );
7135# undef NOMMU_HACK_FMT
7136 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7137 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7138 */
7139 cnt += 6;
7140 for (cur = G.top_var; cur; cur = cur->next) {
7141 if (!cur->flg_export || cur->flg_read_only)
7142 cnt += 2;
7143 }
7144# if ENABLE_HUSH_FUNCTIONS
7145 for (funcp = G.top_func; funcp; funcp = funcp->next)
7146 cnt += 3;
7147# endif
7148 pp = g_argv;
7149 while (*pp++)
7150 cnt++;
7151 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7152 *pp++ = (char *) G.argv0_for_re_execing;
7153 *pp++ = param_buf;
7154 for (cur = G.top_var; cur; cur = cur->next) {
7155 if (strcmp(cur->varstr, hush_version_str) == 0)
7156 continue;
7157 if (cur->flg_read_only) {
7158 *pp++ = (char *) "-R";
7159 *pp++ = cur->varstr;
7160 } else if (!cur->flg_export) {
7161 *pp++ = (char *) "-V";
7162 *pp++ = cur->varstr;
7163 }
7164 }
7165# if ENABLE_HUSH_FUNCTIONS
7166 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7167 *pp++ = (char *) "-F";
7168 *pp++ = funcp->name;
7169 *pp++ = funcp->body_as_string;
7170 }
7171# endif
7172 /* We can pass activated traps here. Say, -Tnn:trap_string
7173 *
7174 * However, POSIX says that subshells reset signals with traps
7175 * to SIG_DFL.
7176 * I tested bash-3.2 and it not only does that with true subshells
7177 * of the form ( list ), but with any forked children shells.
7178 * I set trap "echo W" WINCH; and then tried:
7179 *
7180 * { echo 1; sleep 20; echo 2; } &
7181 * while true; do echo 1; sleep 20; echo 2; break; done &
7182 * true | { echo 1; sleep 20; echo 2; } | cat
7183 *
7184 * In all these cases sending SIGWINCH to the child shell
7185 * did not run the trap. If I add trap "echo V" WINCH;
7186 * _inside_ group (just before echo 1), it works.
7187 *
7188 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007189 */
7190 *pp++ = (char *) "-c";
7191 *pp++ = (char *) s;
7192 if (builtin_argv) {
7193 while (*++builtin_argv)
7194 *pp++ = *builtin_argv;
7195 *pp++ = (char *) "";
7196 }
7197 *pp++ = g_argv0;
7198 while (*g_argv)
7199 *pp++ = *g_argv++;
7200 /* *pp = NULL; - is already there */
7201 pp = environ;
7202
7203 do_exec:
7204 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007205 /* Don't propagate SIG_IGN to the child */
7206 if (SPECIAL_JOBSTOP_SIGS != 0)
7207 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007208 execve(bb_busybox_exec_path, argv, pp);
7209 /* Fallback. Useful for init=/bin/hush usage etc */
7210 if (argv[0][0] == '/')
7211 execve(argv[0], argv, pp);
7212 xfunc_error_retval = 127;
7213 bb_error_msg_and_die("can't re-execute the shell");
7214}
7215#endif /* !BB_MMU */
7216
7217
7218static int run_and_free_list(struct pipe *pi);
7219
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007220/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007221 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7222 * end_trigger controls how often we stop parsing
7223 * NUL: parse all, execute, return
7224 * ';': parse till ';' or newline, execute, repeat till EOF
7225 */
7226static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007227{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007228 /* Why we need empty flag?
7229 * An obscure corner case "false; ``; echo $?":
7230 * empty command in `` should still set $? to 0.
7231 * But we can't just set $? to 0 at the start,
7232 * this breaks "false; echo `echo $?`" case.
7233 */
7234 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007235 while (1) {
7236 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007237
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007238#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007239 if (end_trigger == ';') {
7240 G.promptmode = 0; /* PS1 */
7241 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7242 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007243#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007244 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007245 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7246 /* If we are in "big" script
7247 * (not in `cmd` or something similar)...
7248 */
7249 if (pipe_list == ERR_PTR && end_trigger == ';') {
7250 /* Discard cached input (rest of line) */
7251 int ch = inp->last_char;
7252 while (ch != EOF && ch != '\n') {
7253 //bb_error_msg("Discarded:'%c'", ch);
7254 ch = i_getch(inp);
7255 }
7256 /* Force prompt */
7257 inp->p = NULL;
7258 /* This stream isn't empty */
7259 empty = 0;
7260 continue;
7261 }
7262 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007263 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007264 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007265 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007266 debug_print_tree(pipe_list, 0);
7267 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7268 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007269 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007270 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007271 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007272 }
Eric Andersen25f27032001-04-26 23:22:31 +00007273}
7274
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007275static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007276{
7277 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007278 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7279
Eric Andersen25f27032001-04-26 23:22:31 +00007280 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007281 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007282 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007283}
7284
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007285static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007286{
Eric Andersen25f27032001-04-26 23:22:31 +00007287 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007288 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007289
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007290 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007291 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007292 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007293 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007294}
7295
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007296#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007297static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007298{
7299 pid_t pid;
7300 int channel[2];
7301# if !BB_MMU
7302 char **to_free = NULL;
7303# endif
7304
7305 xpipe(channel);
7306 pid = BB_MMU ? xfork() : xvfork();
7307 if (pid == 0) { /* child */
7308 disable_restore_tty_pgrp_on_exit();
7309 /* Process substitution is not considered to be usual
7310 * 'command execution'.
7311 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7312 */
7313 bb_signals(0
7314 + (1 << SIGTSTP)
7315 + (1 << SIGTTIN)
7316 + (1 << SIGTTOU)
7317 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007318 close(channel[0]); /* NB: close _first_, then move fd! */
7319 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007320# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007321 /* Awful hack for `trap` or $(trap).
7322 *
7323 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7324 * contains an example where "trap" is executed in a subshell:
7325 *
7326 * save_traps=$(trap)
7327 * ...
7328 * eval "$save_traps"
7329 *
7330 * Standard does not say that "trap" in subshell shall print
7331 * parent shell's traps. It only says that its output
7332 * must have suitable form, but then, in the above example
7333 * (which is not supposed to be normative), it implies that.
7334 *
7335 * bash (and probably other shell) does implement it
7336 * (traps are reset to defaults, but "trap" still shows them),
7337 * but as a result, "trap" logic is hopelessly messed up:
7338 *
7339 * # trap
7340 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7341 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7342 * # true | trap <--- trap is in subshell - no output (ditto)
7343 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7344 * trap -- 'echo Ho' SIGWINCH
7345 * # echo `(trap)` <--- in subshell in subshell - output
7346 * trap -- 'echo Ho' SIGWINCH
7347 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7348 * trap -- 'echo Ho' SIGWINCH
7349 *
7350 * The rules when to forget and when to not forget traps
7351 * get really complex and nonsensical.
7352 *
7353 * Our solution: ONLY bare $(trap) or `trap` is special.
7354 */
7355 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007356 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007357 && skip_whitespace(s + 4)[0] == '\0'
7358 ) {
7359 static const char *const argv[] = { NULL, NULL };
7360 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007361 fflush_all(); /* important */
7362 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007363 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007364# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007365# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007366 /* Prevent it from trying to handle ctrl-z etc */
7367 IF_HUSH_JOB(G.run_list_level = 1;)
7368 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007369 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007370 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007371 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007372 parse_and_run_string(s);
7373 _exit(G.last_exitcode);
7374# else
7375 /* We re-execute after vfork on NOMMU. This makes this script safe:
7376 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7377 * huge=`cat BIG` # was blocking here forever
7378 * echo OK
7379 */
7380 re_execute_shell(&to_free,
7381 s,
7382 G.global_argv[0],
7383 G.global_argv + 1,
7384 NULL);
7385# endif
7386 }
7387
7388 /* parent */
7389 *pid_p = pid;
7390# if ENABLE_HUSH_FAST
7391 G.count_SIGCHLD++;
7392//bb_error_msg("[%d] fork in generate_stream_from_string:"
7393// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7394// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7395# endif
7396 enable_restore_tty_pgrp_on_exit();
7397# if !BB_MMU
7398 free(to_free);
7399# endif
7400 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007401 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007402}
7403
7404/* Return code is exit status of the process that is run. */
7405static int process_command_subs(o_string *dest, const char *s)
7406{
7407 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007408 pid_t pid;
7409 int status, ch, eol_cnt;
7410
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007411 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007412
7413 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007414 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007415 while ((ch = getc(fp)) != EOF) {
7416 if (ch == '\0')
7417 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007418 if (ch == '\n') {
7419 eol_cnt++;
7420 continue;
7421 }
7422 while (eol_cnt) {
7423 o_addchr(dest, '\n');
7424 eol_cnt--;
7425 }
7426 o_addQchr(dest, ch);
7427 }
7428
7429 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007430 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007431 /* We need to extract exitcode. Test case
7432 * "true; echo `sleep 1; false` $?"
7433 * should print 1 */
7434 safe_waitpid(pid, &status, 0);
7435 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7436 return WEXITSTATUS(status);
7437}
7438#endif /* ENABLE_HUSH_TICK */
7439
7440
7441static void setup_heredoc(struct redir_struct *redir)
7442{
7443 struct fd_pair pair;
7444 pid_t pid;
7445 int len, written;
7446 /* the _body_ of heredoc (misleading field name) */
7447 const char *heredoc = redir->rd_filename;
7448 char *expanded;
7449#if !BB_MMU
7450 char **to_free;
7451#endif
7452
7453 expanded = NULL;
7454 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007455 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007456 if (expanded)
7457 heredoc = expanded;
7458 }
7459 len = strlen(heredoc);
7460
7461 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7462 xpiped_pair(pair);
7463 xmove_fd(pair.rd, redir->rd_fd);
7464
7465 /* Try writing without forking. Newer kernels have
7466 * dynamically growing pipes. Must use non-blocking write! */
7467 ndelay_on(pair.wr);
7468 while (1) {
7469 written = write(pair.wr, heredoc, len);
7470 if (written <= 0)
7471 break;
7472 len -= written;
7473 if (len == 0) {
7474 close(pair.wr);
7475 free(expanded);
7476 return;
7477 }
7478 heredoc += written;
7479 }
7480 ndelay_off(pair.wr);
7481
7482 /* Okay, pipe buffer was not big enough */
7483 /* Note: we must not create a stray child (bastard? :)
7484 * for the unsuspecting parent process. Child creates a grandchild
7485 * and exits before parent execs the process which consumes heredoc
7486 * (that exec happens after we return from this function) */
7487#if !BB_MMU
7488 to_free = NULL;
7489#endif
7490 pid = xvfork();
7491 if (pid == 0) {
7492 /* child */
7493 disable_restore_tty_pgrp_on_exit();
7494 pid = BB_MMU ? xfork() : xvfork();
7495 if (pid != 0)
7496 _exit(0);
7497 /* grandchild */
7498 close(redir->rd_fd); /* read side of the pipe */
7499#if BB_MMU
7500 full_write(pair.wr, heredoc, len); /* may loop or block */
7501 _exit(0);
7502#else
7503 /* Delegate blocking writes to another process */
7504 xmove_fd(pair.wr, STDOUT_FILENO);
7505 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7506#endif
7507 }
7508 /* parent */
7509#if ENABLE_HUSH_FAST
7510 G.count_SIGCHLD++;
7511//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7512#endif
7513 enable_restore_tty_pgrp_on_exit();
7514#if !BB_MMU
7515 free(to_free);
7516#endif
7517 close(pair.wr);
7518 free(expanded);
7519 wait(NULL); /* wait till child has died */
7520}
7521
Denys Vlasenko2db74612017-07-07 22:07:28 +02007522struct squirrel {
7523 int orig_fd;
7524 int moved_to;
7525 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7526 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7527};
7528
Denys Vlasenko621fc502017-07-24 12:42:17 +02007529static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7530{
7531 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7532 sq[i].orig_fd = orig;
7533 sq[i].moved_to = moved;
7534 sq[i+1].orig_fd = -1; /* end marker */
7535 return sq;
7536}
7537
Denys Vlasenko2db74612017-07-07 22:07:28 +02007538static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7539{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007540 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007541 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007542
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007543 i = 0;
7544 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007545 /* If we collide with an already moved fd... */
7546 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007547 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007548 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7549 if (sq[i].moved_to < 0) /* what? */
7550 xfunc_die();
7551 return sq;
7552 }
7553 if (fd == sq[i].orig_fd) {
7554 /* Example: echo Hello >/dev/null 1>&2 */
7555 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7556 return sq;
7557 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007558 }
7559
Denys Vlasenko2db74612017-07-07 22:07:28 +02007560 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007561 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007562 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7563 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007564 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007565 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007566}
7567
Denys Vlasenko657e9002017-07-30 23:34:04 +02007568static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7569{
7570 int i;
7571
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007572 i = 0;
7573 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007574 /* If we collide with an already moved fd... */
7575 if (fd == sq[i].orig_fd) {
7576 /* Examples:
7577 * "echo 3>FILE 3>&- 3>FILE"
7578 * "echo 3>&- 3>FILE"
7579 * No need for last redirect to insert
7580 * another "need to close 3" indicator.
7581 */
7582 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7583 return sq;
7584 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007585 }
7586
7587 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7588 return append_squirrel(sq, i, fd, -1);
7589}
7590
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007591/* fd: redirect wants this fd to be used (e.g. 3>file).
7592 * Move all conflicting internally used fds,
7593 * and remember them so that we can restore them later.
7594 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007595static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007596{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007597 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7598 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007599
7600#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007601 if (fd == G.interactive_fd) {
7602 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007603 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007604 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7605 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007606 }
7607#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007608 /* Are we called from setup_redirects(squirrel==NULL)
7609 * in redirect in a [v]forked child?
7610 */
7611 if (sqp == NULL) {
7612 /* No need to move script fds.
7613 * For NOMMU case, it's actively wrong: we'd change ->fd
7614 * fields in memory for the parent, but parent's fds
7615 * aren't be moved, it would use wrong fd!
7616 * Reproducer: "cmd 3>FILE" in script.
7617 * If we would call move_HFILEs_on_redirect(), child would:
7618 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7619 * close(3) = 0
7620 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7621 */
7622 //bb_error_msg("sqp == NULL: [v]forked child");
7623 return 0;
7624 }
7625
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007626 /* If this one of script's fds? */
7627 if (move_HFILEs_on_redirect(fd, avoid_fd))
7628 return 1; /* yes. "we closed fd" (actually moved it) */
7629
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007630 /* Are we called for "exec 3>FILE"? Came through
7631 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7632 * This case used to fail for this script:
7633 * exec 3>FILE
7634 * echo Ok
7635 * ...100000 more lines...
7636 * echo Ok
7637 * as follows:
7638 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7639 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7640 * dup2(4, 3) = 3
7641 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7642 * close(4) = 0
7643 * write(1, "Ok\n", 3) = 3
7644 * ... = 3
7645 * write(1, "Ok\n", 3) = 3
7646 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7647 * ^^^^^^^^ oops, wrong fd!!!
7648 * With this case separate from sqp == NULL and *after* move_HFILEs,
7649 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007650 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007651 if (sqp == ERR_PTR) {
7652 /* Don't preserve redirected fds: exec is _meant_ to change these */
7653 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007654 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007655 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007656
Denys Vlasenko2db74612017-07-07 22:07:28 +02007657 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7658 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7659 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007660}
7661
Denys Vlasenko2db74612017-07-07 22:07:28 +02007662static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007663{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007664 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007665 int i;
7666 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007667 if (sq[i].moved_to >= 0) {
7668 /* We simply die on error */
7669 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7670 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7671 } else {
7672 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7673 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7674 close(sq[i].orig_fd);
7675 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007676 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007677 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007678 }
7679
Denys Vlasenko2db74612017-07-07 22:07:28 +02007680 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007681}
7682
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007683#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007684static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007685{
7686 if (G_interactive_fd)
7687 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007688 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007689}
7690#endif
7691
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007692static int internally_opened_fd(int fd, struct squirrel *sq)
7693{
7694 int i;
7695
7696#if ENABLE_HUSH_INTERACTIVE
7697 if (fd == G.interactive_fd)
7698 return 1;
7699#endif
7700 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007701 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007702 return 1;
7703
7704 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7705 if (fd == sq[i].moved_to)
7706 return 1;
7707 }
7708 return 0;
7709}
7710
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007711/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7712 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007713static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007714{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007715 struct redir_struct *redir;
7716
7717 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007718 int newfd;
7719 int closed;
7720
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007721 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007722 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007723 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007724 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7725 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007726 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007727 redir->rd_filename);
7728 setup_heredoc(redir);
7729 continue;
7730 }
7731
7732 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007733 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007734 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007735 int mode;
7736
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007737 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007738 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007739 * "cmd >" (no filename)
7740 * "cmd > <file" (2nd redirect starts too early)
7741 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007742 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007743 continue;
7744 }
7745 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007746 p = expand_string_to_string(redir->rd_filename,
7747 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007748 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007749 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007750 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007751 /* Error message from open_or_warn can be lost
7752 * if stderr has been redirected, but bash
7753 * and ash both lose it as well
7754 * (though zsh doesn't!)
7755 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007756 return 1;
7757 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007758 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007759 /* open() gave us precisely the fd we wanted.
7760 * This means that this fd was not busy
7761 * (not opened to anywhere).
7762 * Remember to close it on restore:
7763 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007764 *sqp = add_squirrel_closed(*sqp, newfd);
7765 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007766 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007767 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007768 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7769 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007770 }
7771
Denys Vlasenko657e9002017-07-30 23:34:04 +02007772 if (newfd == redir->rd_fd)
7773 continue;
7774
7775 /* if "N>FILE": move newfd to redir->rd_fd */
7776 /* if "N>&M": dup newfd to redir->rd_fd */
7777 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7778
7779 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7780 if (newfd == REDIRFD_CLOSE) {
7781 /* "N>&-" means "close me" */
7782 if (!closed) {
7783 /* ^^^ optimization: saving may already
7784 * have closed it. If not... */
7785 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007786 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007787 /* Sometimes we do another close on restore, getting EBADF.
7788 * Consider "echo 3>FILE 3>&-"
7789 * first redirect remembers "need to close 3",
7790 * and second redirect closes 3! Restore code then closes 3 again.
7791 */
7792 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007793 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007794 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007795 //errno = EBADF;
7796 //bb_perror_msg_and_die("can't duplicate file descriptor");
7797 newfd = -1; /* same effect as code above */
7798 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007799 xdup2(newfd, redir->rd_fd);
7800 if (redir->rd_dup == REDIRFD_TO_FILE)
7801 /* "rd_fd > FILE" */
7802 close(newfd);
7803 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007804 }
7805 }
7806 return 0;
7807}
7808
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007809static char *find_in_path(const char *arg)
7810{
7811 char *ret = NULL;
7812 const char *PATH = get_local_var_value("PATH");
7813
7814 if (!PATH)
7815 return NULL;
7816
7817 while (1) {
7818 const char *end = strchrnul(PATH, ':');
7819 int sz = end - PATH; /* must be int! */
7820
7821 free(ret);
7822 if (sz != 0) {
7823 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7824 } else {
7825 /* We have xxx::yyyy in $PATH,
7826 * it means "use current dir" */
7827 ret = xstrdup(arg);
7828 }
7829 if (access(ret, F_OK) == 0)
7830 break;
7831
7832 if (*end == '\0') {
7833 free(ret);
7834 return NULL;
7835 }
7836 PATH = end + 1;
7837 }
7838
7839 return ret;
7840}
7841
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007842static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007843 const struct built_in_command *x,
7844 const struct built_in_command *end)
7845{
7846 while (x != end) {
7847 if (strcmp(name, x->b_cmd) != 0) {
7848 x++;
7849 continue;
7850 }
7851 debug_printf_exec("found builtin '%s'\n", name);
7852 return x;
7853 }
7854 return NULL;
7855}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007856static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007857{
7858 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7859}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007860static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007861{
7862 const struct built_in_command *x = find_builtin1(name);
7863 if (x)
7864 return x;
7865 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7866}
7867
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007868static void remove_nested_vars(void)
7869{
7870 struct variable *cur;
7871 struct variable **cur_pp;
7872
7873 cur_pp = &G.top_var;
7874 while ((cur = *cur_pp) != NULL) {
7875 if (cur->var_nest_level <= G.var_nest_level) {
7876 cur_pp = &cur->next;
7877 continue;
7878 }
7879 /* Unexport */
7880 if (cur->flg_export) {
7881 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7882 bb_unsetenv(cur->varstr);
7883 }
7884 /* Remove from global list */
7885 *cur_pp = cur->next;
7886 /* Free */
7887 if (!cur->max_len) {
7888 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7889 free(cur->varstr);
7890 }
7891 free(cur);
7892 }
7893}
7894
7895static void enter_var_nest_level(void)
7896{
7897 G.var_nest_level++;
7898 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7899
7900 /* Try: f() { echo -n .; f; }; f
7901 * struct variable::var_nest_level is uint16_t,
7902 * thus limiting recursion to < 2^16.
7903 * In any case, with 8 Mbyte stack SEGV happens
7904 * not too long after 2^16 recursions anyway.
7905 */
7906 if (G.var_nest_level > 0xff00)
7907 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7908}
7909
7910static void leave_var_nest_level(void)
7911{
7912 G.var_nest_level--;
7913 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7914 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7915 bb_error_msg_and_die("BUG: nesting underflow");
7916
7917 remove_nested_vars();
7918}
7919
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007920#if ENABLE_HUSH_FUNCTIONS
7921static struct function **find_function_slot(const char *name)
7922{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007923 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007924 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007925
7926 while ((funcp = *funcpp) != NULL) {
7927 if (strcmp(name, funcp->name) == 0) {
7928 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007929 break;
7930 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007931 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007932 }
7933 return funcpp;
7934}
7935
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007936static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007937{
7938 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007939 return funcp;
7940}
7941
7942/* Note: takes ownership on name ptr */
7943static struct function *new_function(char *name)
7944{
7945 struct function **funcpp = find_function_slot(name);
7946 struct function *funcp = *funcpp;
7947
7948 if (funcp != NULL) {
7949 struct command *cmd = funcp->parent_cmd;
7950 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7951 if (!cmd) {
7952 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7953 free(funcp->name);
7954 /* Note: if !funcp->body, do not free body_as_string!
7955 * This is a special case of "-F name body" function:
7956 * body_as_string was not malloced! */
7957 if (funcp->body) {
7958 free_pipe_list(funcp->body);
7959# if !BB_MMU
7960 free(funcp->body_as_string);
7961# endif
7962 }
7963 } else {
7964 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7965 cmd->argv[0] = funcp->name;
7966 cmd->group = funcp->body;
7967# if !BB_MMU
7968 cmd->group_as_string = funcp->body_as_string;
7969# endif
7970 }
7971 } else {
7972 debug_printf_exec("remembering new function '%s'\n", name);
7973 funcp = *funcpp = xzalloc(sizeof(*funcp));
7974 /*funcp->next = NULL;*/
7975 }
7976
7977 funcp->name = name;
7978 return funcp;
7979}
7980
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007981# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007982static void unset_func(const char *name)
7983{
7984 struct function **funcpp = find_function_slot(name);
7985 struct function *funcp = *funcpp;
7986
7987 if (funcp != NULL) {
7988 debug_printf_exec("freeing function '%s'\n", funcp->name);
7989 *funcpp = funcp->next;
7990 /* funcp is unlinked now, deleting it.
7991 * Note: if !funcp->body, the function was created by
7992 * "-F name body", do not free ->body_as_string
7993 * and ->name as they were not malloced. */
7994 if (funcp->body) {
7995 free_pipe_list(funcp->body);
7996 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007997# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007998 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007999# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008000 }
8001 free(funcp);
8002 }
8003}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008004# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008005
8006# if BB_MMU
8007#define exec_function(to_free, funcp, argv) \
8008 exec_function(funcp, argv)
8009# endif
8010static void exec_function(char ***to_free,
8011 const struct function *funcp,
8012 char **argv) NORETURN;
8013static void exec_function(char ***to_free,
8014 const struct function *funcp,
8015 char **argv)
8016{
8017# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008018 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008019
8020 argv[0] = G.global_argv[0];
8021 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008022 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008023
8024// Example when we are here: "cmd | func"
8025// func will run with saved-redirect fds open.
8026// $ f() { echo /proc/self/fd/*; }
8027// $ true | f
8028// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8029// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8030// Same in script:
8031// $ . ./SCRIPT
8032// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8033// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8034// They are CLOEXEC so external programs won't see them, but
8035// for "more correctness" we might want to close those extra fds here:
8036//? close_saved_fds_and_FILE_fds();
8037
Denys Vlasenko332e4112018-04-04 22:32:59 +02008038 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008039 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008040 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008041 IF_HUSH_LOCAL(G.func_nest_level++;)
8042
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008043 /* On MMU, funcp->body is always non-NULL */
8044 n = run_list(funcp->body);
8045 fflush_all();
8046 _exit(n);
8047# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008048//? close_saved_fds_and_FILE_fds();
8049
8050//TODO: check whether "true | func_with_return" works
8051
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008052 re_execute_shell(to_free,
8053 funcp->body_as_string,
8054 G.global_argv[0],
8055 argv + 1,
8056 NULL);
8057# endif
8058}
8059
8060static int run_function(const struct function *funcp, char **argv)
8061{
8062 int rc;
8063 save_arg_t sv;
8064 smallint sv_flg;
8065
8066 save_and_replace_G_args(&sv, argv);
8067
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008068 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008069 sv_flg = G_flag_return_in_progress;
8070 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008071
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008072 /* Make "local" variables properly shadow previous ones */
8073 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008074 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008075
8076 /* On MMU, funcp->body is always non-NULL */
8077# if !BB_MMU
8078 if (!funcp->body) {
8079 /* Function defined by -F */
8080 parse_and_run_string(funcp->body_as_string);
8081 rc = G.last_exitcode;
8082 } else
8083# endif
8084 {
8085 rc = run_list(funcp->body);
8086 }
8087
Denys Vlasenko332e4112018-04-04 22:32:59 +02008088 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008089 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008090
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008091 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008092
8093 restore_G_args(&sv, argv);
8094
8095 return rc;
8096}
8097#endif /* ENABLE_HUSH_FUNCTIONS */
8098
8099
8100#if BB_MMU
8101#define exec_builtin(to_free, x, argv) \
8102 exec_builtin(x, argv)
8103#else
8104#define exec_builtin(to_free, x, argv) \
8105 exec_builtin(to_free, argv)
8106#endif
8107static void exec_builtin(char ***to_free,
8108 const struct built_in_command *x,
8109 char **argv) NORETURN;
8110static void exec_builtin(char ***to_free,
8111 const struct built_in_command *x,
8112 char **argv)
8113{
8114#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008115 int rcode;
8116 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008117//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008118 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008119 fflush_all();
8120 _exit(rcode);
8121#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008122 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008123 /* On NOMMU, we must never block!
8124 * Example: { sleep 99 | read line; } & echo Ok
8125 */
8126 re_execute_shell(to_free,
8127 argv[0],
8128 G.global_argv[0],
8129 G.global_argv + 1,
8130 argv);
8131#endif
8132}
8133
8134
8135static void execvp_or_die(char **argv) NORETURN;
8136static void execvp_or_die(char **argv)
8137{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008138 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008139 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008140 /* Don't propagate SIG_IGN to the child */
8141 if (SPECIAL_JOBSTOP_SIGS != 0)
8142 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008143 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008144 e = 2;
8145 if (errno == EACCES) e = 126;
8146 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008147 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008148 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008149}
8150
8151#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008152static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008153{
8154 unsigned len;
8155 const char *cp;
8156
8157 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008158
8159 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8160 /* test a char with: bash -c 'set -x; echo "CH"' */
8161 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8162 " " "\001\002\003\004\005\006\007"
8163 "\010\011\012\013\014\015\016\017"
8164 "\020\021\022\023\024\025\026\027"
8165 "\030\031\032\033\034\035\036\037"
8166 )
8167 ] == '\0'
8168 ) {
8169 /* string has no special chars */
8170 x_mode_addstr(str);
8171 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008172 }
8173
8174 cp = str;
8175 for (;;) {
8176 /* print '....' up to EOL or first squote */
8177 len = (int)(strchrnul(cp, '\'') - cp);
8178 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008179 x_mode_addchr('\'');
8180 x_mode_addblock(cp, len);
8181 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008182 cp += len;
8183 }
8184 if (*cp == '\0')
8185 break;
8186 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008187 x_mode_addchr('\\');
8188 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008189 cp++;
8190 }
8191}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008192static void dump_cmd_in_x_mode(char **argv)
8193{
8194 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008195 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008196
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008197 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008198 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008199 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008200 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008201 x_mode_addchr(' ');
8202 if (argv[n][0] == '\0') {
8203 x_mode_addchr('\'');
8204 x_mode_addchr('\'');
8205 } else {
8206 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008207 }
8208 n++;
8209 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008210 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008211 }
8212}
8213#else
8214# define dump_cmd_in_x_mode(argv) ((void)0)
8215#endif
8216
Denys Vlasenko57000292018-01-12 14:41:45 +01008217#if ENABLE_HUSH_COMMAND
8218static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8219{
8220 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008221
Denys Vlasenko57000292018-01-12 14:41:45 +01008222 if (!opt_vV)
8223 return;
8224
8225 to_free = NULL;
8226 if (!explanation) {
8227 char *path = getenv("PATH");
8228 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008229 if (!explanation)
8230 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008231 if (opt_vV != 'V')
8232 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8233 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008234 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008235 free(to_free);
8236 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008237 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008238}
8239#else
8240# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8241#endif
8242
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008243#if BB_MMU
8244#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8245 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8246#define pseudo_exec(nommu_save, command, argv_expanded) \
8247 pseudo_exec(command, argv_expanded)
8248#endif
8249
8250/* Called after [v]fork() in run_pipe, or from builtin_exec.
8251 * Never returns.
8252 * Don't exit() here. If you don't exec, use _exit instead.
8253 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008254 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008255 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008256static void pseudo_exec_argv(nommu_save_t *nommu_save,
8257 char **argv, int assignment_cnt,
8258 char **argv_expanded) NORETURN;
8259static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8260 char **argv, int assignment_cnt,
8261 char **argv_expanded)
8262{
Denys Vlasenko57000292018-01-12 14:41:45 +01008263 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008264 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008265 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008266 IF_HUSH_COMMAND(char opt_vV = 0;)
8267 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008268
8269 new_env = expand_assignments(argv, assignment_cnt);
8270 dump_cmd_in_x_mode(new_env);
8271
8272 if (!argv[assignment_cnt]) {
8273 /* Case when we are here: ... | var=val | ...
8274 * (note that we do not exit early, i.e., do not optimize out
8275 * expand_assignments(): think about ... | var=`sleep 1` | ...
8276 */
8277 free_strings(new_env);
8278 _exit(EXIT_SUCCESS);
8279 }
8280
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008281 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008282#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008283 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008284#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008285 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008286 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008287#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008288 set_vars_and_save_old(new_env);
8289 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008290
8291 if (argv_expanded) {
8292 argv = argv_expanded;
8293 } else {
8294 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8295#if !BB_MMU
8296 nommu_save->argv = argv;
8297#endif
8298 }
8299 dump_cmd_in_x_mode(argv);
8300
8301#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8302 if (strchr(argv[0], '/') != NULL)
8303 goto skip;
8304#endif
8305
Denys Vlasenko75481d32017-07-31 05:27:09 +02008306#if ENABLE_HUSH_FUNCTIONS
8307 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008308 funcp = find_function(argv[0]);
8309 if (funcp)
8310 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008311#endif
8312
Denys Vlasenko57000292018-01-12 14:41:45 +01008313#if ENABLE_HUSH_COMMAND
8314 /* "command BAR": run BAR without looking it up among functions
8315 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8316 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8317 */
8318 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8319 char *p;
8320
8321 argv++;
8322 p = *argv;
8323 if (p[0] != '-' || !p[1])
8324 continue; /* bash allows "command command command [-OPT] BAR" */
8325
8326 for (;;) {
8327 p++;
8328 switch (*p) {
8329 case '\0':
8330 argv++;
8331 p = *argv;
8332 if (p[0] != '-' || !p[1])
8333 goto after_opts;
8334 continue; /* next arg is also -opts, process it too */
8335 case 'v':
8336 case 'V':
8337 opt_vV = *p;
8338 continue;
8339 default:
8340 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8341 }
8342 }
8343 }
8344 after_opts:
8345# if ENABLE_HUSH_FUNCTIONS
8346 if (opt_vV && find_function(argv[0]))
8347 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8348# endif
8349#endif
8350
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008351 /* Check if the command matches any of the builtins.
8352 * Depending on context, this might be redundant. But it's
8353 * easier to waste a few CPU cycles than it is to figure out
8354 * if this is one of those cases.
8355 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008356 /* Why "BB_MMU ? :" difference in logic? -
8357 * On NOMMU, it is more expensive to re-execute shell
8358 * just in order to run echo or test builtin.
8359 * It's better to skip it here and run corresponding
8360 * non-builtin later. */
8361 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8362 if (x) {
8363 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8364 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008365 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008366
8367#if ENABLE_FEATURE_SH_STANDALONE
8368 /* Check if the command matches any busybox applets */
8369 {
8370 int a = find_applet_by_name(argv[0]);
8371 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008372 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008373# if BB_MMU /* see above why on NOMMU it is not allowed */
8374 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008375 /* Do not leak open fds from opened script files etc.
8376 * Testcase: interactive "ls -l /proc/self/fd"
8377 * should not show tty fd open.
8378 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008379 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008380//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008381//This casuses test failures in
8382//redir_children_should_not_see_saved_fd_2.tests
8383//redir_children_should_not_see_saved_fd_3.tests
8384//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008385 /* Without this, "rm -i FILE" can't be ^C'ed: */
8386 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008387 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008388 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008389 }
8390# endif
8391 /* Re-exec ourselves */
8392 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008393 /* Don't propagate SIG_IGN to the child */
8394 if (SPECIAL_JOBSTOP_SIGS != 0)
8395 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008396 execv(bb_busybox_exec_path, argv);
8397 /* If they called chroot or otherwise made the binary no longer
8398 * executable, fall through */
8399 }
8400 }
8401#endif
8402
8403#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8404 skip:
8405#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008406 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008407 execvp_or_die(argv);
8408}
8409
8410/* Called after [v]fork() in run_pipe
8411 */
8412static void pseudo_exec(nommu_save_t *nommu_save,
8413 struct command *command,
8414 char **argv_expanded) NORETURN;
8415static void pseudo_exec(nommu_save_t *nommu_save,
8416 struct command *command,
8417 char **argv_expanded)
8418{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008419#if ENABLE_HUSH_FUNCTIONS
8420 if (command->cmd_type == CMD_FUNCDEF) {
8421 /* Ignore funcdefs in pipes:
8422 * true | f() { cmd }
8423 */
8424 _exit(0);
8425 }
8426#endif
8427
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008428 if (command->argv) {
8429 pseudo_exec_argv(nommu_save, command->argv,
8430 command->assignment_cnt, argv_expanded);
8431 }
8432
8433 if (command->group) {
8434 /* Cases when we are here:
8435 * ( list )
8436 * { list } &
8437 * ... | ( list ) | ...
8438 * ... | { list } | ...
8439 */
8440#if BB_MMU
8441 int rcode;
8442 debug_printf_exec("pseudo_exec: run_list\n");
8443 reset_traps_to_defaults();
8444 rcode = run_list(command->group);
8445 /* OK to leak memory by not calling free_pipe_list,
8446 * since this process is about to exit */
8447 _exit(rcode);
8448#else
8449 re_execute_shell(&nommu_save->argv_from_re_execing,
8450 command->group_as_string,
8451 G.global_argv[0],
8452 G.global_argv + 1,
8453 NULL);
8454#endif
8455 }
8456
8457 /* Case when we are here: ... | >file */
8458 debug_printf_exec("pseudo_exec'ed null command\n");
8459 _exit(EXIT_SUCCESS);
8460}
8461
8462#if ENABLE_HUSH_JOB
8463static const char *get_cmdtext(struct pipe *pi)
8464{
8465 char **argv;
8466 char *p;
8467 int len;
8468
8469 /* This is subtle. ->cmdtext is created only on first backgrounding.
8470 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8471 * On subsequent bg argv is trashed, but we won't use it */
8472 if (pi->cmdtext)
8473 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008474
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008475 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008476 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008477 pi->cmdtext = xzalloc(1);
8478 return pi->cmdtext;
8479 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008480 len = 0;
8481 do {
8482 len += strlen(*argv) + 1;
8483 } while (*++argv);
8484 p = xmalloc(len);
8485 pi->cmdtext = p;
8486 argv = pi->cmds[0].argv;
8487 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008488 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008489 *p++ = ' ';
8490 } while (*++argv);
8491 p[-1] = '\0';
8492 return pi->cmdtext;
8493}
8494
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008495static void remove_job_from_table(struct pipe *pi)
8496{
8497 struct pipe *prev_pipe;
8498
8499 if (pi == G.job_list) {
8500 G.job_list = pi->next;
8501 } else {
8502 prev_pipe = G.job_list;
8503 while (prev_pipe->next != pi)
8504 prev_pipe = prev_pipe->next;
8505 prev_pipe->next = pi->next;
8506 }
8507 G.last_jobid = 0;
8508 if (G.job_list)
8509 G.last_jobid = G.job_list->jobid;
8510}
8511
8512static void delete_finished_job(struct pipe *pi)
8513{
8514 remove_job_from_table(pi);
8515 free_pipe(pi);
8516}
8517
8518static void clean_up_last_dead_job(void)
8519{
8520 if (G.job_list && !G.job_list->alive_cmds)
8521 delete_finished_job(G.job_list);
8522}
8523
Denys Vlasenko16096292017-07-10 10:00:28 +02008524static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008525{
8526 struct pipe *job, **jobp;
8527 int i;
8528
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008529 clean_up_last_dead_job();
8530
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008531 /* Find the end of the list, and find next job ID to use */
8532 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008533 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008534 while ((job = *jobp) != NULL) {
8535 if (job->jobid > i)
8536 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008537 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008538 }
8539 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008540
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008541 /* Create a new job struct at the end */
8542 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008543 job->next = NULL;
8544 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8545 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8546 for (i = 0; i < pi->num_cmds; i++) {
8547 job->cmds[i].pid = pi->cmds[i].pid;
8548 /* all other fields are not used and stay zero */
8549 }
8550 job->cmdtext = xstrdup(get_cmdtext(pi));
8551
8552 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008553 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008554 G.last_jobid = job->jobid;
8555}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008556#endif /* JOB */
8557
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008558static int job_exited_or_stopped(struct pipe *pi)
8559{
8560 int rcode, i;
8561
8562 if (pi->alive_cmds != pi->stopped_cmds)
8563 return -1;
8564
8565 /* All processes in fg pipe have exited or stopped */
8566 rcode = 0;
8567 i = pi->num_cmds;
8568 while (--i >= 0) {
8569 rcode = pi->cmds[i].cmd_exitcode;
8570 /* usually last process gives overall exitstatus,
8571 * but with "set -o pipefail", last *failed* process does */
8572 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8573 break;
8574 }
8575 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8576 return rcode;
8577}
8578
Denys Vlasenko7e675362016-10-28 21:57:31 +02008579static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008580{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008581#if ENABLE_HUSH_JOB
8582 struct pipe *pi;
8583#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008584 int i, dead;
8585
8586 dead = WIFEXITED(status) || WIFSIGNALED(status);
8587
8588#if DEBUG_JOBS
8589 if (WIFSTOPPED(status))
8590 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8591 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8592 if (WIFSIGNALED(status))
8593 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8594 childpid, WTERMSIG(status), WEXITSTATUS(status));
8595 if (WIFEXITED(status))
8596 debug_printf_jobs("pid %d exited, exitcode %d\n",
8597 childpid, WEXITSTATUS(status));
8598#endif
8599 /* Were we asked to wait for a fg pipe? */
8600 if (fg_pipe) {
8601 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008602
Denys Vlasenko7e675362016-10-28 21:57:31 +02008603 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008604 int rcode;
8605
Denys Vlasenko7e675362016-10-28 21:57:31 +02008606 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8607 if (fg_pipe->cmds[i].pid != childpid)
8608 continue;
8609 if (dead) {
8610 int ex;
8611 fg_pipe->cmds[i].pid = 0;
8612 fg_pipe->alive_cmds--;
8613 ex = WEXITSTATUS(status);
8614 /* bash prints killer signal's name for *last*
8615 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8616 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8617 */
8618 if (WIFSIGNALED(status)) {
8619 int sig = WTERMSIG(status);
8620 if (i == fg_pipe->num_cmds-1)
8621 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8622 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8623 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8624 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8625 * Maybe we need to use sig | 128? */
8626 ex = sig + 128;
8627 }
8628 fg_pipe->cmds[i].cmd_exitcode = ex;
8629 } else {
8630 fg_pipe->stopped_cmds++;
8631 }
8632 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8633 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008634 rcode = job_exited_or_stopped(fg_pipe);
8635 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008636/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8637 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8638 * and "killall -STOP cat" */
8639 if (G_interactive_fd) {
8640#if ENABLE_HUSH_JOB
8641 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008642 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008643#endif
8644 return rcode;
8645 }
8646 if (fg_pipe->alive_cmds == 0)
8647 return rcode;
8648 }
8649 /* There are still running processes in the fg_pipe */
8650 return -1;
8651 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008652 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008653 }
8654
8655#if ENABLE_HUSH_JOB
8656 /* We were asked to wait for bg or orphaned children */
8657 /* No need to remember exitcode in this case */
8658 for (pi = G.job_list; pi; pi = pi->next) {
8659 for (i = 0; i < pi->num_cmds; i++) {
8660 if (pi->cmds[i].pid == childpid)
8661 goto found_pi_and_prognum;
8662 }
8663 }
8664 /* Happens when shell is used as init process (init=/bin/sh) */
8665 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8666 return -1; /* this wasn't a process from fg_pipe */
8667
8668 found_pi_and_prognum:
8669 if (dead) {
8670 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008671 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008672 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008673 rcode = 128 + WTERMSIG(status);
8674 pi->cmds[i].cmd_exitcode = rcode;
8675 if (G.last_bg_pid == pi->cmds[i].pid)
8676 G.last_bg_pid_exitcode = rcode;
8677 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008678 pi->alive_cmds--;
8679 if (!pi->alive_cmds) {
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008680#if ENABLE_HUSH_BASH_COMPAT
8681 G.dead_job_exitcode = job_exited_or_stopped(pi);
8682#endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008683 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008684 printf(JOB_STATUS_FORMAT, pi->jobid,
8685 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008686 delete_finished_job(pi);
8687 } else {
8688/*
8689 * bash deletes finished jobs from job table only in interactive mode,
8690 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8691 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8692 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8693 * We only retain one "dead" job, if it's the single job on the list.
8694 * This covers most of real-world scenarios where this is useful.
8695 */
8696 if (pi != G.job_list)
8697 delete_finished_job(pi);
8698 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008699 }
8700 } else {
8701 /* child stopped */
8702 pi->stopped_cmds++;
8703 }
8704#endif
8705 return -1; /* this wasn't a process from fg_pipe */
8706}
8707
8708/* Check to see if any processes have exited -- if they have,
8709 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008710 *
8711 * If non-NULL fg_pipe: wait for its completion or stop.
8712 * Return its exitcode or zero if stopped.
8713 *
8714 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8715 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8716 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8717 * or 0 if no children changed status.
8718 *
8719 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8720 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8721 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008722 */
8723static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8724{
8725 int attributes;
8726 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008727 int rcode = 0;
8728
8729 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8730
8731 attributes = WUNTRACED;
8732 if (fg_pipe == NULL)
8733 attributes |= WNOHANG;
8734
8735 errno = 0;
8736#if ENABLE_HUSH_FAST
8737 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8738//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8739//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8740 /* There was neither fork nor SIGCHLD since last waitpid */
8741 /* Avoid doing waitpid syscall if possible */
8742 if (!G.we_have_children) {
8743 errno = ECHILD;
8744 return -1;
8745 }
8746 if (fg_pipe == NULL) { /* is WNOHANG set? */
8747 /* We have children, but they did not exit
8748 * or stop yet (we saw no SIGCHLD) */
8749 return 0;
8750 }
8751 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8752 }
8753#endif
8754
8755/* Do we do this right?
8756 * bash-3.00# sleep 20 | false
8757 * <ctrl-Z pressed>
8758 * [3]+ Stopped sleep 20 | false
8759 * bash-3.00# echo $?
8760 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8761 * [hush 1.14.0: yes we do it right]
8762 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008763 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008764 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008765#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008766 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008767 i = G.count_SIGCHLD;
8768#endif
8769 childpid = waitpid(-1, &status, attributes);
8770 if (childpid <= 0) {
8771 if (childpid && errno != ECHILD)
8772 bb_perror_msg("waitpid");
8773#if ENABLE_HUSH_FAST
8774 else { /* Until next SIGCHLD, waitpid's are useless */
8775 G.we_have_children = (childpid == 0);
8776 G.handled_SIGCHLD = i;
8777//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8778 }
8779#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008780 /* ECHILD (no children), or 0 (no change in children status) */
8781 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008782 break;
8783 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008784 rcode = process_wait_result(fg_pipe, childpid, status);
8785 if (rcode >= 0) {
8786 /* fg_pipe exited or stopped */
8787 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008788 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008789 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008790 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008791 rcode = WEXITSTATUS(status);
8792 if (WIFSIGNALED(status))
8793 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008794 if (WIFSTOPPED(status))
8795 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8796 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008797 rcode++;
8798 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008799 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008800#if ENABLE_HUSH_BASH_COMPAT
8801 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8802 && G.dead_job_exitcode >= 0 /* some job did finish */
8803 ) {
8804 debug_printf_exec("waitfor_pid:-1\n");
8805 rcode = G.dead_job_exitcode + 1;
8806 break;
8807 }
8808#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008809 /* This wasn't one of our processes, or */
8810 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008811 } /* while (waitpid succeeds)... */
8812
8813 return rcode;
8814}
8815
8816#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008817static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008818{
8819 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008820 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008821 if (G_saved_tty_pgrp) {
8822 /* Job finished, move the shell to the foreground */
8823 p = getpgrp(); /* our process group id */
8824 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8825 tcsetpgrp(G_interactive_fd, p);
8826 }
8827 return rcode;
8828}
8829#endif
8830
8831/* Start all the jobs, but don't wait for anything to finish.
8832 * See checkjobs().
8833 *
8834 * Return code is normally -1, when the caller has to wait for children
8835 * to finish to determine the exit status of the pipe. If the pipe
8836 * is a simple builtin command, however, the action is done by the
8837 * time run_pipe returns, and the exit code is provided as the
8838 * return value.
8839 *
8840 * Returns -1 only if started some children. IOW: we have to
8841 * mask out retvals of builtins etc with 0xff!
8842 *
8843 * The only case when we do not need to [v]fork is when the pipe
8844 * is single, non-backgrounded, non-subshell command. Examples:
8845 * cmd ; ... { list } ; ...
8846 * cmd && ... { list } && ...
8847 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008848 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008849 * or (if SH_STANDALONE) an applet, and we can run the { list }
8850 * with run_list. If it isn't one of these, we fork and exec cmd.
8851 *
8852 * Cases when we must fork:
8853 * non-single: cmd | cmd
8854 * backgrounded: cmd & { list } &
8855 * subshell: ( list ) [&]
8856 */
8857#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008858#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8859 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008860#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008861static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008862 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008863 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008864 char **argv_expanded)
8865{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008866 /* Assignments occur before redirects. Try:
8867 * a=`sleep 1` sleep 2 3>/qwe/rty
8868 */
8869
8870 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8871 dump_cmd_in_x_mode(new_env);
8872 dump_cmd_in_x_mode(argv_expanded);
8873 /* this takes ownership of new_env[i] elements, and frees new_env: */
8874 set_vars_and_save_old(new_env);
8875
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008876 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008877}
8878static NOINLINE int run_pipe(struct pipe *pi)
8879{
8880 static const char *const null_ptr = NULL;
8881
8882 int cmd_no;
8883 int next_infd;
8884 struct command *command;
8885 char **argv_expanded;
8886 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008887 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008888 int rcode;
8889
8890 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8891 debug_enter();
8892
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008893 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8894 * Result should be 3 lines: q w e, qwe, q w e
8895 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008896 if (G.ifs_whitespace != G.ifs)
8897 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008898 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008899 if (G.ifs) {
8900 char *p;
8901 G.ifs_whitespace = (char*)G.ifs;
8902 p = skip_whitespace(G.ifs);
8903 if (*p) {
8904 /* Not all $IFS is whitespace */
8905 char *d;
8906 int len = p - G.ifs;
8907 p = skip_non_whitespace(p);
8908 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8909 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8910 while (*p) {
8911 if (isspace(*p))
8912 *d++ = *p;
8913 p++;
8914 }
8915 *d = '\0';
8916 }
8917 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008918 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008919 G.ifs_whitespace = (char*)G.ifs;
8920 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008921
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008922 IF_HUSH_JOB(pi->pgrp = -1;)
8923 pi->stopped_cmds = 0;
8924 command = &pi->cmds[0];
8925 argv_expanded = NULL;
8926
8927 if (pi->num_cmds != 1
8928 || pi->followup == PIPE_BG
8929 || command->cmd_type == CMD_SUBSHELL
8930 ) {
8931 goto must_fork;
8932 }
8933
8934 pi->alive_cmds = 1;
8935
8936 debug_printf_exec(": group:%p argv:'%s'\n",
8937 command->group, command->argv ? command->argv[0] : "NONE");
8938
8939 if (command->group) {
8940#if ENABLE_HUSH_FUNCTIONS
8941 if (command->cmd_type == CMD_FUNCDEF) {
8942 /* "executing" func () { list } */
8943 struct function *funcp;
8944
8945 funcp = new_function(command->argv[0]);
8946 /* funcp->name is already set to argv[0] */
8947 funcp->body = command->group;
8948# if !BB_MMU
8949 funcp->body_as_string = command->group_as_string;
8950 command->group_as_string = NULL;
8951# endif
8952 command->group = NULL;
8953 command->argv[0] = NULL;
8954 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8955 funcp->parent_cmd = command;
8956 command->child_func = funcp;
8957
8958 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8959 debug_leave();
8960 return EXIT_SUCCESS;
8961 }
8962#endif
8963 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008964 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008965 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008966 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008967 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008968//FIXME: we need to pass squirrel down into run_list()
8969//for SH_STANDALONE case, or else this construct:
8970// { find /proc/self/fd; true; } >FILE; cmd2
8971//has no way of closing saved fd#1 for "find",
8972//and in SH_STANDALONE mode, "find" is not execed,
8973//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008974 rcode = run_list(command->group) & 0xff;
8975 }
8976 restore_redirects(squirrel);
8977 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8978 debug_leave();
8979 debug_printf_exec("run_pipe: return %d\n", rcode);
8980 return rcode;
8981 }
8982
8983 argv = command->argv ? command->argv : (char **) &null_ptr;
8984 {
8985 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008986 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8987 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008988 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008989 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008990
Denys Vlasenko5807e182018-02-08 19:19:04 +01008991#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008992 if (G.lineno_var)
8993 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8994#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008995
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008996 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008997 /* Assignments, but no command.
8998 * Ensure redirects take effect (that is, create files).
8999 * Try "a=t >file"
9000 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009001 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009002 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009003 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009004 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009005 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009006
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009007 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009008 i = 0;
9009 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009010 char *p = expand_string_to_string(argv[i],
9011 EXP_FLAG_ESC_GLOB_CHARS,
9012 /*unbackslash:*/ 1
9013 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009014#if ENABLE_HUSH_MODE_X
9015 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009016 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009017 if (i == 0)
9018 x_mode_prefix();
9019 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009020 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009021 if (*eq) eq++;
9022 x_mode_addblock(p, (eq - p));
9023 x_mode_print_optionally_squoted(eq);
9024 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009025 }
9026#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009027 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009028 if (set_local_var(p, /*flag:*/ 0)) {
9029 /* assignment to readonly var / putenv error? */
9030 rcode = 1;
9031 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009032 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009033 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009034 /* Redirect error sets $? to 1. Otherwise,
9035 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009036 * Else, clear $?:
9037 * false; q=`exit 2`; echo $? - should print 2
9038 * false; x=1; echo $? - should print 0
9039 * Because of the 2nd case, we can't just use G.last_exitcode.
9040 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009041 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009042 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009043 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9044 debug_leave();
9045 debug_printf_exec("run_pipe: return %d\n", rcode);
9046 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009047 }
9048
9049 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02009050#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009051 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009052 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009053 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009054#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009055 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009056
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009057 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009058 if (!argv_expanded[0]) {
9059 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009060 /* `false` still has to set exitcode 1 */
9061 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009062 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009063 }
9064
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009065 old_vars = NULL;
9066 sv_shadowed = G.shadowed_vars_pp;
9067
Denys Vlasenko75481d32017-07-31 05:27:09 +02009068 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009069 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9070 IF_HUSH_FUNCTIONS(x = NULL;)
9071 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009072 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009073 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009074 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9075 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009076 /*
9077 * Variable assignments are executed, but then "forgotten":
9078 * a=`sleep 1;echo A` exec 3>&-; echo $a
9079 * sleeps, but prints nothing.
9080 */
9081 enter_var_nest_level();
9082 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009083 rcode = redirect_and_varexp_helper(command,
9084 /*squirrel:*/ ERR_PTR,
9085 argv_expanded
9086 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009087 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009088 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009089
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009090 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009091 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009092
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009093 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009094 * a=b true; env | grep ^a=
9095 */
9096 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009097 /* Collect all variables "shadowed" by helper
9098 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9099 * into old_vars list:
9100 */
9101 G.shadowed_vars_pp = &old_vars;
9102 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009103 if (rcode == 0) {
9104 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009105 /* Do not collect *to old_vars list* vars shadowed
9106 * by e.g. "local VAR" builtin (collect them
9107 * in the previously nested list instead):
9108 * don't want them to be restored immediately
9109 * after "local" completes.
9110 */
9111 G.shadowed_vars_pp = sv_shadowed;
9112
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009113 debug_printf_exec(": builtin '%s' '%s'...\n",
9114 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009115 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009116 rcode = x->b_function(argv_expanded) & 0xff;
9117 fflush_all();
9118 }
9119#if ENABLE_HUSH_FUNCTIONS
9120 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009121 debug_printf_exec(": function '%s' '%s'...\n",
9122 funcp->name, argv_expanded[1]);
9123 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009124 /*
9125 * But do collect *to old_vars list* vars shadowed
9126 * within function execution. To that end, restore
9127 * this pointer _after_ function run:
9128 */
9129 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009130 }
9131#endif
9132 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009133 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009134 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009135 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009136 if (n < 0 || !APPLET_IS_NOFORK(n))
9137 goto must_fork;
9138
9139 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009140 /* Collect all variables "shadowed" by helper into old_vars list */
9141 G.shadowed_vars_pp = &old_vars;
9142 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9143 G.shadowed_vars_pp = sv_shadowed;
9144
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009145 if (rcode == 0) {
9146 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9147 argv_expanded[0], argv_expanded[1]);
9148 /*
9149 * Note: signals (^C) can't interrupt here.
9150 * We remember them and they will be acted upon
9151 * after applet returns.
9152 * This makes applets which can run for a long time
9153 * and/or wait for user input ineligible for NOFORK:
9154 * for example, "yes" or "rm" (rm -i waits for input).
9155 */
9156 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009157 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009158 } else
9159 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009160
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009161 restore_redirects(squirrel);
9162 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009163 leave_var_nest_level();
9164 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009165
9166 /*
9167 * Try "usleep 99999999" + ^C + "echo $?"
9168 * with FEATURE_SH_NOFORK=y.
9169 */
9170 if (!funcp) {
9171 /* It was builtin or nofork.
9172 * if this would be a real fork/execed program,
9173 * it should have died if a fatal sig was received.
9174 * But OTOH, there was no separate process,
9175 * the sig was sent to _shell_, not to non-existing
9176 * child.
9177 * Let's just handle ^C only, this one is obvious:
9178 * we aren't ok with exitcode 0 when ^C was pressed
9179 * during builtin/nofork.
9180 */
9181 if (sigismember(&G.pending_set, SIGINT))
9182 rcode = 128 + SIGINT;
9183 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009184 free(argv_expanded);
9185 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9186 debug_leave();
9187 debug_printf_exec("run_pipe return %d\n", rcode);
9188 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009189 }
9190
9191 must_fork:
9192 /* NB: argv_expanded may already be created, and that
9193 * might include `cmd` runs! Do not rerun it! We *must*
9194 * use argv_expanded if it's non-NULL */
9195
9196 /* Going to fork a child per each pipe member */
9197 pi->alive_cmds = 0;
9198 next_infd = 0;
9199
9200 cmd_no = 0;
9201 while (cmd_no < pi->num_cmds) {
9202 struct fd_pair pipefds;
9203#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009204 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009205 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009206 nommu_save.old_vars = NULL;
9207 nommu_save.argv = NULL;
9208 nommu_save.argv_from_re_execing = NULL;
9209#endif
9210 command = &pi->cmds[cmd_no];
9211 cmd_no++;
9212 if (command->argv) {
9213 debug_printf_exec(": pipe member '%s' '%s'...\n",
9214 command->argv[0], command->argv[1]);
9215 } else {
9216 debug_printf_exec(": pipe member with no argv\n");
9217 }
9218
9219 /* pipes are inserted between pairs of commands */
9220 pipefds.rd = 0;
9221 pipefds.wr = 1;
9222 if (cmd_no < pi->num_cmds)
9223 xpiped_pair(pipefds);
9224
Denys Vlasenko5807e182018-02-08 19:19:04 +01009225#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009226 if (G.lineno_var)
9227 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9228#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009229
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009230 command->pid = BB_MMU ? fork() : vfork();
9231 if (!command->pid) { /* child */
9232#if ENABLE_HUSH_JOB
9233 disable_restore_tty_pgrp_on_exit();
9234 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9235
9236 /* Every child adds itself to new process group
9237 * with pgid == pid_of_first_child_in_pipe */
9238 if (G.run_list_level == 1 && G_interactive_fd) {
9239 pid_t pgrp;
9240 pgrp = pi->pgrp;
9241 if (pgrp < 0) /* true for 1st process only */
9242 pgrp = getpid();
9243 if (setpgid(0, pgrp) == 0
9244 && pi->followup != PIPE_BG
9245 && G_saved_tty_pgrp /* we have ctty */
9246 ) {
9247 /* We do it in *every* child, not just first,
9248 * to avoid races */
9249 tcsetpgrp(G_interactive_fd, pgrp);
9250 }
9251 }
9252#endif
9253 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9254 /* 1st cmd in backgrounded pipe
9255 * should have its stdin /dev/null'ed */
9256 close(0);
9257 if (open(bb_dev_null, O_RDONLY))
9258 xopen("/", O_RDONLY);
9259 } else {
9260 xmove_fd(next_infd, 0);
9261 }
9262 xmove_fd(pipefds.wr, 1);
9263 if (pipefds.rd > 1)
9264 close(pipefds.rd);
9265 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009266 * and the pipe fd (fd#1) is available for dup'ing:
9267 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9268 * of cmd1 goes into pipe.
9269 */
9270 if (setup_redirects(command, NULL)) {
9271 /* Happens when redir file can't be opened:
9272 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9273 * FOO
9274 * hush: can't open '/qwe/rty': No such file or directory
9275 * BAZ
9276 * (echo BAR is not executed, it hits _exit(1) below)
9277 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009278 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009279 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009280
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009281 /* Stores to nommu_save list of env vars putenv'ed
9282 * (NOMMU, on MMU we don't need that) */
9283 /* cast away volatility... */
9284 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9285 /* pseudo_exec() does not return */
9286 }
9287
9288 /* parent or error */
9289#if ENABLE_HUSH_FAST
9290 G.count_SIGCHLD++;
9291//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9292#endif
9293 enable_restore_tty_pgrp_on_exit();
9294#if !BB_MMU
9295 /* Clean up after vforked child */
9296 free(nommu_save.argv);
9297 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009298 G.var_nest_level = sv_var_nest_level;
9299 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009300 add_vars(nommu_save.old_vars);
9301#endif
9302 free(argv_expanded);
9303 argv_expanded = NULL;
9304 if (command->pid < 0) { /* [v]fork failed */
9305 /* Clearly indicate, was it fork or vfork */
9306 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9307 } else {
9308 pi->alive_cmds++;
9309#if ENABLE_HUSH_JOB
9310 /* Second and next children need to know pid of first one */
9311 if (pi->pgrp < 0)
9312 pi->pgrp = command->pid;
9313#endif
9314 }
9315
9316 if (cmd_no > 1)
9317 close(next_infd);
9318 if (cmd_no < pi->num_cmds)
9319 close(pipefds.wr);
9320 /* Pass read (output) pipe end to next iteration */
9321 next_infd = pipefds.rd;
9322 }
9323
9324 if (!pi->alive_cmds) {
9325 debug_leave();
9326 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9327 return 1;
9328 }
9329
9330 debug_leave();
9331 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9332 return -1;
9333}
9334
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009335/* NB: called by pseudo_exec, and therefore must not modify any
9336 * global data until exec/_exit (we can be a child after vfork!) */
9337static int run_list(struct pipe *pi)
9338{
9339#if ENABLE_HUSH_CASE
9340 char *case_word = NULL;
9341#endif
9342#if ENABLE_HUSH_LOOPS
9343 struct pipe *loop_top = NULL;
9344 char **for_lcur = NULL;
9345 char **for_list = NULL;
9346#endif
9347 smallint last_followup;
9348 smalluint rcode;
9349#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9350 smalluint cond_code = 0;
9351#else
9352 enum { cond_code = 0 };
9353#endif
9354#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009355 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009356 smallint last_rword; /* ditto */
9357#endif
9358
9359 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9360 debug_enter();
9361
9362#if ENABLE_HUSH_LOOPS
9363 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009364 {
9365 struct pipe *cpipe;
9366 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9367 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9368 continue;
9369 /* current word is FOR or IN (BOLD in comments below) */
9370 if (cpipe->next == NULL) {
9371 syntax_error("malformed for");
9372 debug_leave();
9373 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9374 return 1;
9375 }
9376 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9377 if (cpipe->next->res_word == RES_DO)
9378 continue;
9379 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9380 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9381 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9382 ) {
9383 syntax_error("malformed for");
9384 debug_leave();
9385 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9386 return 1;
9387 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009388 }
9389 }
9390#endif
9391
9392 /* Past this point, all code paths should jump to ret: label
9393 * in order to return, no direct "return" statements please.
9394 * This helps to ensure that no memory is leaked. */
9395
9396#if ENABLE_HUSH_JOB
9397 G.run_list_level++;
9398#endif
9399
9400#if HAS_KEYWORDS
9401 rword = RES_NONE;
9402 last_rword = RES_XXXX;
9403#endif
9404 last_followup = PIPE_SEQ;
9405 rcode = G.last_exitcode;
9406
9407 /* Go through list of pipes, (maybe) executing them. */
9408 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009409 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009410 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009411
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009412 if (G.flag_SIGINT)
9413 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009414 if (G_flag_return_in_progress == 1)
9415 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009416
9417 IF_HAS_KEYWORDS(rword = pi->res_word;)
9418 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9419 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009420
9421 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009422 if (
9423#if ENABLE_HUSH_IF
9424 rword == RES_IF || rword == RES_ELIF ||
9425#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009426 pi->followup != PIPE_SEQ
9427 ) {
9428 G.errexit_depth++;
9429 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009430#if ENABLE_HUSH_LOOPS
9431 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9432 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9433 ) {
9434 /* start of a loop: remember where loop starts */
9435 loop_top = pi;
9436 G.depth_of_loop++;
9437 }
9438#endif
9439 /* Still in the same "if...", "then..." or "do..." branch? */
9440 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9441 if ((rcode == 0 && last_followup == PIPE_OR)
9442 || (rcode != 0 && last_followup == PIPE_AND)
9443 ) {
9444 /* It is "<true> || CMD" or "<false> && CMD"
9445 * and we should not execute CMD */
9446 debug_printf_exec("skipped cmd because of || or &&\n");
9447 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009448 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009449 }
9450 }
9451 last_followup = pi->followup;
9452 IF_HAS_KEYWORDS(last_rword = rword;)
9453#if ENABLE_HUSH_IF
9454 if (cond_code) {
9455 if (rword == RES_THEN) {
9456 /* if false; then ... fi has exitcode 0! */
9457 G.last_exitcode = rcode = EXIT_SUCCESS;
9458 /* "if <false> THEN cmd": skip cmd */
9459 continue;
9460 }
9461 } else {
9462 if (rword == RES_ELSE || rword == RES_ELIF) {
9463 /* "if <true> then ... ELSE/ELIF cmd":
9464 * skip cmd and all following ones */
9465 break;
9466 }
9467 }
9468#endif
9469#if ENABLE_HUSH_LOOPS
9470 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9471 if (!for_lcur) {
9472 /* first loop through for */
9473
9474 static const char encoded_dollar_at[] ALIGN1 = {
9475 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9476 }; /* encoded representation of "$@" */
9477 static const char *const encoded_dollar_at_argv[] = {
9478 encoded_dollar_at, NULL
9479 }; /* argv list with one element: "$@" */
9480 char **vals;
9481
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009482 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009483 vals = (char**)encoded_dollar_at_argv;
9484 if (pi->next->res_word == RES_IN) {
9485 /* if no variable values after "in" we skip "for" */
9486 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009487 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9488 break;
9489 }
9490 vals = pi->next->cmds[0].argv;
9491 } /* else: "for var; do..." -> assume "$@" list */
9492 /* create list of variable values */
9493 debug_print_strings("for_list made from", vals);
9494 for_list = expand_strvec_to_strvec(vals);
9495 for_lcur = for_list;
9496 debug_print_strings("for_list", for_list);
9497 }
9498 if (!*for_lcur) {
9499 /* "for" loop is over, clean up */
9500 free(for_list);
9501 for_list = NULL;
9502 for_lcur = NULL;
9503 break;
9504 }
9505 /* Insert next value from for_lcur */
9506 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009507 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009508 continue;
9509 }
9510 if (rword == RES_IN) {
9511 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9512 }
9513 if (rword == RES_DONE) {
9514 continue; /* "done" has no cmds too */
9515 }
9516#endif
9517#if ENABLE_HUSH_CASE
9518 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009519 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009520 case_word = expand_string_to_string(pi->cmds->argv[0],
9521 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009522 debug_printf_exec("CASE word1:'%s'\n", case_word);
9523 //unbackslash(case_word);
9524 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009525 continue;
9526 }
9527 if (rword == RES_MATCH) {
9528 char **argv;
9529
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009530 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009531 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9532 break;
9533 /* all prev words didn't match, does this one match? */
9534 argv = pi->cmds->argv;
9535 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009536 char *pattern;
9537 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9538 pattern = expand_string_to_string(*argv,
9539 EXP_FLAG_ESC_GLOB_CHARS,
9540 /*unbackslash:*/ 0
9541 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009542 /* TODO: which FNM_xxx flags to use? */
9543 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009544 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9545 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009546 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009547 if (cond_code == 0) {
9548 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009549 free(case_word);
9550 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009551 break;
9552 }
9553 argv++;
9554 }
9555 continue;
9556 }
9557 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009558 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009559 if (cond_code != 0)
9560 continue; /* not matched yet, skip this pipe */
9561 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009562 if (rword == RES_ESAC) {
9563 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9564 if (case_word) {
9565 /* "case" did not match anything: still set $? (to 0) */
9566 G.last_exitcode = rcode = EXIT_SUCCESS;
9567 }
9568 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009569#endif
9570 /* Just pressing <enter> in shell should check for jobs.
9571 * OTOH, in non-interactive shell this is useless
9572 * and only leads to extra job checks */
9573 if (pi->num_cmds == 0) {
9574 if (G_interactive_fd)
9575 goto check_jobs_and_continue;
9576 continue;
9577 }
9578
9579 /* After analyzing all keywords and conditions, we decided
9580 * to execute this pipe. NB: have to do checkjobs(NULL)
9581 * after run_pipe to collect any background children,
9582 * even if list execution is to be stopped. */
9583 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009584#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009585 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009586#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009587 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9588 if (r != -1) {
9589 /* We ran a builtin, function, or group.
9590 * rcode is already known
9591 * and we don't need to wait for anything. */
9592 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9593 G.last_exitcode = rcode;
9594 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009595#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009596 /* Was it "break" or "continue"? */
9597 if (G.flag_break_continue) {
9598 smallint fbc = G.flag_break_continue;
9599 /* We might fall into outer *loop*,
9600 * don't want to break it too */
9601 if (loop_top) {
9602 G.depth_break_continue--;
9603 if (G.depth_break_continue == 0)
9604 G.flag_break_continue = 0;
9605 /* else: e.g. "continue 2" should *break* once, *then* continue */
9606 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9607 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009608 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009609 break;
9610 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009611 /* "continue": simulate end of loop */
9612 rword = RES_DONE;
9613 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009614 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009615#endif
9616 if (G_flag_return_in_progress == 1) {
9617 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9618 break;
9619 }
9620 } else if (pi->followup == PIPE_BG) {
9621 /* What does bash do with attempts to background builtins? */
9622 /* even bash 3.2 doesn't do that well with nested bg:
9623 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9624 * I'm NOT treating inner &'s as jobs */
9625#if ENABLE_HUSH_JOB
9626 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009627 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009628#endif
9629 /* Last command's pid goes to $! */
9630 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009631 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009632 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009633/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009634 rcode = EXIT_SUCCESS;
9635 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009636 } else {
9637#if ENABLE_HUSH_JOB
9638 if (G.run_list_level == 1 && G_interactive_fd) {
9639 /* Waits for completion, then fg's main shell */
9640 rcode = checkjobs_and_fg_shell(pi);
9641 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009642 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009643 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009644#endif
9645 /* This one just waits for completion */
9646 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9647 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9648 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009649 G.last_exitcode = rcode;
9650 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009651 }
9652
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009653 /* Handle "set -e" */
9654 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9655 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9656 if (G.errexit_depth == 0)
9657 hush_exit(rcode);
9658 }
9659 G.errexit_depth = sv_errexit_depth;
9660
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009661 /* Analyze how result affects subsequent commands */
9662#if ENABLE_HUSH_IF
9663 if (rword == RES_IF || rword == RES_ELIF)
9664 cond_code = rcode;
9665#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009666 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009667 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009668 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009669#if ENABLE_HUSH_LOOPS
9670 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009671 if (pi->next
9672 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009673 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009674 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009675 if (rword == RES_WHILE) {
9676 if (rcode) {
9677 /* "while false; do...done" - exitcode 0 */
9678 G.last_exitcode = rcode = EXIT_SUCCESS;
9679 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009680 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009681 }
9682 }
9683 if (rword == RES_UNTIL) {
9684 if (!rcode) {
9685 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009686 break;
9687 }
9688 }
9689 }
9690#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009691 } /* for (pi) */
9692
9693#if ENABLE_HUSH_JOB
9694 G.run_list_level--;
9695#endif
9696#if ENABLE_HUSH_LOOPS
9697 if (loop_top)
9698 G.depth_of_loop--;
9699 free(for_list);
9700#endif
9701#if ENABLE_HUSH_CASE
9702 free(case_word);
9703#endif
9704 debug_leave();
9705 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9706 return rcode;
9707}
9708
9709/* Select which version we will use */
9710static int run_and_free_list(struct pipe *pi)
9711{
9712 int rcode = 0;
9713 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009714 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009715 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9716 rcode = run_list(pi);
9717 }
9718 /* free_pipe_list has the side effect of clearing memory.
9719 * In the long run that function can be merged with run_list,
9720 * but doing that now would hobble the debugging effort. */
9721 free_pipe_list(pi);
9722 debug_printf_exec("run_and_free_list return %d\n", rcode);
9723 return rcode;
9724}
9725
9726
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009727static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009728{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009729 sighandler_t old_handler;
9730 unsigned sig = 0;
9731 while ((mask >>= 1) != 0) {
9732 sig++;
9733 if (!(mask & 1))
9734 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009735 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009736 /* POSIX allows shell to re-enable SIGCHLD
9737 * even if it was SIG_IGN on entry.
9738 * Therefore we skip IGN check for it:
9739 */
9740 if (sig == SIGCHLD)
9741 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009742 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9743 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9744 */
9745 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009746 if (old_handler == SIG_IGN) {
9747 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009748 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009749#if ENABLE_HUSH_TRAP
9750 if (!G_traps)
9751 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9752 free(G_traps[sig]);
9753 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9754#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009755 }
9756 }
9757}
9758
9759/* Called a few times only (or even once if "sh -c") */
9760static void install_special_sighandlers(void)
9761{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009762 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009763
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009764 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009765 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009766 if (G_interactive_fd) {
9767 mask |= SPECIAL_INTERACTIVE_SIGS;
9768 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009769 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009770 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009771 /* Careful, do not re-install handlers we already installed */
9772 if (G.special_sig_mask != mask) {
9773 unsigned diff = mask & ~G.special_sig_mask;
9774 G.special_sig_mask = mask;
9775 install_sighandlers(diff);
9776 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009777}
9778
9779#if ENABLE_HUSH_JOB
9780/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009781/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009782static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009783{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009784 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009785
9786 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009787 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009788 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9789 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009790 + (1 << SIGBUS ) * HUSH_DEBUG
9791 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009792 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009793 + (1 << SIGABRT)
9794 /* bash 3.2 seems to handle these just like 'fatal' ones */
9795 + (1 << SIGPIPE)
9796 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009797 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009798 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009799 * we never want to restore pgrp on exit, and this fn is not called
9800 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009801 /*+ (1 << SIGHUP )*/
9802 /*+ (1 << SIGTERM)*/
9803 /*+ (1 << SIGINT )*/
9804 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009805 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009806
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009807 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009808}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009809#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009810
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009811static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009812{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009813 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009814 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009815 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009816 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009817 break;
9818 case 'x':
9819 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009820 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 +01009821 break;
9822 case 'o':
9823 if (!o_opt) {
9824 /* "set -+o" without parameter.
9825 * in bash, set -o produces this output:
9826 * pipefail off
9827 * and set +o:
9828 * set +o pipefail
9829 * We always use the second form.
9830 */
9831 const char *p = o_opt_strings;
9832 idx = 0;
9833 while (*p) {
9834 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9835 idx++;
9836 p += strlen(p) + 1;
9837 }
9838 break;
9839 }
9840 idx = index_in_strings(o_opt_strings, o_opt);
9841 if (idx >= 0) {
9842 G.o_opt[idx] = state;
9843 break;
9844 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009845 case 'e':
9846 G.o_opt[OPT_O_ERREXIT] = state;
9847 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009848 default:
9849 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009850 }
9851 return EXIT_SUCCESS;
9852}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009853
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009854int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009855int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009856{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009857 enum {
9858 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009859 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009860 };
9861 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009862 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009863 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009864 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009865 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009866
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009867 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009868 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009869 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009870
Denys Vlasenko10c01312011-05-11 11:49:21 +02009871#if ENABLE_HUSH_FAST
9872 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9873#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009874#if !BB_MMU
9875 G.argv0_for_re_execing = argv[0];
9876#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009877
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009878 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009879 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9880 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009881 shell_ver = xzalloc(sizeof(*shell_ver));
9882 shell_ver->flg_export = 1;
9883 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009884 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009885 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009886 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009887
Denys Vlasenko605067b2010-09-06 12:10:51 +02009888 /* Create shell local variables from the values
9889 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009890 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009891 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009892 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009893 if (e) while (*e) {
9894 char *value = strchr(*e, '=');
9895 if (value) { /* paranoia */
9896 cur_var->next = xzalloc(sizeof(*cur_var));
9897 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009898 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009899 cur_var->max_len = strlen(*e);
9900 cur_var->flg_export = 1;
9901 }
9902 e++;
9903 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009904 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009905 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9906 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009907
9908 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009909 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009910
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009911#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9912 /* Set (but not export) PS1/2 unless already set */
9913 if (!get_local_var_value("PS1"))
9914 set_local_var_from_halves("PS1", "\\w \\$ ");
9915 if (!get_local_var_value("PS2"))
9916 set_local_var_from_halves("PS2", "> ");
9917#endif
9918
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009919#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009920 /* Set (but not export) HOSTNAME unless already set */
9921 if (!get_local_var_value("HOSTNAME")) {
9922 struct utsname uts;
9923 uname(&uts);
9924 set_local_var_from_halves("HOSTNAME", uts.nodename);
9925 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02009926#endif
9927 /* IFS is not inherited from the parent environment */
9928 set_local_var_from_halves("IFS", defifs);
9929
Denys Vlasenko6db47842009-09-05 20:15:17 +02009930 /* bash also exports SHLVL and _,
9931 * and sets (but doesn't export) the following variables:
9932 * BASH=/bin/bash
9933 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9934 * BASH_VERSION='3.2.0(1)-release'
9935 * HOSTTYPE=i386
9936 * MACHTYPE=i386-pc-linux-gnu
9937 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009938 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009939 * EUID=<NNNNN>
9940 * UID=<NNNNN>
9941 * GROUPS=()
9942 * LINES=<NNN>
9943 * COLUMNS=<NNN>
9944 * BASH_ARGC=()
9945 * BASH_ARGV=()
9946 * BASH_LINENO=()
9947 * BASH_SOURCE=()
9948 * DIRSTACK=()
9949 * PIPESTATUS=([0]="0")
9950 * HISTFILE=/<xxx>/.bash_history
9951 * HISTFILESIZE=500
9952 * HISTSIZE=500
9953 * MAILCHECK=60
9954 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9955 * SHELL=/bin/bash
9956 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9957 * TERM=dumb
9958 * OPTERR=1
9959 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +02009960 * PS4='+ '
9961 */
9962
Denys Vlasenko5807e182018-02-08 19:19:04 +01009963#if ENABLE_HUSH_LINENO_VAR
9964 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009965 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9966 set_local_var(p, /*flags*/ 0);
9967 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9968 }
9969#endif
9970
Denis Vlasenko38f63192007-01-22 09:03:07 +00009971#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009972 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009973#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009974
Eric Andersen94ac2442001-05-22 19:05:18 +00009975 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009976 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009977
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009978 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009979
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009980 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009981 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009982 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009983 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009984 * in order to intercept (more) signals.
9985 */
9986
9987 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009988 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009989 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009990 builtin_argc = 0;
Ron Yorston71df2d32018-11-27 14:34:25 +00009991#if NUM_SCRIPTS > 0
9992 if (argc < 0) {
9993 optarg = get_script_content(-argc - 1);
9994 optind = 0;
9995 argc = string_array_len(argv);
9996 goto run_script;
9997 }
9998#endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009999 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010000 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010001#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010002 "<:$:R:V:"
10003# if ENABLE_HUSH_FUNCTIONS
10004 "F:"
10005# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010006#endif
10007 );
10008 if (opt <= 0)
10009 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010010 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010011 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010012 /* Possibilities:
10013 * sh ... -c 'script'
10014 * sh ... -c 'script' ARG0 [ARG1...]
10015 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +010010016 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010017 * "" needs to be replaced with NULL
10018 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +010010019 * Note: the form without ARG0 never happens:
10020 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010021 */
Ron Yorston71df2d32018-11-27 14:34:25 +000010022#if NUM_SCRIPTS > 0
10023 run_script:
10024#endif
Denys Vlasenkodea47882009-10-09 15:40:49 +020010025 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010026 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010027 G.root_ppid = getppid();
10028 }
Denis Vlasenko87a86552008-07-29 19:43:10 +000010029 G.global_argv = argv + optind;
10030 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010031 if (builtin_argc) {
10032 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10033 const struct built_in_command *x;
10034
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010035 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010036 x = find_builtin(optarg);
10037 if (x) { /* paranoia */
10038 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
10039 G.global_argv += builtin_argc;
10040 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +010010041 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +010010042 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010043 }
10044 goto final_return;
10045 }
10046 if (!G.global_argv[0]) {
10047 /* -c 'script' (no params): prevent empty $0 */
10048 G.global_argv--; /* points to argv[i] of 'script' */
10049 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +020010050 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010051 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010052 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010053 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010054 goto final_return;
10055 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010056 /* Well, we cannot just declare interactiveness,
10057 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010058 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010059 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010060 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010061 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010062 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010063 case 'l':
10064 flags |= OPT_login;
10065 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010066#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010067 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010068 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010069 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010070 case '$': {
10071 unsigned long long empty_trap_mask;
10072
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010073 G.root_pid = bb_strtou(optarg, &optarg, 16);
10074 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010075 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10076 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010077 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10078 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010079 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010080 optarg++;
10081 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010082 optarg++;
10083 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10084 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010085 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010086 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010087# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010088 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010089 for (sig = 1; sig < NSIG; sig++) {
10090 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010091 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010092 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010093 }
10094 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010095# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010096 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010097# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010098 optarg++;
10099 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010100# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010101# if ENABLE_HUSH_FUNCTIONS
10102 /* nommu uses re-exec trick for "... | func | ...",
10103 * should allow "return".
10104 * This accidentally allows returns in subshells.
10105 */
10106 G_flag_return_in_progress = -1;
10107# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010108 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010109 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010110 case 'R':
10111 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010112 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010113 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010114# if ENABLE_HUSH_FUNCTIONS
10115 case 'F': {
10116 struct function *funcp = new_function(optarg);
10117 /* funcp->name is already set to optarg */
10118 /* funcp->body is set to NULL. It's a special case. */
10119 funcp->body_as_string = argv[optind];
10120 optind++;
10121 break;
10122 }
10123# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010124#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010125 case 'n':
10126 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010127 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010128 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010129 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010130 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010131#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010132 fprintf(stderr, "Usage: sh [FILE]...\n"
10133 " or: sh -c command [args]...\n\n");
10134 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010135#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010136 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010137#endif
Eric Andersen25f27032001-04-26 23:22:31 +000010138 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010139 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010140
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010141 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10142 G.global_argc = argc - (optind - 1);
10143 G.global_argv = argv + (optind - 1);
10144 G.global_argv[0] = argv[0];
10145
Denys Vlasenkodea47882009-10-09 15:40:49 +020010146 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010147 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010148 G.root_ppid = getppid();
10149 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010150
10151 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010152 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010153 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010154 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010155 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010156 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010157 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010158 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010159 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010160 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010161 /* bash: after sourcing /etc/profile,
10162 * tries to source (in the given order):
10163 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010164 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010165 * bash also sources ~/.bash_logout on exit.
10166 * If called as sh, skips .bash_XXX files.
10167 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010168 }
10169
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010170 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10171 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010172 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010173 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010174 * "bash <script>" (which is never interactive (unless -i?))
10175 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010176 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010177 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010178 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010179 G.global_argc--;
10180 G.global_argv++;
10181 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010182 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010183 input = hfopen(G.global_argv[0]);
10184 if (!input) {
10185 bb_simple_perror_msg_and_die(G.global_argv[0]);
10186 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010187 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010188 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010189 parse_and_run_file(input);
10190#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010191 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010192#endif
10193 goto final_return;
10194 }
10195
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010196 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010197 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010198 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010199
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010200 /* A shell is interactive if the '-i' flag was given,
10201 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010202 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010203 * no arguments remaining or the -s flag given
10204 * standard input is a terminal
10205 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010206 * Refer to Posix.2, the description of the 'sh' utility.
10207 */
10208#if ENABLE_HUSH_JOB
10209 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010210 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10211 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10212 if (G_saved_tty_pgrp < 0)
10213 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010214
10215 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010216 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010217 if (G_interactive_fd < 0) {
10218 /* try to dup to any fd */
10219 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010220 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010221 /* give up */
10222 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010223 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010224 }
10225 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010226// TODO: track & disallow any attempts of user
10227// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010228 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010229 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010230 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010231 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010232
Mike Frysinger38478a62009-05-20 04:48:06 -040010233 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010234 /* If we were run as 'hush &', sleep until we are
10235 * in the foreground (tty pgrp == our pgrp).
10236 * If we get started under a job aware app (like bash),
10237 * make sure we are now in charge so we don't fight over
10238 * who gets the foreground */
10239 while (1) {
10240 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010241 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10242 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010243 break;
10244 /* send TTIN to ourself (should stop us) */
10245 kill(- shell_pgrp, SIGTTIN);
10246 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010247 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010248
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010249 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010250 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010251
Mike Frysinger38478a62009-05-20 04:48:06 -040010252 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010253 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010254 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010255 /* Put ourselves in our own process group
10256 * (bash, too, does this only if ctty is available) */
10257 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10258 /* Grab control of the terminal */
10259 tcsetpgrp(G_interactive_fd, getpid());
10260 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010261 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010262
10263# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10264 {
10265 const char *hp = get_local_var_value("HISTFILE");
10266 if (!hp) {
10267 hp = get_local_var_value("HOME");
10268 if (hp)
10269 hp = concat_path_file(hp, ".hush_history");
10270 } else {
10271 hp = xstrdup(hp);
10272 }
10273 if (hp) {
10274 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010275 //set_local_var(xasprintf("HISTFILE=%s", ...));
10276 }
10277# if ENABLE_FEATURE_SH_HISTFILESIZE
10278 hp = get_local_var_value("HISTFILESIZE");
10279 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10280# endif
10281 }
10282# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010283 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010284 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010285 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010286#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010287 /* No job control compiled in, only prompt/line editing */
10288 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010289 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010290 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010291 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010292 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010293 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010294 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010295 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010296 }
10297 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010298 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010299 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010300 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010301 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010302#else
10303 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010304 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010305#endif
10306 /* bash:
10307 * if interactive but not a login shell, sources ~/.bashrc
10308 * (--norc turns this off, --rcfile <file> overrides)
10309 */
10310
10311 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010312 /* note: ash and hush share this string */
10313 printf("\n\n%s %s\n"
10314 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10315 "\n",
10316 bb_banner,
10317 "hush - the humble shell"
10318 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010319 }
10320
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010321 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010322
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010323 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010324 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010325}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010326
10327
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010328/*
10329 * Built-ins
10330 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010331static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010332{
10333 return 0;
10334}
10335
Denys Vlasenko265062d2017-01-10 15:13:30 +010010336#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010337static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010338{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010339 int argc = string_array_len(argv);
10340 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010341}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010342#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010343#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010344static int FAST_FUNC builtin_test(char **argv)
10345{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010346 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010347}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010348#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010349#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010350static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010351{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010352 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010353}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010354#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010355#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010356static int FAST_FUNC builtin_printf(char **argv)
10357{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010358 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010359}
10360#endif
10361
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010362#if ENABLE_HUSH_HELP
10363static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10364{
10365 const struct built_in_command *x;
10366
10367 printf(
10368 "Built-in commands:\n"
10369 "------------------\n");
10370 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10371 if (x->b_descr)
10372 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10373 }
10374 return EXIT_SUCCESS;
10375}
10376#endif
10377
10378#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10379static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10380{
10381 show_history(G.line_input_state);
10382 return EXIT_SUCCESS;
10383}
10384#endif
10385
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010386static char **skip_dash_dash(char **argv)
10387{
10388 argv++;
10389 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10390 argv++;
10391 return argv;
10392}
10393
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010394static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010395{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010396 const char *newdir;
10397
10398 argv = skip_dash_dash(argv);
10399 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010400 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010401 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010402 * bash says "bash: cd: HOME not set" and does nothing
10403 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010404 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010405 const char *home = get_local_var_value("HOME");
10406 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010407 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010408 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010409 /* Mimic bash message exactly */
10410 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010411 return EXIT_FAILURE;
10412 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010413 /* Read current dir (get_cwd(1) is inside) and set PWD.
10414 * Note: do not enforce exporting. If PWD was unset or unexported,
10415 * set it again, but do not export. bash does the same.
10416 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010417 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010418 return EXIT_SUCCESS;
10419}
10420
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010421static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10422{
10423 puts(get_cwd(0));
10424 return EXIT_SUCCESS;
10425}
10426
10427static int FAST_FUNC builtin_eval(char **argv)
10428{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010429 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010430
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010431 if (!argv[0])
10432 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010433
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010434 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010435 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010436 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010437 /* bash:
10438 * eval "echo Hi; done" ("done" is syntax error):
10439 * "echo Hi" will not execute too.
10440 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010441 parse_and_run_string(argv[0]);
10442 } else {
10443 /* "The eval utility shall construct a command by
10444 * concatenating arguments together, separating
10445 * each with a <space> character."
10446 */
10447 char *str, *p;
10448 unsigned len = 0;
10449 char **pp = argv;
10450 do
10451 len += strlen(*pp) + 1;
10452 while (*++pp);
10453 str = p = xmalloc(len);
10454 pp = argv;
10455 for (;;) {
10456 p = stpcpy(p, *pp);
10457 pp++;
10458 if (!*pp)
10459 break;
10460 *p++ = ' ';
10461 }
10462 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010463 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010464 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010465 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010466 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010467 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010468}
10469
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010470static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010471{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010472 argv = skip_dash_dash(argv);
10473 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010474 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010475
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010476 /* Careful: we can end up here after [v]fork. Do not restore
10477 * tty pgrp then, only top-level shell process does that */
10478 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10479 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10480
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010481 /* Saved-redirect fds, script fds and G_interactive_fd are still
10482 * open here. However, they are all CLOEXEC, and execv below
10483 * closes them. Try interactive "exec ls -l /proc/self/fd",
10484 * it should show no extra open fds in the "ls" process.
10485 * If we'd try to run builtins/NOEXECs, this would need improving.
10486 */
10487 //close_saved_fds_and_FILE_fds();
10488
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010489 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010490 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010491 * and tcsetpgrp, and this is inherently racy.
10492 */
10493 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010494}
10495
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010496static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010498 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010499
10500 /* interactive bash:
10501 * # trap "echo EEE" EXIT
10502 * # exit
10503 * exit
10504 * There are stopped jobs.
10505 * (if there are _stopped_ jobs, running ones don't count)
10506 * # exit
10507 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010508 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010509 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010510 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010511 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010512
10513 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010514 argv = skip_dash_dash(argv);
10515 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010516 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010517 /* mimic bash: exit 123abc == exit 255 + error msg */
10518 xfunc_error_retval = 255;
10519 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010520 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010521}
10522
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010523#if ENABLE_HUSH_TYPE
10524/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10525static int FAST_FUNC builtin_type(char **argv)
10526{
10527 int ret = EXIT_SUCCESS;
10528
10529 while (*++argv) {
10530 const char *type;
10531 char *path = NULL;
10532
10533 if (0) {} /* make conditional compile easier below */
10534 /*else if (find_alias(*argv))
10535 type = "an alias";*/
10536#if ENABLE_HUSH_FUNCTIONS
10537 else if (find_function(*argv))
10538 type = "a function";
10539#endif
10540 else if (find_builtin(*argv))
10541 type = "a shell builtin";
10542 else if ((path = find_in_path(*argv)) != NULL)
10543 type = path;
10544 else {
10545 bb_error_msg("type: %s: not found", *argv);
10546 ret = EXIT_FAILURE;
10547 continue;
10548 }
10549
10550 printf("%s is %s\n", *argv, type);
10551 free(path);
10552 }
10553
10554 return ret;
10555}
10556#endif
10557
10558#if ENABLE_HUSH_READ
10559/* Interruptibility of read builtin in bash
10560 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10561 *
10562 * Empty trap makes read ignore corresponding signal, for any signal.
10563 *
10564 * SIGINT:
10565 * - terminates non-interactive shell;
10566 * - interrupts read in interactive shell;
10567 * if it has non-empty trap:
10568 * - executes trap and returns to command prompt in interactive shell;
10569 * - executes trap and returns to read in non-interactive shell;
10570 * SIGTERM:
10571 * - is ignored (does not interrupt) read in interactive shell;
10572 * - terminates non-interactive shell;
10573 * if it has non-empty trap:
10574 * - executes trap and returns to read;
10575 * SIGHUP:
10576 * - terminates shell (regardless of interactivity);
10577 * if it has non-empty trap:
10578 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010579 * SIGCHLD from children:
10580 * - does not interrupt read regardless of interactivity:
10581 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010582 */
10583static int FAST_FUNC builtin_read(char **argv)
10584{
10585 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010586 struct builtin_read_params params;
10587
10588 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010589
10590 /* "!": do not abort on errors.
10591 * Option string must start with "sr" to match BUILTIN_READ_xxx
10592 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010593 params.read_flags = getopt32(argv,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010594#if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010595 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010596#else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010597 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010598#endif
10599 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010600 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010601 return EXIT_FAILURE;
10602 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010603 params.argv = argv;
10604 params.setvar = set_local_var_from_halves;
10605 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010606
10607 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010608 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010609
10610 if ((uintptr_t)r == 1 && errno == EINTR) {
10611 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010612 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010613 goto again;
10614 }
10615
10616 if ((uintptr_t)r > 1) {
10617 bb_error_msg("%s", r);
10618 r = (char*)(uintptr_t)1;
10619 }
10620
10621 return (uintptr_t)r;
10622}
10623#endif
10624
10625#if ENABLE_HUSH_UMASK
10626static int FAST_FUNC builtin_umask(char **argv)
10627{
10628 int rc;
10629 mode_t mask;
10630
10631 rc = 1;
10632 mask = umask(0);
10633 argv = skip_dash_dash(argv);
10634 if (argv[0]) {
10635 mode_t old_mask = mask;
10636
10637 /* numeric umasks are taken as-is */
10638 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10639 if (!isdigit(argv[0][0]))
10640 mask ^= 0777;
10641 mask = bb_parse_mode(argv[0], mask);
10642 if (!isdigit(argv[0][0]))
10643 mask ^= 0777;
10644 if ((unsigned)mask > 0777) {
10645 mask = old_mask;
10646 /* bash messages:
10647 * bash: umask: 'q': invalid symbolic mode operator
10648 * bash: umask: 999: octal number out of range
10649 */
10650 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10651 rc = 0;
10652 }
10653 } else {
10654 /* Mimic bash */
10655 printf("%04o\n", (unsigned) mask);
10656 /* fall through and restore mask which we set to 0 */
10657 }
10658 umask(mask);
10659
10660 return !rc; /* rc != 0 - success */
10661}
10662#endif
10663
Denys Vlasenko41ade052017-01-08 18:56:24 +010010664#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010665static void print_escaped(const char *s)
10666{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010667 if (*s == '\'')
10668 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010669 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010670 const char *p = strchrnul(s, '\'');
10671 /* print 'xxxx', possibly just '' */
10672 printf("'%.*s'", (int)(p - s), s);
10673 if (*p == '\0')
10674 break;
10675 s = p;
10676 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010677 /* s points to '; print "'''...'''" */
10678 putchar('"');
10679 do putchar('\''); while (*++s == '\'');
10680 putchar('"');
10681 } while (*s);
10682}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010683#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010684
Denys Vlasenko1e660422017-07-17 21:10:50 +020010685#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010686static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010687{
10688 do {
10689 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010690 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010691
10692 /* So far we do not check that name is valid (TODO?) */
10693
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010694 if (*name_end == '\0') {
10695 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010696
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010697 vpp = get_ptr_to_local_var(name, name_end - name);
10698 var = vpp ? *vpp : NULL;
10699
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010700 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010701 /* export -n NAME (without =VALUE) */
10702 if (var) {
10703 var->flg_export = 0;
10704 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10705 unsetenv(name);
10706 } /* else: export -n NOT_EXISTING_VAR: no-op */
10707 continue;
10708 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010709 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010710 /* export NAME (without =VALUE) */
10711 if (var) {
10712 var->flg_export = 1;
10713 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10714 putenv(var->varstr);
10715 continue;
10716 }
10717 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010718 if (flags & SETFLAG_MAKE_RO) {
10719 /* readonly NAME (without =VALUE) */
10720 if (var) {
10721 var->flg_read_only = 1;
10722 continue;
10723 }
10724 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010725# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010726 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010727 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010728 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10729 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010730 /* "local x=abc; ...; local x" - ignore second local decl */
10731 continue;
10732 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010733 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010734# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010735 /* Exporting non-existing variable.
10736 * bash does not put it in environment,
10737 * but remembers that it is exported,
10738 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010739 * We just set it to "" and export.
10740 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010741 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010742 * bash sets the value to "".
10743 */
10744 /* Or, it's "readonly NAME" (without =VALUE).
10745 * bash remembers NAME and disallows its creation
10746 * in the future.
10747 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010748 name = xasprintf("%s=", name);
10749 } else {
10750 /* (Un)exporting/making local NAME=VALUE */
10751 name = xstrdup(name);
10752 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010753 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010754 if (set_local_var(name, flags))
10755 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010756 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010757 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010758}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010759#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010760
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010761#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010762static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010763{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010764 unsigned opt_unexport;
10765
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010766#if ENABLE_HUSH_EXPORT_N
10767 /* "!": do not abort on errors */
10768 opt_unexport = getopt32(argv, "!n");
10769 if (opt_unexport == (uint32_t)-1)
10770 return EXIT_FAILURE;
10771 argv += optind;
10772#else
10773 opt_unexport = 0;
10774 argv++;
10775#endif
10776
10777 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010778 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010779 if (e) {
10780 while (*e) {
10781#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010782 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010783#else
10784 /* ash emits: export VAR='VAL'
10785 * bash: declare -x VAR="VAL"
10786 * we follow ash example */
10787 const char *s = *e++;
10788 const char *p = strchr(s, '=');
10789
10790 if (!p) /* wtf? take next variable */
10791 continue;
10792 /* export var= */
10793 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010794 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010795 putchar('\n');
10796#endif
10797 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010798 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010799 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010800 return EXIT_SUCCESS;
10801 }
10802
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010803 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010804}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010805#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010806
Denys Vlasenko295fef82009-06-03 12:47:26 +020010807#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010808static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010809{
10810 if (G.func_nest_level == 0) {
10811 bb_error_msg("%s: not in a function", argv[0]);
10812 return EXIT_FAILURE; /* bash compat */
10813 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010814 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010815 /* Since all builtins run in a nested variable level,
10816 * need to use level - 1 here. Or else the variable will be removed at once
10817 * after builtin returns.
10818 */
10819 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010820}
10821#endif
10822
Denys Vlasenko1e660422017-07-17 21:10:50 +020010823#if ENABLE_HUSH_READONLY
10824static int FAST_FUNC builtin_readonly(char **argv)
10825{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010826 argv++;
10827 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010828 /* bash: readonly [-p]: list all readonly VARs
10829 * (-p has no effect in bash)
10830 */
10831 struct variable *e;
10832 for (e = G.top_var; e; e = e->next) {
10833 if (e->flg_read_only) {
10834//TODO: quote value: readonly VAR='VAL'
10835 printf("readonly %s\n", e->varstr);
10836 }
10837 }
10838 return EXIT_SUCCESS;
10839 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010840 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010841}
10842#endif
10843
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010844#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010845/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10846static int FAST_FUNC builtin_unset(char **argv)
10847{
10848 int ret;
10849 unsigned opts;
10850
10851 /* "!": do not abort on errors */
10852 /* "+": stop at 1st non-option */
10853 opts = getopt32(argv, "!+vf");
10854 if (opts == (unsigned)-1)
10855 return EXIT_FAILURE;
10856 if (opts == 3) {
10857 bb_error_msg("unset: -v and -f are exclusive");
10858 return EXIT_FAILURE;
10859 }
10860 argv += optind;
10861
10862 ret = EXIT_SUCCESS;
10863 while (*argv) {
10864 if (!(opts & 2)) { /* not -f */
10865 if (unset_local_var(*argv)) {
10866 /* unset <nonexistent_var> doesn't fail.
10867 * Error is when one tries to unset RO var.
10868 * Message was printed by unset_local_var. */
10869 ret = EXIT_FAILURE;
10870 }
10871 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010872# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010873 else {
10874 unset_func(*argv);
10875 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010876# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010877 argv++;
10878 }
10879 return ret;
10880}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010881#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010882
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010883#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010884/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10885 * built-in 'set' handler
10886 * SUSv3 says:
10887 * set [-abCefhmnuvx] [-o option] [argument...]
10888 * set [+abCefhmnuvx] [+o option] [argument...]
10889 * set -- [argument...]
10890 * set -o
10891 * set +o
10892 * Implementations shall support the options in both their hyphen and
10893 * plus-sign forms. These options can also be specified as options to sh.
10894 * Examples:
10895 * Write out all variables and their values: set
10896 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10897 * Turn on the -x and -v options: set -xv
10898 * Unset all positional parameters: set --
10899 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10900 * Set the positional parameters to the expansion of x, even if x expands
10901 * with a leading '-' or '+': set -- $x
10902 *
10903 * So far, we only support "set -- [argument...]" and some of the short names.
10904 */
10905static int FAST_FUNC builtin_set(char **argv)
10906{
10907 int n;
10908 char **pp, **g_argv;
10909 char *arg = *++argv;
10910
10911 if (arg == NULL) {
10912 struct variable *e;
10913 for (e = G.top_var; e; e = e->next)
10914 puts(e->varstr);
10915 return EXIT_SUCCESS;
10916 }
10917
10918 do {
10919 if (strcmp(arg, "--") == 0) {
10920 ++argv;
10921 goto set_argv;
10922 }
10923 if (arg[0] != '+' && arg[0] != '-')
10924 break;
10925 for (n = 1; arg[n]; ++n) {
10926 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10927 goto error;
10928 if (arg[n] == 'o' && argv[1])
10929 argv++;
10930 }
10931 } while ((arg = *++argv) != NULL);
10932 /* Now argv[0] is 1st argument */
10933
10934 if (arg == NULL)
10935 return EXIT_SUCCESS;
10936 set_argv:
10937
10938 /* NB: G.global_argv[0] ($0) is never freed/changed */
10939 g_argv = G.global_argv;
10940 if (G.global_args_malloced) {
10941 pp = g_argv;
10942 while (*++pp)
10943 free(*pp);
10944 g_argv[1] = NULL;
10945 } else {
10946 G.global_args_malloced = 1;
10947 pp = xzalloc(sizeof(pp[0]) * 2);
10948 pp[0] = g_argv[0]; /* retain $0 */
10949 g_argv = pp;
10950 }
10951 /* This realloc's G.global_argv */
10952 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10953
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010954 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010955
10956 return EXIT_SUCCESS;
10957
10958 /* Nothing known, so abort */
10959 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010960 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010961 return EXIT_FAILURE;
10962}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010963#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010964
10965static int FAST_FUNC builtin_shift(char **argv)
10966{
10967 int n = 1;
10968 argv = skip_dash_dash(argv);
10969 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010970 n = bb_strtou(argv[0], NULL, 10);
10971 if (errno || n < 0) {
10972 /* shared string with ash.c */
10973 bb_error_msg("Illegal number: %s", argv[0]);
10974 /*
10975 * ash aborts in this case.
10976 * bash prints error message and set $? to 1.
10977 * Interestingly, for "shift 99999" bash does not
10978 * print error message, but does set $? to 1
10979 * (and does no shifting at all).
10980 */
10981 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010982 }
10983 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010984 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010985 int m = 1;
10986 while (m <= n)
10987 free(G.global_argv[m++]);
10988 }
10989 G.global_argc -= n;
10990 memmove(&G.global_argv[1], &G.global_argv[n+1],
10991 G.global_argc * sizeof(G.global_argv[0]));
10992 return EXIT_SUCCESS;
10993 }
10994 return EXIT_FAILURE;
10995}
10996
Denys Vlasenko74d40582017-08-11 01:32:46 +020010997#if ENABLE_HUSH_GETOPTS
10998static int FAST_FUNC builtin_getopts(char **argv)
10999{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011000/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11001
Denys Vlasenko74d40582017-08-11 01:32:46 +020011002TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011003If a required argument is not found, and getopts is not silent,
11004a question mark (?) is placed in VAR, OPTARG is unset, and a
11005diagnostic message is printed. If getopts is silent, then a
11006colon (:) is placed in VAR and OPTARG is set to the option
11007character found.
11008
11009Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011010
11011"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011012*/
11013 char cbuf[2];
11014 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011015 int c, n, exitcode, my_opterr;
11016 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011017
11018 optstring = *++argv;
11019 if (!optstring || !(var = *++argv)) {
11020 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
11021 return EXIT_FAILURE;
11022 }
11023
Denys Vlasenko238ff982017-08-29 13:38:30 +020011024 if (argv[1])
11025 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11026 else
11027 argv = G.global_argv;
11028 cbuf[1] = '\0';
11029
11030 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011031 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011032 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011033 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011034 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011035 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011036
11037 /* getopts stops on first non-option. Add "+" to force that */
11038 /*if (optstring[0] != '+')*/ {
11039 char *s = alloca(strlen(optstring) + 2);
11040 sprintf(s, "+%s", optstring);
11041 optstring = s;
11042 }
11043
Denys Vlasenko238ff982017-08-29 13:38:30 +020011044 /* Naively, now we should just
11045 * cp = get_local_var_value("OPTIND");
11046 * optind = cp ? atoi(cp) : 0;
11047 * optarg = NULL;
11048 * opterr = my_opterr;
11049 * c = getopt(string_array_len(argv), argv, optstring);
11050 * and be done? Not so fast...
11051 * Unlike normal getopt() usage in C programs, here
11052 * each successive call will (usually) have the same argv[] CONTENTS,
11053 * but not the ADDRESSES. Worse yet, it's possible that between
11054 * invocations of "getopts", there will be calls to shell builtins
11055 * which use getopt() internally. Example:
11056 * while getopts "abc" RES -a -bc -abc de; do
11057 * unset -ff func
11058 * done
11059 * This would not work correctly: getopt() call inside "unset"
11060 * modifies internal libc state which is tracking position in
11061 * multi-option strings ("-abc"). At best, it can skip options
11062 * or return the same option infinitely. With glibc implementation
11063 * of getopt(), it would use outright invalid pointers and return
11064 * garbage even _without_ "unset" mangling internal state.
11065 *
11066 * We resort to resetting getopt() state and calling it N times,
11067 * until we get Nth result (or failure).
11068 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11069 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011070 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011071 count = 0;
11072 n = string_array_len(argv);
11073 do {
11074 optarg = NULL;
11075 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11076 c = getopt(n, argv, optstring);
11077 if (c < 0)
11078 break;
11079 count++;
11080 } while (count <= G.getopt_count);
11081
11082 /* Set OPTIND. Prevent resetting of the magic counter! */
11083 set_local_var_from_halves("OPTIND", utoa(optind));
11084 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011085 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011086
11087 /* Set OPTARG */
11088 /* Always set or unset, never left as-is, even on exit/error:
11089 * "If no option was found, or if the option that was found
11090 * does not have an option-argument, OPTARG shall be unset."
11091 */
11092 cp = optarg;
11093 if (c == '?') {
11094 /* If ":optstring" and unknown option is seen,
11095 * it is stored to OPTARG.
11096 */
11097 if (optstring[1] == ':') {
11098 cbuf[0] = optopt;
11099 cp = cbuf;
11100 }
11101 }
11102 if (cp)
11103 set_local_var_from_halves("OPTARG", cp);
11104 else
11105 unset_local_var("OPTARG");
11106
11107 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011108 exitcode = EXIT_SUCCESS;
11109 if (c < 0) { /* -1: end of options */
11110 exitcode = EXIT_FAILURE;
11111 c = '?';
11112 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011113
Denys Vlasenko238ff982017-08-29 13:38:30 +020011114 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011115 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011116 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011117
Denys Vlasenko74d40582017-08-11 01:32:46 +020011118 return exitcode;
11119}
11120#endif
11121
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011122static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011123{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011124 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011125 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011126 save_arg_t sv;
11127 char *args_need_save;
11128#if ENABLE_HUSH_FUNCTIONS
11129 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011130#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011131
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011132 argv = skip_dash_dash(argv);
11133 filename = argv[0];
11134 if (!filename) {
11135 /* bash says: "bash: .: filename argument required" */
11136 return 2; /* bash compat */
11137 }
11138 arg_path = NULL;
11139 if (!strchr(filename, '/')) {
11140 arg_path = find_in_path(filename);
11141 if (arg_path)
11142 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011143 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011144 errno = ENOENT;
11145 bb_simple_perror_msg(filename);
11146 return EXIT_FAILURE;
11147 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011148 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011149 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011150 free(arg_path);
11151 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011152 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011153 /* POSIX: non-interactive shell should abort here,
11154 * not merely fail. So far no one complained :)
11155 */
11156 return EXIT_FAILURE;
11157 }
11158
11159#if ENABLE_HUSH_FUNCTIONS
11160 sv_flg = G_flag_return_in_progress;
11161 /* "we are inside sourced file, ok to use return" */
11162 G_flag_return_in_progress = -1;
11163#endif
11164 args_need_save = argv[1]; /* used as a boolean variable */
11165 if (args_need_save)
11166 save_and_replace_G_args(&sv, argv);
11167
11168 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11169 G.last_exitcode = 0;
11170 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011171 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011172
11173 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11174 restore_G_args(&sv, argv);
11175#if ENABLE_HUSH_FUNCTIONS
11176 G_flag_return_in_progress = sv_flg;
11177#endif
11178
11179 return G.last_exitcode;
11180}
11181
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011182#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011183static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011184{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011185 int sig;
11186 char *new_cmd;
11187
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011188 if (!G_traps)
11189 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011190
11191 argv++;
11192 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011193 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011194 /* No args: print all trapped */
11195 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011196 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011197 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011198 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011199 /* note: bash adds "SIG", but only if invoked
11200 * as "bash". If called as "sh", or if set -o posix,
11201 * then it prints short signal names.
11202 * We are printing short names: */
11203 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011204 }
11205 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011206 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011207 return EXIT_SUCCESS;
11208 }
11209
11210 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011211 /* If first arg is a number: reset all specified signals */
11212 sig = bb_strtou(*argv, NULL, 10);
11213 if (errno == 0) {
11214 int ret;
11215 process_sig_list:
11216 ret = EXIT_SUCCESS;
11217 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011218 sighandler_t handler;
11219
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011220 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011221 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011222 ret = EXIT_FAILURE;
11223 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011224 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011225 continue;
11226 }
11227
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011228 free(G_traps[sig]);
11229 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011230
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011231 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011232 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011233
11234 /* There is no signal for 0 (EXIT) */
11235 if (sig == 0)
11236 continue;
11237
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011238 if (new_cmd)
11239 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11240 else
11241 /* We are removing trap handler */
11242 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011243 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011244 }
11245 return ret;
11246 }
11247
11248 if (!argv[1]) { /* no second arg */
11249 bb_error_msg("trap: invalid arguments");
11250 return EXIT_FAILURE;
11251 }
11252
11253 /* First arg is "-": reset all specified to default */
11254 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11255 /* Everything else: set arg as signal handler
11256 * (includes "" case, which ignores signal) */
11257 if (argv[0][0] == '-') {
11258 if (argv[0][1] == '\0') { /* "-" */
11259 /* new_cmd remains NULL: "reset these sigs" */
11260 goto reset_traps;
11261 }
11262 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11263 argv++;
11264 }
11265 /* else: "-something", no special meaning */
11266 }
11267 new_cmd = *argv;
11268 reset_traps:
11269 argv++;
11270 goto process_sig_list;
11271}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011272#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011273
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011274#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011275static struct pipe *parse_jobspec(const char *str)
11276{
11277 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011278 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011279
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011280 if (sscanf(str, "%%%u", &jobnum) != 1) {
11281 if (str[0] != '%'
11282 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11283 ) {
11284 bb_error_msg("bad argument '%s'", str);
11285 return NULL;
11286 }
11287 /* It is "%%", "%+" or "%" - current job */
11288 jobnum = G.last_jobid;
11289 if (jobnum == 0) {
11290 bb_error_msg("no current job");
11291 return NULL;
11292 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011293 }
11294 for (pi = G.job_list; pi; pi = pi->next) {
11295 if (pi->jobid == jobnum) {
11296 return pi;
11297 }
11298 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011299 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011300 return NULL;
11301}
11302
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011303static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11304{
11305 struct pipe *job;
11306 const char *status_string;
11307
11308 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11309 for (job = G.job_list; job; job = job->next) {
11310 if (job->alive_cmds == job->stopped_cmds)
11311 status_string = "Stopped";
11312 else
11313 status_string = "Running";
11314
11315 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11316 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011317
11318 clean_up_last_dead_job();
11319
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011320 return EXIT_SUCCESS;
11321}
11322
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011323/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011324static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011325{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011326 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011327 struct pipe *pi;
11328
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011329 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011330 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011331
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011332 /* If they gave us no args, assume they want the last backgrounded task */
11333 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011334 for (pi = G.job_list; pi; pi = pi->next) {
11335 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011336 goto found;
11337 }
11338 }
11339 bb_error_msg("%s: no current job", argv[0]);
11340 return EXIT_FAILURE;
11341 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011342
11343 pi = parse_jobspec(argv[1]);
11344 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011345 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011346 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011347 /* TODO: bash prints a string representation
11348 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011349 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011350 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011351 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011352 }
11353
11354 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011355 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11356 for (i = 0; i < pi->num_cmds; i++) {
11357 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011358 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011359 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011360
11361 i = kill(- pi->pgrp, SIGCONT);
11362 if (i < 0) {
11363 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011364 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011365 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011366 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011367 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011368 }
11369
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011370 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011371 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011372 return checkjobs_and_fg_shell(pi);
11373 }
11374 return EXIT_SUCCESS;
11375}
11376#endif
11377
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011378#if ENABLE_HUSH_KILL
11379static int FAST_FUNC builtin_kill(char **argv)
11380{
11381 int ret = 0;
11382
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011383# if ENABLE_HUSH_JOB
11384 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11385 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011386
11387 do {
11388 struct pipe *pi;
11389 char *dst;
11390 int j, n;
11391
11392 if (argv[i][0] != '%')
11393 continue;
11394 /*
11395 * "kill %N" - job kill
11396 * Converting to pgrp / pid kill
11397 */
11398 pi = parse_jobspec(argv[i]);
11399 if (!pi) {
11400 /* Eat bad jobspec */
11401 j = i;
11402 do {
11403 j++;
11404 argv[j - 1] = argv[j];
11405 } while (argv[j]);
11406 ret = 1;
11407 i--;
11408 continue;
11409 }
11410 /*
11411 * In jobs started under job control, we signal
11412 * entire process group by kill -PGRP_ID.
11413 * This happens, f.e., in interactive shell.
11414 *
11415 * Otherwise, we signal each child via
11416 * kill PID1 PID2 PID3.
11417 * Testcases:
11418 * sh -c 'sleep 1|sleep 1 & kill %1'
11419 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11420 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11421 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011422 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011423 dst = alloca(n * sizeof(int)*4);
11424 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011425 if (G_interactive_fd)
11426 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011427 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011428 struct command *cmd = &pi->cmds[j];
11429 /* Skip exited members of the job */
11430 if (cmd->pid == 0)
11431 continue;
11432 /*
11433 * kill_main has matching code to expect
11434 * leading space. Needed to not confuse
11435 * negative pids with "kill -SIGNAL_NO" syntax
11436 */
11437 dst += sprintf(dst, " %u", (int)cmd->pid);
11438 }
11439 *dst = '\0';
11440 } while (argv[++i]);
11441 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011442# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011443
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011444 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011445 ret = run_applet_main(argv, kill_main);
11446 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011447 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011448 return ret;
11449}
11450#endif
11451
11452#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011453/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011454#if !ENABLE_HUSH_JOB
11455# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11456#endif
11457static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011458{
11459 int ret = 0;
11460 for (;;) {
11461 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011462 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011463
Denys Vlasenko830ea352016-11-08 04:59:11 +010011464 if (!sigisemptyset(&G.pending_set))
11465 goto check_sig;
11466
Denys Vlasenko7e675362016-10-28 21:57:31 +020011467 /* waitpid is not interruptible by SA_RESTARTed
11468 * signals which we use. Thus, this ugly dance:
11469 */
11470
11471 /* Make sure possible SIGCHLD is stored in kernel's
11472 * pending signal mask before we call waitpid.
11473 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011474 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011475 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011476 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011477 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011478
11479 if (!sigisemptyset(&G.pending_set)) {
11480 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011481 goto restore;
11482 }
11483
11484 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011485/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011486 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011487 debug_printf_exec("checkjobs:%d\n", ret);
11488#if ENABLE_HUSH_JOB
11489 if (waitfor_pipe) {
11490 int rcode = job_exited_or_stopped(waitfor_pipe);
11491 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11492 if (rcode >= 0) {
11493 ret = rcode;
11494 sigprocmask(SIG_SETMASK, &oldset, NULL);
11495 break;
11496 }
11497 }
11498#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011499 /* if ECHILD, there are no children (ret is -1 or 0) */
11500 /* if ret == 0, no children changed state */
11501 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011502 if (errno == ECHILD || ret) {
11503 ret--;
11504 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011505 ret = 0;
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011506#if ENABLE_HUSH_BASH_COMPAT
11507 if (waitfor_pid == -1 && errno == ECHILD) {
11508 /* exitcode of "wait -n" with no children is 127, not 0 */
11509 ret = 127;
11510 }
11511#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011512 sigprocmask(SIG_SETMASK, &oldset, NULL);
11513 break;
11514 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011515 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011516 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11517 /* Note: sigsuspend invokes signal handler */
11518 sigsuspend(&oldset);
11519 restore:
11520 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011521 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011522 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011523 sig = check_and_run_traps();
11524 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011525 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011526 ret = 128 + sig;
11527 break;
11528 }
11529 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11530 }
11531 return ret;
11532}
11533
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011534static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011535{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011536 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011537 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011538
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011539 argv = skip_dash_dash(argv);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011540#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011541 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011542 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011543 /* (bash accepts "wait -n PID" too and ignores PID) */
11544 G.dead_job_exitcode = -1;
11545 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011546 }
11547#endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011548 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011549 /* Don't care about wait results */
11550 /* Note 1: must wait until there are no more children */
11551 /* Note 2: must be interruptible */
11552 /* Examples:
11553 * $ sleep 3 & sleep 6 & wait
11554 * [1] 30934 sleep 3
11555 * [2] 30935 sleep 6
11556 * [1] Done sleep 3
11557 * [2] Done sleep 6
11558 * $ sleep 3 & sleep 6 & wait
11559 * [1] 30936 sleep 3
11560 * [2] 30937 sleep 6
11561 * [1] Done sleep 3
11562 * ^C <-- after ~4 sec from keyboard
11563 * $
11564 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011565 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011566 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011567
Denys Vlasenko7e675362016-10-28 21:57:31 +020011568 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011569 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011570 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011571#if ENABLE_HUSH_JOB
11572 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011573 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011574 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011575 wait_pipe = parse_jobspec(*argv);
11576 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011577 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011578 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011579 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011580 } else {
11581 /* waiting on "last dead job" removes it */
11582 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011583 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011584 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011585 /* else: parse_jobspec() already emitted error msg */
11586 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011587 }
11588#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011589 /* mimic bash message */
11590 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011591 ret = EXIT_FAILURE;
11592 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011593 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011594
Denys Vlasenko7e675362016-10-28 21:57:31 +020011595 /* Do we have such child? */
11596 ret = waitpid(pid, &status, WNOHANG);
11597 if (ret < 0) {
11598 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011599 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011600 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011601 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011602 /* "wait $!" but last bg task has already exited. Try:
11603 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11604 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011605 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011606 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011607 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011608 } else {
11609 /* Example: "wait 1". mimic bash message */
11610 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011611 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011612 } else {
11613 /* ??? */
11614 bb_perror_msg("wait %s", *argv);
11615 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011616 continue; /* bash checks all argv[] */
11617 }
11618 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011619 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011620 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011621 } else {
11622 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011623 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011624 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011625 if (WIFSIGNALED(status))
11626 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011627 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011628 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011629
11630 return ret;
11631}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011632#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011633
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011634#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11635static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11636{
11637 if (argv[1]) {
11638 def = bb_strtou(argv[1], NULL, 10);
11639 if (errno || def < def_min || argv[2]) {
11640 bb_error_msg("%s: bad arguments", argv[0]);
11641 def = UINT_MAX;
11642 }
11643 }
11644 return def;
11645}
11646#endif
11647
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011648#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011649static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011650{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011651 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011652 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011653 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011654 /* if we came from builtin_continue(), need to undo "= 1" */
11655 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011656 return EXIT_SUCCESS; /* bash compat */
11657 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011658 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011659
11660 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11661 if (depth == UINT_MAX)
11662 G.flag_break_continue = BC_BREAK;
11663 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011664 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011665
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011666 return EXIT_SUCCESS;
11667}
11668
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011669static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011670{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011671 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11672 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011673}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011674#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011675
11676#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011677static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011678{
11679 int rc;
11680
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011681 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011682 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11683 return EXIT_FAILURE; /* bash compat */
11684 }
11685
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011686 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011687
11688 /* bash:
11689 * out of range: wraps around at 256, does not error out
11690 * non-numeric param:
11691 * f() { false; return qwe; }; f; echo $?
11692 * bash: return: qwe: numeric argument required <== we do this
11693 * 255 <== we also do this
11694 */
11695 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11696 return rc;
11697}
11698#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011699
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011700#if ENABLE_HUSH_TIMES
11701static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11702{
11703 static const uint8_t times_tbl[] ALIGN1 = {
11704 ' ', offsetof(struct tms, tms_utime),
11705 '\n', offsetof(struct tms, tms_stime),
11706 ' ', offsetof(struct tms, tms_cutime),
11707 '\n', offsetof(struct tms, tms_cstime),
11708 0
11709 };
11710 const uint8_t *p;
11711 unsigned clk_tck;
11712 struct tms buf;
11713
11714 clk_tck = bb_clk_tck();
11715
11716 times(&buf);
11717 p = times_tbl;
11718 do {
11719 unsigned sec, frac;
11720 unsigned long t;
11721 t = *(clock_t *)(((char *) &buf) + p[1]);
11722 sec = t / clk_tck;
11723 frac = t % clk_tck;
11724 printf("%um%u.%03us%c",
11725 sec / 60, sec % 60,
11726 (frac * 1000) / clk_tck,
11727 p[0]);
11728 p += 2;
11729 } while (*p);
11730
11731 return EXIT_SUCCESS;
11732}
11733#endif
11734
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011735#if ENABLE_HUSH_MEMLEAK
11736static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11737{
11738 void *p;
11739 unsigned long l;
11740
11741# ifdef M_TRIM_THRESHOLD
11742 /* Optional. Reduces probability of false positives */
11743 malloc_trim(0);
11744# endif
11745 /* Crude attempt to find where "free memory" starts,
11746 * sans fragmentation. */
11747 p = malloc(240);
11748 l = (unsigned long)p;
11749 free(p);
11750 p = malloc(3400);
11751 if (l < (unsigned long)p) l = (unsigned long)p;
11752 free(p);
11753
11754
11755# if 0 /* debug */
11756 {
11757 struct mallinfo mi = mallinfo();
11758 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11759 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11760 }
11761# endif
11762
11763 if (!G.memleak_value)
11764 G.memleak_value = l;
11765
11766 l -= G.memleak_value;
11767 if ((long)l < 0)
11768 l = 0;
11769 l /= 1024;
11770 if (l > 127)
11771 l = 127;
11772
11773 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11774 return l;
11775}
11776#endif