blob: c26484b49f2d4ede169c94bb722ea8bd391f14fd [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 Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 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
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process 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
360#ifndef F_DUPFD_CLOEXEC
361# define F_DUPFD_CLOEXEC F_DUPFD
362#endif
363#ifndef PIPE_BUF
364# define PIPE_BUF 4096 /* amount of buffering in a pipe */
365#endif
366
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000367
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100368/* So far, all bash compat is controlled by one config option */
369/* Separate defines document which part of code implements what */
370#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100372#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200374#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200375#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376
377
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200378/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000379#define LEAK_HUNTING 0
380#define BUILD_AS_NOMMU 0
381/* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
384 */
385#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200386/* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
391 */
392#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200393/* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
395 */
396#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000397
398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000399#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400# undef BB_MMU
401# undef USE_FOR_NOMMU
402# undef USE_FOR_MMU
403# define BB_MMU 0
404# define USE_FOR_NOMMU(...) __VA_ARGS__
405# define USE_FOR_MMU(...)
406#endif
407
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200408#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100409#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000410/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef CONFIG_FEATURE_SH_STANDALONE
412# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000413# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100414# undef IF_NOT_FEATURE_SH_STANDALONE
415# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# define IF_FEATURE_SH_STANDALONE(...)
417# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000418#endif
419
Denis Vlasenko05743d72008-02-10 12:10:08 +0000420#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# undef ENABLE_FEATURE_EDITING
422# define ENABLE_FEATURE_EDITING 0
423# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200425# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427#endif
428
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000429/* Do we support ANY keywords? */
430#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000431# define HAS_KEYWORDS 1
432# define IF_HAS_KEYWORDS(...) __VA_ARGS__
433# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000434#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000435# define HAS_KEYWORDS 0
436# define IF_HAS_KEYWORDS(...)
437# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000439
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000440/* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200444#define debug_printf_parse(...) do {} while (0)
445#define debug_printf_heredoc(...) do {} while (0)
446#define debug_print_tree(a, b) do {} while (0)
447#define debug_printf_exec(...) do {} while (0)
448#define debug_printf_env(...) do {} while (0)
449#define debug_printf_jobs(...) do {} while (0)
450#define debug_printf_expand(...) do {} while (0)
451#define debug_printf_varexp(...) do {} while (0)
452#define debug_printf_glob(...) do {} while (0)
453#define debug_printf_redir(...) do {} while (0)
454#define debug_printf_list(...) do {} while (0)
455#define debug_printf_subst(...) do {} while (0)
456#define debug_printf_prompt(...) do {} while (0)
457#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000458
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000459#define ERR_PTR ((void*)(long)1)
460
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100461#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000462
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200463#define _SPECIAL_VARS_STR "_*@$!?#"
464#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
465#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100466#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200467/* Support / and // replace ops */
468/* Note that // is stored as \ in "encoded" string representation */
469# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
470# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
471# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
472#else
473# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
474# define VAR_SUBST_OPS "%#:-=+?"
475# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
476#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200477
Denys Vlasenko932b9972018-01-11 12:39:48 +0100478#define SPECIAL_VAR_SYMBOL_STR "\3"
479#define SPECIAL_VAR_SYMBOL 3
480/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
481#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000482
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200483struct variable;
484
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000485static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
486
487/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000488 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000489 */
490#if !BB_MMU
491typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200492 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000493 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000494 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000495} nommu_save_t;
496#endif
497
Denys Vlasenko9b782552010-09-08 13:33:26 +0200498enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000499 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000500#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000501 RES_IF ,
502 RES_THEN ,
503 RES_ELIF ,
504 RES_ELSE ,
505 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000506#endif
507#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000508 RES_FOR ,
509 RES_WHILE ,
510 RES_UNTIL ,
511 RES_DO ,
512 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000513#endif
514#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000515 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000516#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000517#if ENABLE_HUSH_CASE
518 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200519 /* three pseudo-keywords support contrived "case" syntax: */
520 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
521 RES_MATCH , /* "word)" */
522 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523 RES_ESAC ,
524#endif
525 RES_XXXX ,
526 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200527};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000528
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000529typedef struct o_string {
530 char *data;
531 int length; /* position where data is appended */
532 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200533 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000534 /* At least some part of the string was inside '' or "",
535 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200536 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200538 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000539} o_string;
540enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200541 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
542 EXP_FLAG_GLOB = 0x2,
543 /* Protect newly added chars against globbing
544 * by prepending \ to *, ?, [, \ */
545 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
546};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000547/* Used for initialization: o_string foo = NULL_O_STRING; */
548#define NULL_O_STRING { NULL }
549
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200550#ifndef debug_printf_parse
551static const char *const assignment_flag[] = {
552 "MAYBE_ASSIGNMENT",
553 "DEFINITELY_ASSIGNMENT",
554 "NOT_ASSIGNMENT",
555 "WORD_IS_KEYWORD",
556};
557#endif
558
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000559typedef struct in_str {
560 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200561 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200562 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000564} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000565
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200566/* The descrip member of this structure is only used to make
567 * debugging output pretty */
568static const struct {
569 int mode;
570 signed char default_fd;
571 char descrip[3];
572} redir_table[] = {
573 { O_RDONLY, 0, "<" },
574 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
575 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
576 { O_CREAT|O_RDWR, 1, "<>" },
577 { O_RDONLY, 0, "<<" },
578/* Should not be needed. Bogus default_fd helps in debugging */
579/* { O_RDONLY, 77, "<<" }, */
580};
581
Eric Andersen25f27032001-04-26 23:22:31 +0000582struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000583 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000584 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000585 int rd_fd; /* fd to redirect */
586 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
587 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000588 smallint rd_type; /* (enum redir_type) */
589 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000590 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200591 * bit 0: do we need to trim leading tabs?
592 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593 */
Eric Andersen25f27032001-04-26 23:22:31 +0000594};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000595typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200596 REDIRECT_INPUT = 0,
597 REDIRECT_OVERWRITE = 1,
598 REDIRECT_APPEND = 2,
599 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000600 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200601 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000602
603 REDIRFD_CLOSE = -3,
604 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000605 REDIRFD_TO_FILE = -1,
606 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000607
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000608 HEREDOC_SKIPTABS = 1,
609 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000610} redir_type;
611
Eric Andersen25f27032001-04-26 23:22:31 +0000612
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000613struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000614 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200615 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100616#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100617 unsigned lineno;
618#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200619 smallint cmd_type; /* CMD_xxx */
620#define CMD_NORMAL 0
621#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200622#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
623/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
624 * "export v=t*"
625 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200626# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000627#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200628#if ENABLE_HUSH_FUNCTIONS
629# define CMD_FUNCDEF 3
630#endif
631
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100632 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200633 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
634 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000635#if !BB_MMU
636 char *group_as_string;
637#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000638#if ENABLE_HUSH_FUNCTIONS
639 struct function *child_func;
640/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200641 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000642 * When we execute "f1() {a;}" cmd, we create new function and clear
643 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200644 * When we execute "f1() {b;}", we notice that f1 exists,
645 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646 * we put those fields back into cmd->xxx
647 * (struct function has ->parent_cmd ptr to facilitate that).
648 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
649 * Without this trick, loop would execute a;b;b;b;...
650 * instead of correct sequence a;b;a;b;...
651 * When command is freed, it severs the link
652 * (sets ->child_func->parent_cmd to NULL).
653 */
654#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000655 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000656/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
657 * and on execution these are substituted with their values.
658 * Substitution can make _several_ words out of one argv[n]!
659 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000660 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000661 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000662 struct redir_struct *redirects; /* I/O redirections */
663};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000664/* Is there anything in this command at all? */
665#define IS_NULL_CMD(cmd) \
666 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
667
Eric Andersen25f27032001-04-26 23:22:31 +0000668struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000669 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000670 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000671 int alive_cmds; /* number of commands running (not exited) */
672 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000673#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100674 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000675 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000676 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000677#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000678 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000679 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000680 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
681 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000682};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000683typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100684 PIPE_SEQ = 0,
685 PIPE_AND = 1,
686 PIPE_OR = 2,
687 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000688} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000689/* Is there anything in this pipe at all? */
690#define IS_NULL_PIPE(pi) \
691 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000692
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000693/* This holds pointers to the various results of parsing */
694struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000697 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000698 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000699 /* last command in pipe (being constructed right now) */
700 struct command *command;
701 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000702 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200703 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000704#if !BB_MMU
705 o_string as_string;
706#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200707 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000708#if HAS_KEYWORDS
709 smallint ctx_res_w;
710 smallint ctx_inverted; /* "! cmd | cmd" */
711#if ENABLE_HUSH_CASE
712 smallint ctx_dsemicolon; /* ";;" seen */
713#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
715 int old_flag;
716 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000717 * example: "if pipe1; pipe2; then pipe3; fi"
718 * when we see "if" or "then", we malloc and copy current context,
719 * and make ->stack point to it. then we parse pipeN.
720 * when closing "then" / fi" / whatever is found,
721 * we move list_head into ->stack->command->group,
722 * copy ->stack into current context, and delete ->stack.
723 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000724 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000725 struct parse_context *stack;
726#endif
727};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200728enum {
729 MAYBE_ASSIGNMENT = 0,
730 DEFINITELY_ASSIGNMENT = 1,
731 NOT_ASSIGNMENT = 2,
732 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
733 WORD_IS_KEYWORD = 3,
734};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000735
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000736/* On program start, environ points to initial environment.
737 * putenv adds new pointers into it, unsetenv removes them.
738 * Neither of these (de)allocates the strings.
739 * setenv allocates new strings in malloc space and does putenv,
740 * and thus setenv is unusable (leaky) for shell's purposes */
741#define setenv(...) setenv_is_leaky_dont_use()
742struct variable {
743 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000744 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000745 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200746 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000747 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000748 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000749};
750
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000751enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000752 BC_BREAK = 1,
753 BC_CONTINUE = 2,
754};
755
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000756#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000757struct function {
758 struct function *next;
759 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000760 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000761 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200762# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000763 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200764# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000766#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000767
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000768
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100769/* set -/+o OPT support. (TODO: make it optional)
770 * bash supports the following opts:
771 * allexport off
772 * braceexpand on
773 * emacs on
774 * errexit off
775 * errtrace off
776 * functrace off
777 * hashall on
778 * histexpand off
779 * history on
780 * ignoreeof off
781 * interactive-comments on
782 * keyword off
783 * monitor on
784 * noclobber off
785 * noexec off
786 * noglob off
787 * nolog off
788 * notify off
789 * nounset off
790 * onecmd off
791 * physical off
792 * pipefail off
793 * posix off
794 * privileged off
795 * verbose off
796 * vi off
797 * xtrace off
798 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800799static const char o_opt_strings[] ALIGN1 =
800 "pipefail\0"
801 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200802 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800803#if ENABLE_HUSH_MODE_X
804 "xtrace\0"
805#endif
806 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100807enum {
808 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800809 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200810 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800811#if ENABLE_HUSH_MODE_X
812 OPT_O_XTRACE,
813#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100814 NUM_OPT_O
815};
816
817
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200818struct FILE_list {
819 struct FILE_list *next;
820 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200821 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200822};
823
824
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000826/* Sorted roughly by size (smaller offsets == smaller code) */
827struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000828 /* interactive_fd != 0 means we are an interactive shell.
829 * If we are, then saved_tty_pgrp can also be != 0, meaning
830 * that controlling tty is available. With saved_tty_pgrp == 0,
831 * job control still works, but terminal signals
832 * (^C, ^Z, ^Y, ^\) won't work at all, and background
833 * process groups can only be created with "cmd &".
834 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
835 * to give tty to the foreground process group,
836 * and will take it back when the group is stopped (^Z)
837 * or killed (^C).
838 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839#if ENABLE_HUSH_INTERACTIVE
840 /* 'interactive_fd' is a fd# open to ctty, if we have one
841 * _AND_ if we decided to act interactively */
842 int interactive_fd;
843 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200844 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000846#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000847# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000848#endif
849#if ENABLE_FEATURE_EDITING
850 line_input_t *line_input_state;
851#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000852 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200853 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000854 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200855#if ENABLE_HUSH_RANDOM_SUPPORT
856 random_t random_gen;
857#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000858#if ENABLE_HUSH_JOB
859 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100860 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000861 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000862 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400863# define G_saved_tty_pgrp (G.saved_tty_pgrp)
864#else
865# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000866#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200867 /* How deeply are we in context where "set -e" is ignored */
868 int errexit_depth;
869 /* "set -e" rules (do we follow them correctly?):
870 * Exit if pipe, list, or compound command exits with a non-zero status.
871 * Shell does not exit if failed command is part of condition in
872 * if/while, part of && or || list except the last command, any command
873 * in a pipe but the last, or if the command's return value is being
874 * inverted with !. If a compound command other than a subshell returns a
875 * non-zero status because a command failed while -e was being ignored, the
876 * shell does not exit. A trap on ERR, if set, is executed before the shell
877 * exits [ERR is a bashism].
878 *
879 * If a compound command or function executes in a context where -e is
880 * ignored, none of the commands executed within are affected by the -e
881 * setting. If a compound command or function sets -e while executing in a
882 * context where -e is ignored, that setting does not have any effect until
883 * the compound command or the command containing the function call completes.
884 */
885
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100886 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100887#if ENABLE_HUSH_MODE_X
888# define G_x_mode (G.o_opt[OPT_O_XTRACE])
889#else
890# define G_x_mode 0
891#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200892#if ENABLE_HUSH_INTERACTIVE
893 smallint promptmode; /* 0: PS1, 1: PS2 */
894#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000895 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000896#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000897 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000898#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000899#if ENABLE_HUSH_FUNCTIONS
900 /* 0: outside of a function (or sourced file)
901 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000902 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000903 */
904 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200905# define G_flag_return_in_progress (G.flag_return_in_progress)
906#else
907# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000908#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000909 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200910 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000911 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200912 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200913 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100914#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000915 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000916 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100917# define G_global_args_malloced (G.global_args_malloced)
918#else
919# define G_global_args_malloced 0
920#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000921 /* how many non-NULL argv's we have. NB: $# + 1 */
922 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000923 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000925 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000927#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000928 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000929 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000930#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200931#if ENABLE_HUSH_GETOPTS
932 unsigned getopt_count;
933#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200935 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000936 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200937 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200938 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200939 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200940 unsigned var_nest_level;
941#if ENABLE_HUSH_FUNCTIONS
942# if ENABLE_HUSH_LOCAL
943 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200944# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200945 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000946#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000947 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200948#if ENABLE_HUSH_FAST
949 unsigned count_SIGCHLD;
950 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200951 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200952#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100953#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100954 unsigned lineno;
955 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100956#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200957 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200958 /* Which signals have non-DFL handler (even with no traps set)?
959 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200960 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200961 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200962 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200963 * Other than these two times, never modified.
964 */
965 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200966#if ENABLE_HUSH_JOB
967 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100968# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200969#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200970# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200971#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100972#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000973 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100974# define G_traps G.traps
975#else
976# define G_traps ((char**)NULL)
977#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200978 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100979#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000980 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100981#endif
982#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000984#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200985 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200986#if ENABLE_FEATURE_EDITING
987 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
988#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000989};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000990#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000991/* Not #defining name to G.name - this quickly gets unwieldy
992 * (too many defines). Also, I actually prefer to see when a variable
993 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000994#define INIT_G() do { \
995 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200996 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
997 sigfillset(&G.sa.sa_mask); \
998 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000999} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001000
1001
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001003static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001004#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001005static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001006#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001007static int builtin_eval(char **argv) FAST_FUNC;
1008static int builtin_exec(char **argv) FAST_FUNC;
1009static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001010#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001011static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001012#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001013#if ENABLE_HUSH_READONLY
1014static int builtin_readonly(char **argv) FAST_FUNC;
1015#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001017static int builtin_fg_bg(char **argv) FAST_FUNC;
1018static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001019#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001020#if ENABLE_HUSH_GETOPTS
1021static int builtin_getopts(char **argv) FAST_FUNC;
1022#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001023#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001024static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001025#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001026#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001027static int builtin_history(char **argv) FAST_FUNC;
1028#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001029#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001031#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001032#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001033static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001034#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001035#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001036static int builtin_printf(char **argv) FAST_FUNC;
1037#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001039#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001041#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001042#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001043static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001044#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001045static int builtin_shift(char **argv) FAST_FUNC;
1046static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001047#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001048static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001049#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001050#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001052#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001053#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001055#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001056#if ENABLE_HUSH_TIMES
1057static int builtin_times(char **argv) FAST_FUNC;
1058#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001060#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001061static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001062#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001063#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001064static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001065#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001066#if ENABLE_HUSH_KILL
1067static int builtin_kill(char **argv) FAST_FUNC;
1068#endif
1069#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001071#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_break(char **argv) FAST_FUNC;
1074static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001076#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001078#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001079
1080/* Table of built-in functions. They can be forked or not, depending on
1081 * context: within pipes, they fork. As simple commands, they do not.
1082 * When used in non-forking context, they can change global variables
1083 * in the parent shell process. If forked, of course they cannot.
1084 * For example, 'unset foo | whatever' will parse and run, but foo will
1085 * still be set at the end. */
1086struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001087 const char *b_cmd;
1088 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001090 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001091# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001093# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001094#endif
1095};
1096
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001097static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001098 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001099 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001100#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001101 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001102#endif
1103#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001104 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001109#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001110 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1111 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001112 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001113#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001114 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001115#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001117 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001119#if ENABLE_HUSH_GETOPTS
1120 BLTIN("getopts" , builtin_getopts , NULL),
1121#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001123 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001125#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001126 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001127#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001128#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001129 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001130#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001131#if ENABLE_HUSH_KILL
1132 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1133#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001134#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001136#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001137#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001139#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001140#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001141 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001142#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001143#if ENABLE_HUSH_READONLY
1144 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1145#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001146#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001148#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001149#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001150 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001151#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001153#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001154 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001155#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001156#if ENABLE_HUSH_TIMES
1157 BLTIN("times" , builtin_times , NULL),
1158#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001159#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001160 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001161#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001162 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001163#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001164 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001165#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001166#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001167 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001168#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001169#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001171#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001172#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001174#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001175#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001176 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001178};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001179/* These builtins won't be used if we are on NOMMU and need to re-exec
1180 * (it's cheaper to run an external program in this case):
1181 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001183#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001185#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001186#if BASH_TEST2
1187 BLTIN("[[" , builtin_test , NULL),
1188#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001189#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001190 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001191#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001192#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001193 BLTIN("printf" , builtin_printf , NULL),
1194#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001195 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001196#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001197 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001198#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001199};
1200
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001201
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001202/* Debug printouts.
1203 */
1204#if HUSH_DEBUG
1205/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001206# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001207# define debug_enter() (G.debug_indent++)
1208# define debug_leave() (G.debug_indent--)
1209#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001210# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001211# define debug_enter() ((void)0)
1212# define debug_leave() ((void)0)
1213#endif
1214
1215#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001216# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001217#endif
1218
1219#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001220# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001221#endif
1222
Denys Vlasenko3675c372018-07-23 16:31:21 +02001223#ifndef debug_printf_heredoc
1224# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1225#endif
1226
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001227#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001228#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001229#endif
1230
1231#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001232# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001233#endif
1234
1235#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001236# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237# define DEBUG_JOBS 1
1238#else
1239# define DEBUG_JOBS 0
1240#endif
1241
1242#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001243# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001244# define DEBUG_EXPAND 1
1245#else
1246# define DEBUG_EXPAND 0
1247#endif
1248
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001249#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001251#endif
1252
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001254# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001255# define DEBUG_GLOB 1
1256#else
1257# define DEBUG_GLOB 0
1258#endif
1259
Denys Vlasenko2db74612017-07-07 22:07:28 +02001260#ifndef debug_printf_redir
1261# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1262#endif
1263
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266#endif
1267
1268#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001269# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001270#endif
1271
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001272#ifndef debug_printf_prompt
1273# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1274#endif
1275
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001277# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001278# define DEBUG_CLEAN 1
1279#else
1280# define DEBUG_CLEAN 0
1281#endif
1282
1283#if DEBUG_EXPAND
1284static void debug_print_strings(const char *prefix, char **vv)
1285{
1286 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001287 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001288 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001289 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290}
1291#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001292# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001293#endif
1294
1295
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001296/* Leak hunting. Use hush_leaktool.sh for post-processing.
1297 */
1298#if LEAK_HUNTING
1299static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001300{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001301 void *ptr = xmalloc((size + 0xff) & ~0xff);
1302 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1303 return ptr;
1304}
1305static void *xxrealloc(int lineno, void *ptr, size_t size)
1306{
1307 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1308 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1309 return ptr;
1310}
1311static char *xxstrdup(int lineno, const char *str)
1312{
1313 char *ptr = xstrdup(str);
1314 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1315 return ptr;
1316}
1317static void xxfree(void *ptr)
1318{
1319 fdprintf(2, "free %p\n", ptr);
1320 free(ptr);
1321}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001322# define xmalloc(s) xxmalloc(__LINE__, s)
1323# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1324# define xstrdup(s) xxstrdup(__LINE__, s)
1325# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001326#endif
1327
1328
1329/* Syntax and runtime errors. They always abort scripts.
1330 * In interactive use they usually discard unparsed and/or unexecuted commands
1331 * and return to the prompt.
1332 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1333 */
1334#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001335# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001336# define syntax_error(lineno, msg) syntax_error(msg)
1337# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1338# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1339# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1340# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001341#endif
1342
Denys Vlasenko39701202017-08-02 19:44:05 +02001343static void die_if_script(void)
1344{
1345 if (!G_interactive_fd) {
1346 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1347 xfunc_error_retval = G.last_exitcode;
1348 xfunc_die();
1349 }
1350}
1351
1352static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001353{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001354 va_list p;
1355
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001356#if HUSH_DEBUG >= 2
1357 bb_error_msg("hush.c:%u", lineno);
1358#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001359 va_start(p, fmt);
1360 bb_verror_msg(fmt, p, NULL);
1361 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001362 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001363}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001364
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001365static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001366{
1367 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001368 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001369 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001370 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001371 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372}
1373
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001374static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001375{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001376 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001377 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001378}
1379
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001380static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001381{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001382 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001383//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1384// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001385}
1386
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001387static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001389 char msg[2] = { ch, '\0' };
1390 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001391}
1392
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001393static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001394{
1395 char msg[2];
1396 msg[0] = ch;
1397 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001398#if HUSH_DEBUG >= 2
1399 bb_error_msg("hush.c:%u", lineno);
1400#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001401 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001402 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001403}
1404
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001405#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001406# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001407# undef syntax_error
1408# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001409# undef syntax_error_unterm_ch
1410# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001411# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001412#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001413# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001414# define syntax_error(msg) syntax_error(__LINE__, msg)
1415# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1416# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1417# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1418# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001419#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001420
Denis Vlasenko552433b2009-04-04 19:29:21 +00001421
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001422#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001423static void cmdedit_update_prompt(void);
1424#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001425# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001426#endif
1427
1428
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001429/* Utility functions
1430 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001431/* Replace each \x with x in place, return ptr past NUL. */
1432static char *unbackslash(char *src)
1433{
Denys Vlasenko71885402009-09-24 01:44:13 +02001434 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001435 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001436 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001437 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001438 if (*src != '\0') {
1439 /* \x -> x */
1440 *dst++ = *src++;
1441 continue;
1442 }
1443 /* else: "\<nul>". Do not delete this backslash.
1444 * Testcase: eval 'echo ok\'
1445 */
1446 *dst++ = '\\';
1447 /* fallthrough */
1448 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001449 if ((*dst++ = *src++) == '\0')
1450 break;
1451 }
1452 return dst;
1453}
1454
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001455static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001456{
1457 int i;
1458 unsigned count1;
1459 unsigned count2;
1460 char **v;
1461
1462 v = strings;
1463 count1 = 0;
1464 if (v) {
1465 while (*v) {
1466 count1++;
1467 v++;
1468 }
1469 }
1470 count2 = 0;
1471 v = add;
1472 while (*v) {
1473 count2++;
1474 v++;
1475 }
1476 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1477 v[count1 + count2] = NULL;
1478 i = count2;
1479 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001480 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001481 return v;
1482}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001483#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001484static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1485{
1486 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1487 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1488 return ptr;
1489}
1490#define add_strings_to_strings(strings, add, need_to_dup) \
1491 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1492#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001493
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001494/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001495static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001496{
1497 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001498 v[0] = add;
1499 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001500 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001501}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001502#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001503static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1504{
1505 char **ptr = add_string_to_strings(strings, add);
1506 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1507 return ptr;
1508}
1509#define add_string_to_strings(strings, add) \
1510 xx_add_string_to_strings(__LINE__, strings, add)
1511#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001512
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001513static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001514{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001515 char **v;
1516
1517 if (!strings)
1518 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001519 v = strings;
1520 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001521 free(*v);
1522 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001523 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001524 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001525}
1526
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001527static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001528{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001529 int newfd;
1530 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001531 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1532 if (newfd >= 0) {
1533 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1534 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1535 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001536 if (errno == EBUSY)
1537 goto repeat;
1538 if (errno == EINTR)
1539 goto repeat;
1540 }
1541 return newfd;
1542}
1543
Denys Vlasenko657e9002017-07-30 23:34:04 +02001544static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001545{
1546 int newfd;
1547 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001548 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001549 if (newfd < 0) {
1550 if (errno == EBUSY)
1551 goto repeat;
1552 if (errno == EINTR)
1553 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001554 /* fd was not open? */
1555 if (errno == EBADF)
1556 return fd;
1557 xfunc_die();
1558 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001559 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1560 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001561 close(fd);
1562 return newfd;
1563}
1564
1565
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001566/* Manipulating the list of open FILEs */
1567static FILE *remember_FILE(FILE *fp)
1568{
1569 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001570 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001571 n->next = G.FILE_list;
1572 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001573 n->fp = fp;
1574 n->fd = fileno(fp);
1575 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001576 }
1577 return fp;
1578}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001579static void fclose_and_forget(FILE *fp)
1580{
1581 struct FILE_list **pp = &G.FILE_list;
1582 while (*pp) {
1583 struct FILE_list *cur = *pp;
1584 if (cur->fp == fp) {
1585 *pp = cur->next;
1586 free(cur);
1587 break;
1588 }
1589 pp = &cur->next;
1590 }
1591 fclose(fp);
1592}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001593static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001594{
1595 struct FILE_list *fl = G.FILE_list;
1596 while (fl) {
1597 if (fd == fl->fd) {
1598 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001599 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001600 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001601 return 1;
1602 }
1603 fl = fl->next;
1604 }
1605 return 0;
1606}
1607static void restore_redirected_FILEs(void)
1608{
1609 struct FILE_list *fl = G.FILE_list;
1610 while (fl) {
1611 int should_be = fileno(fl->fp);
1612 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001613 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001614 xmove_fd(fl->fd, should_be);
1615 fl->fd = should_be;
1616 }
1617 fl = fl->next;
1618 }
1619}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001620#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001621static void close_all_FILE_list(void)
1622{
1623 struct FILE_list *fl = G.FILE_list;
1624 while (fl) {
1625 /* fclose would also free FILE object.
1626 * It is disastrous if we share memory with a vforked parent.
1627 * I'm not sure we never come here after vfork.
1628 * Therefore just close fd, nothing more.
1629 */
1630 /*fclose(fl->fp); - unsafe */
1631 close(fl->fd);
1632 fl = fl->next;
1633 }
1634}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001635#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001636static int fd_in_FILEs(int fd)
1637{
1638 struct FILE_list *fl = G.FILE_list;
1639 while (fl) {
1640 if (fl->fd == fd)
1641 return 1;
1642 fl = fl->next;
1643 }
1644 return 0;
1645}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001646
1647
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001648/* Helpers for setting new $n and restoring them back
1649 */
1650typedef struct save_arg_t {
1651 char *sv_argv0;
1652 char **sv_g_argv;
1653 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001654 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001655} save_arg_t;
1656
1657static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1658{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001659 sv->sv_argv0 = argv[0];
1660 sv->sv_g_argv = G.global_argv;
1661 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001662 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001663
1664 argv[0] = G.global_argv[0]; /* retain $0 */
1665 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001666 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001667
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001668 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001669}
1670
1671static void restore_G_args(save_arg_t *sv, char **argv)
1672{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001673#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001674 if (G.global_args_malloced) {
1675 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001676 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001677 while (*++pp) /* note: does not free $0 */
1678 free(*pp);
1679 free(G.global_argv);
1680 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001681#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001682 argv[0] = sv->sv_argv0;
1683 G.global_argv = sv->sv_g_argv;
1684 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001685 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001686}
1687
1688
Denis Vlasenkod5762932009-03-31 11:22:57 +00001689/* Basic theory of signal handling in shell
1690 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001691 * This does not describe what hush does, rather, it is current understanding
1692 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001693 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1694 *
1695 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1696 * is finished or backgrounded. It is the same in interactive and
1697 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001698 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001699 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001700 * backgrounds (i.e. stops) or kills all members of currently running
1701 * pipe.
1702 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001703 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001704 * or by SIGINT in interactive shell.
1705 *
1706 * Trap handlers will execute even within trap handlers. (right?)
1707 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001708 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1709 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001710 *
1711 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001712 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001713 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001714 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001715 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001716 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001717 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001718 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001719 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001720 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001721 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 *
1723 * SIGQUIT: ignore
1724 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001725 * SIGHUP (interactive):
1726 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001727 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001728 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1729 * that all pipe members are stopped. Try this in bash:
1730 * while :; do :; done - ^Z does not background it
1731 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001732 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001733 * of the command line, show prompt. NB: ^C does not send SIGINT
1734 * to interactive shell while shell is waiting for a pipe,
1735 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001736 * Example 1: this waits 5 sec, but does not execute ls:
1737 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1738 * Example 2: this does not wait and does not execute ls:
1739 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1740 * Example 3: this does not wait 5 sec, but executes ls:
1741 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001742 * Example 4: this does not wait and does not execute ls:
1743 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001744 *
1745 * (What happens to signals which are IGN on shell start?)
1746 * (What happens with signal mask on shell start?)
1747 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001748 * Old implementation
1749 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001750 * We use in-kernel pending signal mask to determine which signals were sent.
1751 * We block all signals which we don't want to take action immediately,
1752 * i.e. we block all signals which need to have special handling as described
1753 * above, and all signals which have traps set.
1754 * After each pipe execution, we extract any pending signals via sigtimedwait()
1755 * and act on them.
1756 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001757 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001758 * sigset_t blocked_set: current blocked signal set
1759 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001760 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001761 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001762 * "trap 'cmd' SIGxxx":
1763 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001764 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001765 * unblock signals with special interactive handling
1766 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001767 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001768 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001769 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001770 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001771 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001772 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001773 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001774 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001775 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001776 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001777 * Standard says "When a subshell is entered, traps that are not being ignored
1778 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001779 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001780 *
1781 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001782 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001783 * masked signals are not visible!
1784 *
1785 * New implementation
1786 * ==================
1787 * We record each signal we are interested in by installing signal handler
1788 * for them - a bit like emulating kernel pending signal mask in userspace.
1789 * We are interested in: signals which need to have special handling
1790 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001791 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001792 * After each pipe execution, we extract any pending signals
1793 * and act on them.
1794 *
1795 * unsigned special_sig_mask: a mask of shell-special signals.
1796 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1797 * char *traps[sig] if trap for sig is set (even if it's '').
1798 * sigset_t pending_set: set of sigs we received.
1799 *
1800 * "trap - SIGxxx":
1801 * if sig is in special_sig_mask, set handler back to:
1802 * record_pending_signo, or to IGN if it's a tty stop signal
1803 * if sig is in fatal_sig_mask, set handler back to sigexit.
1804 * else: set handler back to SIG_DFL
1805 * "trap 'cmd' SIGxxx":
1806 * set handler to record_pending_signo.
1807 * "trap '' SIGxxx":
1808 * set handler to SIG_IGN.
1809 * after [v]fork, if we plan to be a shell:
1810 * set signals with special interactive handling to SIG_DFL
1811 * (because child shell is not interactive),
1812 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1813 * after [v]fork, if we plan to exec:
1814 * POSIX says fork clears pending signal mask in child - no need to clear it.
1815 *
1816 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1817 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1818 *
1819 * Note (compat):
1820 * Standard says "When a subshell is entered, traps that are not being ignored
1821 * are set to the default actions". bash interprets it so that traps which
1822 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001823 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001824enum {
1825 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001826 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001827 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001828 | (1 << SIGHUP)
1829 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001830 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001831#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001832 | (1 << SIGTTIN)
1833 | (1 << SIGTTOU)
1834 | (1 << SIGTSTP)
1835#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001836 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001837};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001838
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001839static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001840{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001841 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001842#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001843 if (sig == SIGCHLD) {
1844 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001845//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 +02001846 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001847#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001848}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001849
Denys Vlasenko0806e402011-05-12 23:06:20 +02001850static sighandler_t install_sighandler(int sig, sighandler_t handler)
1851{
1852 struct sigaction old_sa;
1853
1854 /* We could use signal() to install handlers... almost:
1855 * except that we need to mask ALL signals while handlers run.
1856 * I saw signal nesting in strace, race window isn't small.
1857 * SA_RESTART is also needed, but in Linux, signal()
1858 * sets SA_RESTART too.
1859 */
1860 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1861 /* sigfillset(&G.sa.sa_mask); - already done */
1862 /* G.sa.sa_flags = SA_RESTART; - already done */
1863 G.sa.sa_handler = handler;
1864 sigaction(sig, &G.sa, &old_sa);
1865 return old_sa.sa_handler;
1866}
1867
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001868static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001869
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001870static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001871static void restore_ttypgrp_and__exit(void)
1872{
1873 /* xfunc has failed! die die die */
1874 /* no EXIT traps, this is an escape hatch! */
1875 G.exiting = 1;
1876 hush_exit(xfunc_error_retval);
1877}
1878
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001879#if ENABLE_HUSH_JOB
1880
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001881/* Needed only on some libc:
1882 * It was observed that on exit(), fgetc'ed buffered data
1883 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1884 * With the net effect that even after fork(), not vfork(),
1885 * exit() in NOEXECed applet in "sh SCRIPT":
1886 * noexec_applet_here
1887 * echo END_OF_SCRIPT
1888 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1889 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001890 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001891 * and in `cmd` handling.
1892 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1893 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001894static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001895static void fflush_and__exit(void)
1896{
1897 fflush_all();
1898 _exit(xfunc_error_retval);
1899}
1900
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001901/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001902# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001903/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001904# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001905
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001906/* Restores tty foreground process group, and exits.
1907 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001908 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001909 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001910 * We also call it if xfunc is exiting.
1911 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001912static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001913static void sigexit(int sig)
1914{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001915 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001916 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001917 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1918 /* Disable all signals: job control, SIGPIPE, etc.
1919 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1920 */
1921 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001922 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001923 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001924
1925 /* Not a signal, just exit */
1926 if (sig <= 0)
1927 _exit(- sig);
1928
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001929 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001930}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001931#else
1932
Denys Vlasenko8391c482010-05-22 17:50:43 +02001933# define disable_restore_tty_pgrp_on_exit() ((void)0)
1934# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001935
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001936#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001937
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001938static sighandler_t pick_sighandler(unsigned sig)
1939{
1940 sighandler_t handler = SIG_DFL;
1941 if (sig < sizeof(unsigned)*8) {
1942 unsigned sigmask = (1 << sig);
1943
1944#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001945 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001946 if (G_fatal_sig_mask & sigmask)
1947 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001948 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001949#endif
1950 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001951 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001952 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001953 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001954 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001955 * in an endless loop when we try to do some
1956 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001957 */
1958 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1959 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001960 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001961 }
1962 return handler;
1963}
1964
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001965/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001966static void hush_exit(int exitcode)
1967{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001968#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1969 save_history(G.line_input_state);
1970#endif
1971
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001972 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001973 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001974 char *argv[3];
1975 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001976 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001977 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001978 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001979 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001980 * "trap" will still show it, if executed
1981 * in the handler */
1982 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001983 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001984
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001985#if ENABLE_FEATURE_CLEAN_UP
1986 {
1987 struct variable *cur_var;
1988 if (G.cwd != bb_msg_unknown)
1989 free((char*)G.cwd);
1990 cur_var = G.top_var;
1991 while (cur_var) {
1992 struct variable *tmp = cur_var;
1993 if (!cur_var->max_len)
1994 free(cur_var->varstr);
1995 cur_var = cur_var->next;
1996 free(tmp);
1997 }
1998 }
1999#endif
2000
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002001 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002002#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002003 sigexit(- (exitcode & 0xff));
2004#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002005 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002006#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002007}
2008
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002009
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002010//TODO: return a mask of ALL handled sigs?
2011static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002012{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002013 int last_sig = 0;
2014
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002015 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002016 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002017
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002018 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002019 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002020 sig = 0;
2021 do {
2022 sig++;
2023 if (sigismember(&G.pending_set, sig)) {
2024 sigdelset(&G.pending_set, sig);
2025 goto got_sig;
2026 }
2027 } while (sig < NSIG);
2028 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002029 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002030 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002031 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002032 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002033 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002034 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002035 char *argv[3];
2036 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002037 argv[1] = xstrdup(G_traps[sig]);
2038 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002039 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002040 save_rcode = G.last_exitcode;
2041 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002042 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002043//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002044 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002045 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002046 } /* else: "" trap, ignoring signal */
2047 continue;
2048 }
2049 /* not a trap: special action */
2050 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002051 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002052 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002053 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002054 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002055 break;
2056#if ENABLE_HUSH_JOB
2057 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002058//TODO: why are we doing this? ash and dash don't do this,
2059//they have no handler for SIGHUP at all,
2060//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002061 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002062 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002063 /* bash is observed to signal whole process groups,
2064 * not individual processes */
2065 for (job = G.job_list; job; job = job->next) {
2066 if (job->pgrp <= 0)
2067 continue;
2068 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2069 if (kill(- job->pgrp, SIGHUP) == 0)
2070 kill(- job->pgrp, SIGCONT);
2071 }
2072 sigexit(SIGHUP);
2073 }
2074#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002075#if ENABLE_HUSH_FAST
2076 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002077 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002078 G.count_SIGCHLD++;
2079//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2080 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002081 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002082 * This simplifies wait builtin a bit.
2083 */
2084 break;
2085#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002086 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002087 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002088 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002089 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002090 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002091 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002092 * in interactive shell, because TERM is ignored.
2093 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002094 break;
2095 }
2096 }
2097 return last_sig;
2098}
2099
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002100
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002101static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002102{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002103 if (force || G.cwd == NULL) {
2104 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2105 * we must not try to free(bb_msg_unknown) */
2106 if (G.cwd == bb_msg_unknown)
2107 G.cwd = NULL;
2108 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2109 if (!G.cwd)
2110 G.cwd = bb_msg_unknown;
2111 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002112 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002113}
2114
Denis Vlasenko83506862007-11-23 13:11:42 +00002115
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002116/*
2117 * Shell and environment variable support
2118 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002119static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002120{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002121 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002124 pp = &G.top_var;
2125 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002127 return pp;
2128 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 }
2130 return NULL;
2131}
2132
Denys Vlasenko03dad222010-01-12 23:29:57 +01002133static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002134{
Denys Vlasenko29082232010-07-16 13:52:32 +02002135 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002136 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002137
2138 if (G.expanded_assignments) {
2139 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002140 while (*cpp) {
2141 char *cp = *cpp;
2142 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2143 return cp + len + 1;
2144 cpp++;
2145 }
2146 }
2147
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002148 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002149 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002150 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002151
Denys Vlasenkodea47882009-10-09 15:40:49 +02002152 if (strcmp(name, "PPID") == 0)
2153 return utoa(G.root_ppid);
2154 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002155#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002156 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002157 return utoa(next_random(&G.random_gen));
2158#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159 return NULL;
2160}
2161
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002162static void handle_changed_special_names(const char *name, unsigned name_len)
2163{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002164 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2165 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2166 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002167 cmdedit_update_prompt();
2168 return;
2169 }
2170
2171 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2172 && name_len == 6
2173 ) {
2174#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002175 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002176 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002177 return;
2178 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002179#endif
2180#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002181 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002182 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002183 return;
2184 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002185#endif
2186 }
2187}
2188
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002189/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002190 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002191 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002192#define SETFLAG_EXPORT (1 << 0)
2193#define SETFLAG_UNEXPORT (1 << 1)
2194#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002195#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002196static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197{
Denys Vlasenko61407802018-04-04 21:14:28 +02002198 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002200 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002201 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002203 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002204
Denis Vlasenko950bd722009-04-21 11:23:56 +00002205 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002206 if (HUSH_DEBUG && !eq_sign)
2207 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002208
Denis Vlasenko950bd722009-04-21 11:23:56 +00002209 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002210 cur_pp = &G.top_var;
2211 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002213 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002214 continue;
2215 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002216
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002217 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002218 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002219 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002220 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002221//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2222//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 return -1;
2224 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002225 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002226 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2227 *eq_sign = '\0';
2228 unsetenv(str);
2229 *eq_sign = '=';
2230 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002231 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002232 /* bash 3.2.33(1) and exported vars:
2233 * # export z=z
2234 * # f() { local z=a; env | grep ^z; }
2235 * # f
2236 * z=a
2237 * # env | grep ^z
2238 * z=z
2239 */
2240 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002241 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002242 /* New variable is local ("local VAR=VAL" or
2243 * "VAR=VAL cmd")
2244 * and existing one is global, or local
2245 * on a lower level that new one.
2246 * Remove it from global variable list:
2247 */
2248 *cur_pp = cur->next;
2249 if (G.shadowed_vars_pp) {
2250 /* Save in "shadowed" list */
2251 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2252 cur->flg_export ? "exported " : "",
2253 cur->varstr, cur->var_nest_level, str, local_lvl
2254 );
2255 cur->next = *G.shadowed_vars_pp;
2256 *G.shadowed_vars_pp = cur;
2257 } else {
2258 /* Came from pseudo_exec_argv(), no need to save: delete it */
2259 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2260 cur->flg_export ? "exported " : "",
2261 cur->varstr, cur->var_nest_level, str, local_lvl
2262 );
2263 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2264 free_me = cur->varstr; /* then free it later */
2265 free(cur);
2266 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002267 break;
2268 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002269
Denis Vlasenko950bd722009-04-21 11:23:56 +00002270 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002271 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002272 free_and_exp:
2273 free(str);
2274 goto exp;
2275 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002276
2277 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002278 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002279 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002280 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002281 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002282 strcpy(cur->varstr, str);
2283 goto free_and_exp;
2284 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002285 /* Can't reuse */
2286 cur->max_len = 0;
2287 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002288 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002289 /* max_len == 0 signifies "malloced" var, which we can
2290 * (and have to) free. But we can't free(cur->varstr) here:
2291 * if cur->flg_export is 1, it is in the environment.
2292 * We should either unsetenv+free, or wait until putenv,
2293 * then putenv(new)+free(old).
2294 */
2295 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002296 goto set_str_and_exp;
2297 }
2298
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002299 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002300 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002301 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002302 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002303 cur->next = *cur_pp;
2304 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002305
2306 set_str_and_exp:
2307 cur->varstr = str;
2308 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002309#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002310 if (flags & SETFLAG_MAKE_RO) {
2311 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002312 }
2313#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002314 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 cur->flg_export = 1;
2316 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002317 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002318 cur->flg_export = 0;
2319 /* unsetenv was already done */
2320 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002321 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002322 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002323 i = putenv(cur->varstr);
2324 /* only now we can free old exported malloced string */
2325 free(free_me);
2326 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002327 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002329 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002330
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002331 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002332
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002333 return 0;
2334}
2335
Denys Vlasenko6db47842009-09-05 20:15:17 +02002336/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002337static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002338{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002339 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002340}
2341
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002342#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002343static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002344{
2345 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002346 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002347
Denys Vlasenko61407802018-04-04 21:14:28 +02002348 cur_pp = &G.top_var;
2349 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002350 if (strncmp(cur->varstr, name, name_len) == 0
2351 && cur->varstr[name_len] == '='
2352 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002353 if (cur->flg_read_only) {
2354 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002355 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002356 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002357
Denys Vlasenko61407802018-04-04 21:14:28 +02002358 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002359 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2360 bb_unsetenv(cur->varstr);
2361 if (!cur->max_len)
2362 free(cur->varstr);
2363 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002364
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002365 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002366 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002367 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002368 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002369
2370 /* Handle "unset PS1" et al even if did not find the variable to unset */
2371 handle_changed_special_names(name, name_len);
2372
Mike Frysingerd690f682009-03-30 06:50:54 +00002373 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002374}
2375
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002376static int unset_local_var(const char *name)
2377{
2378 return unset_local_var_len(name, strlen(name));
2379}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002380#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002381
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002382#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2383 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002384static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002385{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002386 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002387 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002388}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002389#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002390
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002391
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002392/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002393 * Helpers for "var1=val1 var2=val2 cmd" feature
2394 */
2395static void add_vars(struct variable *var)
2396{
2397 struct variable *next;
2398
2399 while (var) {
2400 next = var->next;
2401 var->next = G.top_var;
2402 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002403 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002404 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002405 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002406 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002407 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002408 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002409 var = next;
2410 }
2411}
2412
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002413/* We put strings[i] into variable table and possibly putenv them.
2414 * If variable is read only, we can free the strings[i]
2415 * which attempts to overwrite it.
2416 * The strings[] vector itself is freed.
2417 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002418static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002419{
2420 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002421
2422 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002423 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002424
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002425 s = strings;
2426 while (*s) {
2427 struct variable *var_p;
2428 struct variable **var_pp;
2429 char *eq;
2430
2431 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002432 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002433 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002434 var_pp = get_ptr_to_local_var(*s, eq - *s);
2435 if (var_pp) {
2436 var_p = *var_pp;
2437 if (var_p->flg_read_only) {
2438 char **p;
2439 bb_error_msg("%s: readonly variable", *s);
2440 /*
2441 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2442 * If VAR is readonly, leaving it in the list
2443 * after asssignment error (msg above)
2444 * causes doubled error message later, on unset.
2445 */
2446 debug_printf_env("removing/freeing '%s' element\n", *s);
2447 free(*s);
2448 p = s;
2449 do { *p = p[1]; p++; } while (*p);
2450 goto next;
2451 }
2452 /* below, set_local_var() with nest level will
2453 * "shadow" (remove) this variable from
2454 * global linked list.
2455 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002456 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002457 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2458 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002459 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002460 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002461 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002462 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002463}
2464
2465
2466/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002467 * Unicode helper
2468 */
2469static void reinit_unicode_for_hush(void)
2470{
2471 /* Unicode support should be activated even if LANG is set
2472 * _during_ shell execution, not only if it was set when
2473 * shell was started. Therefore, re-check LANG every time:
2474 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002475 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2476 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002477 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002478 const char *s = get_local_var_value("LC_ALL");
2479 if (!s) s = get_local_var_value("LC_CTYPE");
2480 if (!s) s = get_local_var_value("LANG");
2481 reinit_unicode(s);
2482 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002483}
2484
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002485/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002486 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002487 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488
2489#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002490/* To test correct lineedit/interactive behavior, type from command line:
2491 * echo $P\
2492 * \
2493 * AT\
2494 * H\
2495 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002496 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002497 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002498# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002499static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002500{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002501 G.PS1 = get_local_var_value("PS1");
2502 if (G.PS1 == NULL)
2503 G.PS1 = "";
2504 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002505 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002506 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002508# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002509static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002510{
2511 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002512
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002513 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002514
2515 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2516 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002517 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002518 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2519 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002520 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002521 /* bash uses $PWD value, even if it is set by user.
2522 * It uses current dir only if PWD is unset.
2523 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002524 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002525 }
2526 prompt_str = G.PS1;
2527 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002528 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002529 return prompt_str;
2530}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002531static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002532{
2533 int r;
2534 const char *prompt_str;
2535
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002536 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002537# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002538 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002539 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002540 if (G.flag_SIGINT) {
2541 /* There was ^C'ed, make it look prettier: */
2542 bb_putchar('\n');
2543 G.flag_SIGINT = 0;
2544 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002545 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002546 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002547 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002548 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002549 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002550 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002551 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002552 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002553 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002554 if (r != 0 && !G.flag_SIGINT)
2555 break;
2556 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002557 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2558 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002559 G.last_exitcode = 128 + SIGINT;
2560 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002561 if (r < 0) {
2562 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002563 i->p = NULL;
2564 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002565 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002566 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002567 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002568 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002569# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002570 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002571 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002572 if (i->last_char == '\0' || i->last_char == '\n') {
2573 /* Why check_and_run_traps here? Try this interactively:
2574 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2575 * $ <[enter], repeatedly...>
2576 * Without check_and_run_traps, handler never runs.
2577 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002578 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002579 fputs(prompt_str, stdout);
2580 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002581 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002582//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002583 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002584 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2585 * no ^C masking happens during fgetc, no special code for ^C:
2586 * it generates SIGINT as usual.
2587 */
2588 check_and_run_traps();
2589 if (G.flag_SIGINT)
2590 G.last_exitcode = 128 + SIGINT;
2591 if (r != '\0')
2592 break;
2593 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002594 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002595# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002596}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002597/* This is the magic location that prints prompts
2598 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002599static int fgetc_interactive(struct in_str *i)
2600{
2601 int ch;
2602 /* If it's interactive stdin, get new line. */
2603 if (G_interactive_fd && i->file == stdin) {
2604 /* Returns first char (or EOF), the rest is in i->p[] */
2605 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002606 G.promptmode = 1; /* PS2 */
2607 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002608 } else {
2609 /* Not stdin: script file, sourced file, etc */
2610 do ch = fgetc(i->file); while (ch == '\0');
2611 }
2612 return ch;
2613}
2614#else
2615static inline int fgetc_interactive(struct in_str *i)
2616{
2617 int ch;
2618 do ch = fgetc(i->file); while (ch == '\0');
2619 return ch;
2620}
2621#endif /* INTERACTIVE */
2622
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002623static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002624{
2625 int ch;
2626
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002627 if (!i->file) {
2628 /* string-based in_str */
2629 ch = (unsigned char)*i->p;
2630 if (ch != '\0') {
2631 i->p++;
2632 i->last_char = ch;
2633 return ch;
2634 }
2635 return EOF;
2636 }
2637
2638 /* FILE-based in_str */
2639
Denys Vlasenko4074d492016-09-30 01:49:53 +02002640#if ENABLE_FEATURE_EDITING
2641 /* This can be stdin, check line editing char[] buffer */
2642 if (i->p && *i->p != '\0') {
2643 ch = (unsigned char)*i->p++;
2644 goto out;
2645 }
2646#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002647 /* peek_buf[] is an int array, not char. Can contain EOF. */
2648 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002649 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002650 int ch2 = i->peek_buf[1];
2651 i->peek_buf[0] = ch2;
2652 if (ch2 == 0) /* very likely, avoid redundant write */
2653 goto out;
2654 i->peek_buf[1] = 0;
2655 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002656 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002657
Denys Vlasenko4074d492016-09-30 01:49:53 +02002658 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002659 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002660 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002661 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002662#if ENABLE_HUSH_LINENO_VAR
2663 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002664 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002665 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2666 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002667#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668 return ch;
2669}
2670
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002671static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002672{
2673 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002674
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002675 if (!i->file) {
2676 /* string-based in_str */
2677 /* Doesn't report EOF on NUL. None of the callers care. */
2678 return (unsigned char)*i->p;
2679 }
2680
2681 /* FILE-based in_str */
2682
Denys Vlasenko4074d492016-09-30 01:49:53 +02002683#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002684 /* This can be stdin, check line editing char[] buffer */
2685 if (i->p && *i->p != '\0')
2686 return (unsigned char)*i->p;
2687#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002688 /* peek_buf[] is an int array, not char. Can contain EOF. */
2689 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002690 if (ch != 0)
2691 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002692
Denys Vlasenko4074d492016-09-30 01:49:53 +02002693 /* Need to get a new char */
2694 ch = fgetc_interactive(i);
2695 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2696
2697 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2698#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2699 if (i->p) {
2700 i->p -= 1;
2701 return ch;
2702 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002703#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002704 i->peek_buf[0] = ch;
2705 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002706 return ch;
2707}
2708
Denys Vlasenko4074d492016-09-30 01:49:53 +02002709/* Only ever called if i_peek() was called, and did not return EOF.
2710 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2711 * not end-of-line. Therefore we never need to read a new editing line here.
2712 */
2713static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002714{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002715 int ch;
2716
2717 /* There are two cases when i->p[] buffer exists.
2718 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002719 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002720 * In both cases, we know that i->p[0] exists and not NUL, and
2721 * the peek2 result is in i->p[1].
2722 */
2723 if (i->p)
2724 return (unsigned char)i->p[1];
2725
2726 /* Now we know it is a file-based in_str. */
2727
2728 /* peek_buf[] is an int array, not char. Can contain EOF. */
2729 /* Is there 2nd char? */
2730 ch = i->peek_buf[1];
2731 if (ch == 0) {
2732 /* We did not read it yet, get it now */
2733 do ch = fgetc(i->file); while (ch == '\0');
2734 i->peek_buf[1] = ch;
2735 }
2736
2737 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2738 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002739}
2740
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002741static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2742{
2743 for (;;) {
2744 int ch, ch2;
2745
2746 ch = i_getch(input);
2747 if (ch != '\\')
2748 return ch;
2749 ch2 = i_peek(input);
2750 if (ch2 != '\n')
2751 return ch;
2752 /* backslash+newline, skip it */
2753 i_getch(input);
2754 }
2755}
2756
2757/* Note: this function _eats_ \<newline> pairs, safe to use plain
2758 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2759 */
2760static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2761{
2762 for (;;) {
2763 int ch, ch2;
2764
2765 ch = i_peek(input);
2766 if (ch != '\\')
2767 return ch;
2768 ch2 = i_peek2(input);
2769 if (ch2 != '\n')
2770 return ch;
2771 /* backslash+newline, skip it */
2772 i_getch(input);
2773 i_getch(input);
2774 }
2775}
2776
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777static void setup_file_in_str(struct in_str *i, FILE *f)
2778{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002779 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002780 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002781 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782}
2783
2784static void setup_string_in_str(struct in_str *i, const char *s)
2785{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002786 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002787 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789}
2790
2791
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002792/*
2793 * o_string support
2794 */
2795#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002796
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002797static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002798{
2799 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002800 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002801 if (o->data)
2802 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002803}
2804
Denys Vlasenko18567402018-07-20 17:51:31 +02002805static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002806{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002807 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002808 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002809}
2810
Denys Vlasenko18567402018-07-20 17:51:31 +02002811static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002812{
2813 free(o->data);
2814}
2815
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002816static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002817{
2818 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002819 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002820 o->data = xrealloc(o->data, 1 + o->maxlen);
2821 }
2822}
2823
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002824static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002825{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002826 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002827 if (o->length < o->maxlen) {
2828 /* likely. avoid o_grow_by() call */
2829 add:
2830 o->data[o->length] = ch;
2831 o->length++;
2832 o->data[o->length] = '\0';
2833 return;
2834 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002835 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002836 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002837}
2838
Denys Vlasenko657086a2016-09-29 18:07:42 +02002839#if 0
2840/* Valid only if we know o_string is not empty */
2841static void o_delchr(o_string *o)
2842{
2843 o->length--;
2844 o->data[o->length] = '\0';
2845}
2846#endif
2847
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002848static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002849{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002850 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002851 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002852 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002853}
2854
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002855static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002856{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002857 o_addblock(o, str, strlen(str));
2858}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002859
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002860#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002861static void nommu_addchr(o_string *o, int ch)
2862{
2863 if (o)
2864 o_addchr(o, ch);
2865}
2866#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002867# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002868#endif
2869
2870static void o_addstr_with_NUL(o_string *o, const char *str)
2871{
2872 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002873}
2874
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002875/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002876 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002877 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2878 * Apparently, on unquoted $v bash still does globbing
2879 * ("v='*.txt'; echo $v" prints all .txt files),
2880 * but NOT brace expansion! Thus, there should be TWO independent
2881 * quoting mechanisms on $v expansion side: one protects
2882 * $v from brace expansion, and other additionally protects "$v" against globbing.
2883 * We have only second one.
2884 */
2885
Denys Vlasenko9e800222010-10-03 14:28:04 +02002886#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002887# define MAYBE_BRACES "{}"
2888#else
2889# define MAYBE_BRACES ""
2890#endif
2891
Eric Andersen25f27032001-04-26 23:22:31 +00002892/* My analysis of quoting semantics tells me that state information
2893 * is associated with a destination, not a source.
2894 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002895static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002896{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002897 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002898 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002899 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002900 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002901 o_grow_by(o, sz);
2902 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002903 o->data[o->length] = '\\';
2904 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002905 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002906 o->data[o->length] = ch;
2907 o->length++;
2908 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002909}
2910
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002911static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002912{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002914 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2915 && strchr("*?[\\" MAYBE_BRACES, ch)
2916 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002917 sz++;
2918 o->data[o->length] = '\\';
2919 o->length++;
2920 }
2921 o_grow_by(o, sz);
2922 o->data[o->length] = ch;
2923 o->length++;
2924 o->data[o->length] = '\0';
2925}
2926
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002927static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002928{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002929 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002930 char ch;
2931 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002932 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002933 if (ordinary_cnt > len) /* paranoia */
2934 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002935 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002936 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002937 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002938 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002939 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002940
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002941 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002942 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002943 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002944 sz++;
2945 o->data[o->length] = '\\';
2946 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002947 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002948 o_grow_by(o, sz);
2949 o->data[o->length] = ch;
2950 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002951 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002952 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002953}
2954
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002955static void o_addQblock(o_string *o, const char *str, int len)
2956{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002957 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002958 o_addblock(o, str, len);
2959 return;
2960 }
2961 o_addqblock(o, str, len);
2962}
2963
Denys Vlasenko38292b62010-09-05 14:49:40 +02002964static void o_addQstr(o_string *o, const char *str)
2965{
2966 o_addQblock(o, str, strlen(str));
2967}
2968
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002969/* A special kind of o_string for $VAR and `cmd` expansion.
2970 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002971 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972 * list[i] contains an INDEX (int!) into this string data.
2973 * It means that if list[] needs to grow, data needs to be moved higher up
2974 * but list[i]'s need not be modified.
2975 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002976 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002977 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2978 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002979#if DEBUG_EXPAND || DEBUG_GLOB
2980static void debug_print_list(const char *prefix, o_string *o, int n)
2981{
2982 char **list = (char**)o->data;
2983 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2984 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002985
2986 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002987 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 +02002988 prefix, list, n, string_start, o->length, o->maxlen,
2989 !!(o->o_expflags & EXP_FLAG_GLOB),
2990 o->has_quoted_part,
2991 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002992 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002993 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002994 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2995 o->data + (int)(uintptr_t)list[i] + string_start,
2996 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002997 i++;
2998 }
2999 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003000 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003001 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003002 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003003 }
3004}
3005#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003006# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003007#endif
3008
3009/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3010 * in list[n] so that it points past last stored byte so far.
3011 * It returns n+1. */
3012static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003013{
3014 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003015 int string_start;
3016 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003017
3018 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003019 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3020 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003021 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003022 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003023 /* list[n] points to string_start, make space for 16 more pointers */
3024 o->maxlen += 0x10 * sizeof(list[0]);
3025 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003026 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003027 memmove(list + n + 0x10, list + n, string_len);
3028 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003029 } else {
3030 debug_printf_list("list[%d]=%d string_start=%d\n",
3031 n, string_len, string_start);
3032 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003033 } else {
3034 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003035 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3036 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003037 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3038 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003039 o->has_empty_slot = 0;
3040 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003041 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003042 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003043 return n + 1;
3044}
3045
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003046/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003047static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003048{
3049 char **list = (char**)o->data;
3050 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3051
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003052 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003053}
3054
Denys Vlasenko9e800222010-10-03 14:28:04 +02003055#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003056/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3057 * first, it processes even {a} (no commas), second,
3058 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003059 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003060 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003061
3062/* Helper */
3063static int glob_needed(const char *s)
3064{
3065 while (*s) {
3066 if (*s == '\\') {
3067 if (!s[1])
3068 return 0;
3069 s += 2;
3070 continue;
3071 }
3072 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3073 return 1;
3074 s++;
3075 }
3076 return 0;
3077}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003078/* Return pointer to next closing brace or to comma */
3079static const char *next_brace_sub(const char *cp)
3080{
3081 unsigned depth = 0;
3082 cp++;
3083 while (*cp != '\0') {
3084 if (*cp == '\\') {
3085 if (*++cp == '\0')
3086 break;
3087 cp++;
3088 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003089 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003090 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003091 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003092 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003093 depth++;
3094 }
3095
3096 return *cp != '\0' ? cp : NULL;
3097}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003098/* Recursive brace globber. Note: may garble pattern[]. */
3099static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003100{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103 const char *next;
3104 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003105 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003106 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003107
3108 debug_printf_glob("glob_brace('%s')\n", pattern);
3109
3110 begin = pattern;
3111 while (1) {
3112 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003113 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003114 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003115 /* Find the first sub-pattern and at the same time
3116 * find the rest after the closing brace */
3117 next = next_brace_sub(begin);
3118 if (next == NULL) {
3119 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003120 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003121 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003122 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003123 /* "{abc}" with no commas - illegal
3124 * brace expr, disregard and skip it */
3125 begin = next + 1;
3126 continue;
3127 }
3128 break;
3129 }
3130 if (*begin == '\\' && begin[1] != '\0')
3131 begin++;
3132 begin++;
3133 }
3134 debug_printf_glob("begin:%s\n", begin);
3135 debug_printf_glob("next:%s\n", next);
3136
3137 /* Now find the end of the whole brace expression */
3138 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003139 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003140 rest = next_brace_sub(rest);
3141 if (rest == NULL) {
3142 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003143 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003144 }
3145 debug_printf_glob("rest:%s\n", rest);
3146 }
3147 rest_len = strlen(++rest) + 1;
3148
3149 /* We are sure the brace expression is well-formed */
3150
3151 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003152 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003153
3154 /* We have a brace expression. BEGIN points to the opening {,
3155 * NEXT points past the terminator of the first element, and REST
3156 * points past the final }. We will accumulate result names from
3157 * recursive runs for each brace alternative in the buffer using
3158 * GLOB_APPEND. */
3159
3160 p = begin + 1;
3161 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003162 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003163 memcpy(
3164 mempcpy(
3165 mempcpy(new_pattern_buf,
3166 /* We know the prefix for all sub-patterns */
3167 pattern, begin - pattern),
3168 p, next - p),
3169 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003170
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003171 /* Note: glob_brace() may garble new_pattern_buf[].
3172 * That's why we re-copy prefix every time (1st memcpy above).
3173 */
3174 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003175 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003176 /* We saw the last entry */
3177 break;
3178 }
3179 p = next + 1;
3180 next = next_brace_sub(next);
3181 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003182 free(new_pattern_buf);
3183 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003184
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003185 simple_glob:
3186 {
3187 int gr;
3188 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003189
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003190 memset(&globdata, 0, sizeof(globdata));
3191 gr = glob(pattern, 0, NULL, &globdata);
3192 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3193 if (gr != 0) {
3194 if (gr == GLOB_NOMATCH) {
3195 globfree(&globdata);
3196 /* NB: garbles parameter */
3197 unbackslash(pattern);
3198 o_addstr_with_NUL(o, pattern);
3199 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3200 return o_save_ptr_helper(o, n);
3201 }
3202 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003203 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003204 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3205 * but we didn't specify it. Paranoia again. */
3206 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3207 }
3208 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3209 char **argv = globdata.gl_pathv;
3210 while (1) {
3211 o_addstr_with_NUL(o, *argv);
3212 n = o_save_ptr_helper(o, n);
3213 argv++;
3214 if (!*argv)
3215 break;
3216 }
3217 }
3218 globfree(&globdata);
3219 }
3220 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003221}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003222/* Performs globbing on last list[],
3223 * saving each result as a new list[].
3224 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003225static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003226{
3227 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003228
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003229 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003230 if (!o->data)
3231 return o_save_ptr_helper(o, n);
3232 pattern = o->data + o_get_last_ptr(o, n);
3233 debug_printf_glob("glob pattern '%s'\n", pattern);
3234 if (!glob_needed(pattern)) {
3235 /* unbackslash last string in o in place, fix length */
3236 o->length = unbackslash(pattern) - o->data;
3237 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3238 return o_save_ptr_helper(o, n);
3239 }
3240
3241 copy = xstrdup(pattern);
3242 /* "forget" pattern in o */
3243 o->length = pattern - o->data;
3244 n = glob_brace(copy, o, n);
3245 free(copy);
3246 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003247 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003248 return n;
3249}
3250
Denys Vlasenko238081f2010-10-03 14:26:26 +02003251#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003252
3253/* Helper */
3254static int glob_needed(const char *s)
3255{
3256 while (*s) {
3257 if (*s == '\\') {
3258 if (!s[1])
3259 return 0;
3260 s += 2;
3261 continue;
3262 }
3263 if (*s == '*' || *s == '[' || *s == '?')
3264 return 1;
3265 s++;
3266 }
3267 return 0;
3268}
3269/* Performs globbing on last list[],
3270 * saving each result as a new list[].
3271 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003272static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003273{
3274 glob_t globdata;
3275 int gr;
3276 char *pattern;
3277
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003278 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003279 if (!o->data)
3280 return o_save_ptr_helper(o, n);
3281 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003282 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003283 if (!glob_needed(pattern)) {
3284 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003285 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003286 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003287 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003288 return o_save_ptr_helper(o, n);
3289 }
3290
3291 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003292 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3293 * If we glob "*.\*" and don't find anything, we need
3294 * to fall back to using literal "*.*", but GLOB_NOCHECK
3295 * will return "*.\*"!
3296 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003297 gr = glob(pattern, 0, NULL, &globdata);
3298 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003299 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003300 if (gr == GLOB_NOMATCH) {
3301 globfree(&globdata);
3302 goto literal;
3303 }
3304 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003305 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003306 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3307 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003308 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003309 }
3310 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3311 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003312 /* "forget" pattern in o */
3313 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003314 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003315 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003316 n = o_save_ptr_helper(o, n);
3317 argv++;
3318 if (!*argv)
3319 break;
3320 }
3321 }
3322 globfree(&globdata);
3323 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003324 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003325 return n;
3326}
3327
Denys Vlasenko238081f2010-10-03 14:26:26 +02003328#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003329
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003330/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003331 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003332static int o_save_ptr(o_string *o, int n)
3333{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003334 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003335 /* If o->has_empty_slot, list[n] was already globbed
3336 * (if it was requested back then when it was filled)
3337 * so don't do that again! */
3338 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003339 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003340 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003341 return o_save_ptr_helper(o, n);
3342}
3343
3344/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003345static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003346{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003347 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003348 int string_start;
3349
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003350 if (DEBUG_EXPAND)
3351 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003352 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003353 list = (char**)o->data;
3354 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3355 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003356 while (n) {
3357 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003358 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003359 }
3360 return list;
3361}
3362
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003364
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003365/* Returns pi->next - next pipe in the list */
3366static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003367{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 struct pipe *next;
3369 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003370
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003371 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003372 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003373 struct command *command;
3374 struct redir_struct *r, *rnext;
3375
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003376 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003377 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003378 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003379 if (DEBUG_CLEAN) {
3380 int a;
3381 char **p;
3382 for (a = 0, p = command->argv; *p; a++, p++) {
3383 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3384 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003385 }
3386 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003387 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003388 }
3389 /* not "else if": on syntax error, we may have both! */
3390 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003391 debug_printf_clean(" begin group (cmd_type:%d)\n",
3392 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003393 free_pipe_list(command->group);
3394 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003395 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003396 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003397 /* else is crucial here.
3398 * If group != NULL, child_func is meaningless */
3399#if ENABLE_HUSH_FUNCTIONS
3400 else if (command->child_func) {
3401 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3402 command->child_func->parent_cmd = NULL;
3403 }
3404#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003405#if !BB_MMU
3406 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003407 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003408#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003409 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003410 debug_printf_clean(" redirect %d%s",
3411 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003412 /* guard against the case >$FOO, where foo is unset or blank */
3413 if (r->rd_filename) {
3414 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3415 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003416 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003417 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003418 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003419 rnext = r->next;
3420 free(r);
3421 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003422 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003423 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003424 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003425 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003426#if ENABLE_HUSH_JOB
3427 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003428 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003429#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003430
3431 next = pi->next;
3432 free(pi);
3433 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003434}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003435
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003436static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003437{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003438 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003439#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003440 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003441#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003442 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003443 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003444 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003445}
3446
3447
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003448/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003449
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003450#ifndef debug_print_tree
3451static void debug_print_tree(struct pipe *pi, int lvl)
3452{
3453 static const char *const PIPE[] = {
3454 [PIPE_SEQ] = "SEQ",
3455 [PIPE_AND] = "AND",
3456 [PIPE_OR ] = "OR" ,
3457 [PIPE_BG ] = "BG" ,
3458 };
3459 static const char *RES[] = {
3460 [RES_NONE ] = "NONE" ,
3461# if ENABLE_HUSH_IF
3462 [RES_IF ] = "IF" ,
3463 [RES_THEN ] = "THEN" ,
3464 [RES_ELIF ] = "ELIF" ,
3465 [RES_ELSE ] = "ELSE" ,
3466 [RES_FI ] = "FI" ,
3467# endif
3468# if ENABLE_HUSH_LOOPS
3469 [RES_FOR ] = "FOR" ,
3470 [RES_WHILE] = "WHILE",
3471 [RES_UNTIL] = "UNTIL",
3472 [RES_DO ] = "DO" ,
3473 [RES_DONE ] = "DONE" ,
3474# endif
3475# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3476 [RES_IN ] = "IN" ,
3477# endif
3478# if ENABLE_HUSH_CASE
3479 [RES_CASE ] = "CASE" ,
3480 [RES_CASE_IN ] = "CASE_IN" ,
3481 [RES_MATCH] = "MATCH",
3482 [RES_CASE_BODY] = "CASE_BODY",
3483 [RES_ESAC ] = "ESAC" ,
3484# endif
3485 [RES_XXXX ] = "XXXX" ,
3486 [RES_SNTX ] = "SNTX" ,
3487 };
3488 static const char *const CMDTYPE[] = {
3489 "{}",
3490 "()",
3491 "[noglob]",
3492# if ENABLE_HUSH_FUNCTIONS
3493 "func()",
3494# endif
3495 };
3496
3497 int pin, prn;
3498
3499 pin = 0;
3500 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003501 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3502 lvl*2, "",
3503 pin,
3504 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3505 RES[pi->res_word],
3506 pi->followup, PIPE[pi->followup]
3507 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003508 prn = 0;
3509 while (prn < pi->num_cmds) {
3510 struct command *command = &pi->cmds[prn];
3511 char **argv = command->argv;
3512
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003513 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003514 lvl*2, "", prn,
3515 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003516#if ENABLE_HUSH_LINENO_VAR
3517 fdprintf(2, " LINENO:%u", command->lineno);
3518#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003519 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003520 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003521 CMDTYPE[command->cmd_type],
3522 argv
3523# if !BB_MMU
3524 , " group_as_string:", command->group_as_string
3525# else
3526 , "", ""
3527# endif
3528 );
3529 debug_print_tree(command->group, lvl+1);
3530 prn++;
3531 continue;
3532 }
3533 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003534 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003535 argv++;
3536 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003537 if (command->redirects)
3538 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003539 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003540 prn++;
3541 }
3542 pi = pi->next;
3543 pin++;
3544 }
3545}
3546#endif /* debug_print_tree */
3547
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003548static struct pipe *new_pipe(void)
3549{
Eric Andersen25f27032001-04-26 23:22:31 +00003550 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003551 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003552 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003553 return pi;
3554}
3555
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003556/* Command (member of a pipe) is complete, or we start a new pipe
3557 * if ctx->command is NULL.
3558 * No errors possible here.
3559 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003560static int done_command(struct parse_context *ctx)
3561{
3562 /* The command is really already in the pipe structure, so
3563 * advance the pipe counter and make a new, null command. */
3564 struct pipe *pi = ctx->pipe;
3565 struct command *command = ctx->command;
3566
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003567#if 0 /* Instead we emit error message at run time */
3568 if (ctx->pending_redirect) {
3569 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003570 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003571 ctx->pending_redirect = NULL;
3572 }
3573#endif
3574
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003575 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003576 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003577 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003578 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003579 }
3580 pi->num_cmds++;
3581 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003582 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003583 } else {
3584 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3585 }
3586
3587 /* Only real trickiness here is that the uncommitted
3588 * command structure is not counted in pi->num_cmds. */
3589 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003590 ctx->command = command = &pi->cmds[pi->num_cmds];
3591 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003592 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003593#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003594 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003595 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003596#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003597 return pi->num_cmds; /* used only for 0/nonzero check */
3598}
3599
3600static void done_pipe(struct parse_context *ctx, pipe_style type)
3601{
3602 int not_null;
3603
3604 debug_printf_parse("done_pipe entered, followup %d\n", type);
3605 /* Close previous command */
3606 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003607#if HAS_KEYWORDS
3608 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3609 ctx->ctx_inverted = 0;
3610 ctx->pipe->res_word = ctx->ctx_res_w;
3611#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003612 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3613 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003614 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3615 * in a backgrounded subshell.
3616 */
3617 struct pipe *pi;
3618 struct command *command;
3619
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003620 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003621 pi = ctx->list_head;
3622 while (pi != ctx->pipe) {
3623 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3624 goto no_conv;
3625 pi = pi->next;
3626 }
3627
3628 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3629 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3630 pi = xzalloc(sizeof(*pi));
3631 pi->followup = PIPE_BG;
3632 pi->num_cmds = 1;
3633 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3634 command = &pi->cmds[0];
3635 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3636 command->cmd_type = CMD_NORMAL;
3637 command->group = ctx->list_head;
3638#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003639 command->group_as_string = xstrndup(
3640 ctx->as_string.data,
3641 ctx->as_string.length - 1 /* do not copy last char, "&" */
3642 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003643#endif
3644 /* Replace all pipes in ctx with one newly created */
3645 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003646 } else {
3647 no_conv:
3648 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003649 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003650
3651 /* Without this check, even just <enter> on command line generates
3652 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003653 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003654 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003655#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003656 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003657#endif
3658#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003659 || ctx->ctx_res_w == RES_DONE
3660 || ctx->ctx_res_w == RES_FOR
3661 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003662#endif
3663#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003664 || ctx->ctx_res_w == RES_ESAC
3665#endif
3666 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003667 struct pipe *new_p;
3668 debug_printf_parse("done_pipe: adding new pipe: "
3669 "not_null:%d ctx->ctx_res_w:%d\n",
3670 not_null, ctx->ctx_res_w);
3671 new_p = new_pipe();
3672 ctx->pipe->next = new_p;
3673 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003674 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003675 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003676 * This is used to control execution.
3677 * RES_FOR and RES_IN are NOT sticky (needed to support
3678 * cases where variable or value happens to match a keyword):
3679 */
3680#if ENABLE_HUSH_LOOPS
3681 if (ctx->ctx_res_w == RES_FOR
3682 || ctx->ctx_res_w == RES_IN)
3683 ctx->ctx_res_w = RES_NONE;
3684#endif
3685#if ENABLE_HUSH_CASE
3686 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003687 ctx->ctx_res_w = RES_CASE_BODY;
3688 if (ctx->ctx_res_w == RES_CASE)
3689 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003690#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003691 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003692 /* Create the memory for command, roughly:
3693 * ctx->pipe->cmds = new struct command;
3694 * ctx->command = &ctx->pipe->cmds[0];
3695 */
3696 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003697 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003698 }
3699 debug_printf_parse("done_pipe return\n");
3700}
3701
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003702static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003703{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003704 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003705 if (MAYBE_ASSIGNMENT != 0)
3706 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003707 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003708 /* Create the memory for command, roughly:
3709 * ctx->pipe->cmds = new struct command;
3710 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003711 */
3712 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003713}
3714
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003715/* If a reserved word is found and processed, parse context is modified
3716 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003717 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003718#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003719struct reserved_combo {
3720 char literal[6];
3721 unsigned char res;
3722 unsigned char assignment_flag;
3723 int flag;
3724};
3725enum {
3726 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003727# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003728 FLAG_IF = (1 << RES_IF ),
3729 FLAG_THEN = (1 << RES_THEN ),
3730 FLAG_ELIF = (1 << RES_ELIF ),
3731 FLAG_ELSE = (1 << RES_ELSE ),
3732 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003733# endif
3734# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003735 FLAG_FOR = (1 << RES_FOR ),
3736 FLAG_WHILE = (1 << RES_WHILE),
3737 FLAG_UNTIL = (1 << RES_UNTIL),
3738 FLAG_DO = (1 << RES_DO ),
3739 FLAG_DONE = (1 << RES_DONE ),
3740 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003741# endif
3742# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003743 FLAG_MATCH = (1 << RES_MATCH),
3744 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003745# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003746 FLAG_START = (1 << RES_XXXX ),
3747};
3748
3749static const struct reserved_combo* match_reserved_word(o_string *word)
3750{
Eric Andersen25f27032001-04-26 23:22:31 +00003751 /* Mostly a list of accepted follow-up reserved words.
3752 * FLAG_END means we are done with the sequence, and are ready
3753 * to turn the compound list into a command.
3754 * FLAG_START means the word must start a new compound list.
3755 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003756 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003757# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003758 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3759 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3760 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3761 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3762 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3763 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003764# endif
3765# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003766 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3767 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3768 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3769 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3770 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3771 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003772# endif
3773# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003774 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3775 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003776# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003777 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003778 const struct reserved_combo *r;
3779
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003780 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003781 if (strcmp(word->data, r->literal) == 0)
3782 return r;
3783 }
3784 return NULL;
3785}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003786/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003787 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003788static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003789{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003790# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003791 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003792 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003793 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003794# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003795 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003796
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003797 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003798 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003799 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003801 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003802
3803 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003804# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003805 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3806 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003807 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003808 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003809# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003810 if (r->flag == 0) { /* '!' */
3811 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003812 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003813 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003814 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003815 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003816 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003817 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003818 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003819 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003820
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003821 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003822 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003823 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003824 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003825 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003826 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003827 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003828 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003829 } else {
3830 /* "{...} fi" is ok. "{...} if" is not
3831 * Example:
3832 * if { echo foo; } then { echo bar; } fi */
3833 if (ctx->command->group)
3834 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003835 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003836
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003837 ctx->ctx_res_w = r->res;
3838 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003839 ctx->is_assignment = r->assignment_flag;
3840 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003841
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003842 if (ctx->old_flag & FLAG_END) {
3843 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003844
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003845 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003846 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003847 old = ctx->stack;
3848 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003849 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003850# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003851 /* At this point, the compound command's string is in
3852 * ctx->as_string... except for the leading keyword!
3853 * Consider this example: "echo a | if true; then echo a; fi"
3854 * ctx->as_string will contain "true; then echo a; fi",
3855 * with "if " remaining in old->as_string!
3856 */
3857 {
3858 char *str;
3859 int len = old->as_string.length;
3860 /* Concatenate halves */
3861 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003862 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003863 /* Find where leading keyword starts in first half */
3864 str = old->as_string.data + len;
3865 if (str > old->as_string.data)
3866 str--; /* skip whitespace after keyword */
3867 while (str > old->as_string.data && isalpha(str[-1]))
3868 str--;
3869 /* Ugh, we're done with this horrid hack */
3870 old->command->group_as_string = xstrdup(str);
3871 debug_printf_parse("pop, remembering as:'%s'\n",
3872 old->command->group_as_string);
3873 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003874# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003875 *ctx = *old; /* physical copy */
3876 free(old);
3877 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003878 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003879}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003880#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003881
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003882/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003883 * Normal return is 0. Syntax errors return 1.
3884 * Note: on return, word is reset, but not o_free'd!
3885 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003886static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003887{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003888 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003889
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003890 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3891 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003892 debug_printf_parse("done_word return 0: true null, ignored\n");
3893 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003894 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003895
Eric Andersen25f27032001-04-26 23:22:31 +00003896 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003897 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3898 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003899 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003900 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003901 * If the redirection operator is "<<" or "<<-", the word
3902 * that follows the redirection operator shall be
3903 * subjected to quote removal; it is unspecified whether
3904 * any of the other expansions occur. For the other
3905 * redirection operators, the word that follows the
3906 * redirection operator shall be subjected to tilde
3907 * expansion, parameter expansion, command substitution,
3908 * arithmetic expansion, and quote removal.
3909 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003910 * on the word by a non-interactive shell; an interactive
3911 * shell may perform it, but shall do so only when
3912 * the expansion would result in one word."
3913 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003914//bash does not do parameter/command substitution or arithmetic expansion
3915//for _heredoc_ redirection word: these constructs look for exact eof marker
3916// as written:
3917// <<EOF$t
3918// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003919// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3920
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003921 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003922 /* Cater for >\file case:
3923 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3924 * Same with heredocs:
3925 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3926 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003927 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3928 unbackslash(ctx->pending_redirect->rd_filename);
3929 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003930 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003931 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3932 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003933 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003934 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003935 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003936 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003937#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003938# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003939 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003940 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003941 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003942 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003943 /* ctx->ctx_res_w = RES_MATCH; */
3944 ctx->ctx_dsemicolon = 0;
3945 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003946# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003947 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003948# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003949 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3950 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003951# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003952# if ENABLE_HUSH_CASE
3953 && ctx->ctx_res_w != RES_CASE
3954# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003955 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003956 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003957 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003958 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003959 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003960# if ENABLE_HUSH_LINENO_VAR
3961/* Case:
3962 * "while ...; do
3963 * cmd ..."
3964 * If we don't close the pipe _now_, immediately after "do", lineno logic
3965 * sees "cmd" as starting at "do" - i.e., at the previous line.
3966 */
3967 if (0
3968 IF_HUSH_IF(|| reserved->res == RES_THEN)
3969 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3970 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3971 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3972 ) {
3973 done_pipe(ctx, PIPE_SEQ);
3974 }
3975# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003976 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003977 debug_printf_parse("done_word return %d\n",
3978 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003979 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003980 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003981# if defined(CMD_SINGLEWORD_NOGLOB)
3982 if (0
3983# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003984 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003985# endif
3986 /* In bash, local/export/readonly are special, args
3987 * are assignments and therefore expansion of them
3988 * should be "one-word" expansion:
3989 * $ export i=`echo 'a b'` # one arg: "i=a b"
3990 * compare with:
3991 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3992 * ls: cannot access i=a: No such file or directory
3993 * ls: cannot access b: No such file or directory
3994 * Note: bash 3.2.33(1) does this only if export word
3995 * itself is not quoted:
3996 * $ export i=`echo 'aaa bbb'`; echo "$i"
3997 * aaa bbb
3998 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3999 * aaa
4000 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004001 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4002 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4003 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004004 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004005 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4006 }
4007 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004008# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004009 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004010#endif /* HAS_KEYWORDS */
4011
Denis Vlasenkobb929512009-04-16 10:59:40 +00004012 if (command->group) {
4013 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004014 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004015 debug_printf_parse("done_word return 1: syntax error, "
4016 "groups and arglists don't mix\n");
4017 return 1;
4018 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004019
4020 /* If this word wasn't an assignment, next ones definitely
4021 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004022 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4023 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004024 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004025 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004026 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004027 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004028 command->assignment_cnt++;
4029 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4030 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004031 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4032 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004033 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004034 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4035 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004036 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004037 }
Eric Andersen25f27032001-04-26 23:22:31 +00004038
Denis Vlasenko06810332007-05-21 23:30:54 +00004039#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004040 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004041 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004042 || !is_well_formed_var_name(command->argv[0], '\0')
4043 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004044 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004045 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004046 return 1;
4047 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004048 /* Force FOR to have just one word (variable name) */
4049 /* NB: basically, this makes hush see "for v in ..."
4050 * syntax as if it is "for v; in ...". FOR and IN become
4051 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004052 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004053 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004054#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004055#if ENABLE_HUSH_CASE
4056 /* Force CASE to have just one word */
4057 if (ctx->ctx_res_w == RES_CASE) {
4058 done_pipe(ctx, PIPE_SEQ);
4059 }
4060#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004061
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004062 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004063
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004064 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004065 return 0;
4066}
4067
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004068
4069/* Peek ahead in the input to find out if we have a "&n" construct,
4070 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004071 * Return:
4072 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4073 * REDIRFD_SYNTAX_ERR if syntax error,
4074 * REDIRFD_TO_FILE if no & was seen,
4075 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004076 */
4077#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004078#define parse_redir_right_fd(as_string, input) \
4079 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004080#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004081static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004082{
4083 int ch, d, ok;
4084
4085 ch = i_peek(input);
4086 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004087 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004088
4089 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004090 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004091 ch = i_peek(input);
4092 if (ch == '-') {
4093 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004094 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004095 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004096 }
4097 d = 0;
4098 ok = 0;
4099 while (ch != EOF && isdigit(ch)) {
4100 d = d*10 + (ch-'0');
4101 ok = 1;
4102 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004103 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004104 ch = i_peek(input);
4105 }
4106 if (ok) return d;
4107
4108//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4109
4110 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004111 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004112}
4113
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004114/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004115 */
4116static int parse_redirect(struct parse_context *ctx,
4117 int fd,
4118 redir_type style,
4119 struct in_str *input)
4120{
4121 struct command *command = ctx->command;
4122 struct redir_struct *redir;
4123 struct redir_struct **redirp;
4124 int dup_num;
4125
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004126 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004127 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004128 /* Check for a '>&1' type redirect */
4129 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4130 if (dup_num == REDIRFD_SYNTAX_ERR)
4131 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004132 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004133 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004134 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004135 if (dup_num) { /* <<-... */
4136 ch = i_getch(input);
4137 nommu_addchr(&ctx->as_string, ch);
4138 ch = i_peek(input);
4139 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004140 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004141
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004142 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004143 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 if (ch == '|') {
4145 /* >|FILE redirect ("clobbering" >).
4146 * Since we do not support "set -o noclobber" yet,
4147 * >| and > are the same for now. Just eat |.
4148 */
4149 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004150 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004151 }
4152 }
4153
4154 /* Create a new redir_struct and append it to the linked list */
4155 redirp = &command->redirects;
4156 while ((redir = *redirp) != NULL) {
4157 redirp = &(redir->next);
4158 }
4159 *redirp = redir = xzalloc(sizeof(*redir));
4160 /* redir->next = NULL; */
4161 /* redir->rd_filename = NULL; */
4162 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004163 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004164
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004165 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4166 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004168 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004169 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004170 /* Erik had a check here that the file descriptor in question
4171 * is legit; I postpone that to "run time"
4172 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004173 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4174 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004176#if 0 /* Instead we emit error message at run time */
4177 if (ctx->pending_redirect) {
4178 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004179 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004180 }
4181#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004182 /* Set ctx->pending_redirect, so we know what to do at the
4183 * end of the next parsed word. */
4184 ctx->pending_redirect = redir;
4185 }
4186 return 0;
4187}
4188
Eric Andersen25f27032001-04-26 23:22:31 +00004189/* If a redirect is immediately preceded by a number, that number is
4190 * supposed to tell which file descriptor to redirect. This routine
4191 * looks for such preceding numbers. In an ideal world this routine
4192 * needs to handle all the following classes of redirects...
4193 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4194 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4195 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4196 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004197 *
4198 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4199 * "2.7 Redirection
4200 * ... If n is quoted, the number shall not be recognized as part of
4201 * the redirection expression. For example:
4202 * echo \2>a
4203 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004204 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004205 *
4206 * A -1 return means no valid number was found,
4207 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004208 */
4209static int redirect_opt_num(o_string *o)
4210{
4211 int num;
4212
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004213 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004214 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004215 num = bb_strtou(o->data, NULL, 10);
4216 if (errno || num < 0)
4217 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004218 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004219 return num;
4220}
4221
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004222#if BB_MMU
4223#define fetch_till_str(as_string, input, word, skip_tabs) \
4224 fetch_till_str(input, word, skip_tabs)
4225#endif
4226static char *fetch_till_str(o_string *as_string,
4227 struct in_str *input,
4228 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004229 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004230{
4231 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004232 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004233 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004234 int ch;
4235
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004236 /* Starting with "" is necessary for this case:
4237 * cat <<EOF
4238 *
4239 * xxx
4240 * EOF
4241 */
4242 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4243
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004244 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004245
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004246 while (1) {
4247 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004248 if (ch != EOF)
4249 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004250 if (ch == '\n' || ch == EOF) {
4251 check_heredoc_end:
4252 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004253 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004254 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4255 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004256 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004257 return heredoc.data;
4258 }
4259 if (ch == '\n') {
4260 /* This is a new line.
4261 * Remember position and backslash-escaping status.
4262 */
4263 o_addchr(&heredoc, ch);
4264 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004266 past_EOL = heredoc.length;
4267 /* Get 1st char of next line, possibly skipping leading tabs */
4268 do {
4269 ch = i_getch(input);
4270 if (ch != EOF)
4271 nommu_addchr(as_string, ch);
4272 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4273 /* If this immediately ended the line,
4274 * go back to end-of-line checks.
4275 */
4276 if (ch == '\n')
4277 goto check_heredoc_end;
4278 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004279 } else {
4280 /* Backslash-line continuation in an unquoted
4281 * heredoc. This does not need special handling
4282 * for heredoc body (unquoted heredocs are
4283 * expanded on "execution" and that would take
4284 * care of this case too), but not the case
4285 * of line continuation *in terminator*:
4286 * cat <<EOF
4287 * Ok1
4288 * EO\
4289 * F
4290 */
4291 heredoc.data[--heredoc.length] = '\0';
4292 prev = 0; /* not '\' */
4293 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004294 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004295 }
4296 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004297 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004298 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004299 }
4300 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004301 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004302 if (prev == '\\' && ch == '\\')
4303 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004304 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004305 else
4306 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004307 }
4308}
4309
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004310/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4311 * and load them all. There should be exactly heredoc_cnt of them.
4312 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004313#if BB_MMU
4314#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4315 fetch_heredocs(pi, heredoc_cnt, input)
4316#endif
4317static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004318{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004319 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004320 int i;
4321 struct command *cmd = pi->cmds;
4322
Denys Vlasenko3675c372018-07-23 16:31:21 +02004323 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004324 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004325 cmd->argv ? cmd->argv[0] : "NONE"
4326 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004328 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329
Denys Vlasenko3675c372018-07-23 16:31:21 +02004330 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004331 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004332 while (redir) {
4333 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004334 char *p;
4335
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004336 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004337 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004338 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004339 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004340 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004341 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004342 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004343 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004344 free(redir->rd_filename);
4345 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004346 heredoc_cnt--;
4347 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004348 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004349 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004350 if (cmd->group) {
4351 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4352 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4353 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4354 if (heredoc_cnt < 0)
4355 return heredoc_cnt; /* error */
4356 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004357 cmd++;
4358 }
4359 pi = pi->next;
4360 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004361 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004362}
4363
4364
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004365static int run_list(struct pipe *pi);
4366#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004367#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4368 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004369#endif
4370static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004371 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004372 struct in_str *input,
4373 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004374
Denys Vlasenko474cb202018-07-24 13:03:03 +02004375/* Returns number of heredocs not yet consumed,
4376 * or -1 on error.
4377 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004378static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004379 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004380{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004381 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004382 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004383 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004384#if BB_MMU
4385# define as_string NULL
4386#else
4387 char *as_string = NULL;
4388#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004389 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004390 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004391 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004392 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004393
4394 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004395#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004396 if (ch == '(' && !ctx->word.has_quoted_part) {
4397 if (ctx->word.length)
4398 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004399 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004400 if (!command->argv)
4401 goto skip; /* (... */
4402 if (command->argv[1]) { /* word word ... (... */
4403 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004404 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004405 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004406 /* it is "word(..." or "word (..." */
4407 do
4408 ch = i_getch(input);
4409 while (ch == ' ' || ch == '\t');
4410 if (ch != ')') {
4411 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004412 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004413 }
4414 nommu_addchr(&ctx->as_string, ch);
4415 do
4416 ch = i_getch(input);
4417 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004418 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004419 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004420 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004421 }
4422 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004423 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004424 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004425 }
4426#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004427
4428#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004429 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004430 || ctx->word.length /* word{... */
4431 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004432 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004433 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004434 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004435 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004436 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004437 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004438#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004439
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004440 IF_HUSH_FUNCTIONS(skip:)
4441
Denis Vlasenko240c2552009-04-03 03:45:05 +00004442 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004443 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004444 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004445 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4446 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004447 } else {
4448 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004449 ch = i_peek(input);
4450 if (ch != ' ' && ch != '\t' && ch != '\n'
4451 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4452 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004453 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004454 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004455 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004456 if (ch != '(') {
4457 ch = i_getch(input);
4458 nommu_addchr(&ctx->as_string, ch);
4459 }
Eric Andersen25f27032001-04-26 23:22:31 +00004460 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004461
Denys Vlasenko474cb202018-07-24 13:03:03 +02004462 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4463 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4464 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004465#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004466 if (as_string)
4467 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004468#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004469
4470 /* empty ()/{} or parse error? */
4471 if (!pipe_list || pipe_list == ERR_PTR) {
4472 /* parse_stream already emitted error msg */
4473 if (!BB_MMU)
4474 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004475 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004476 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004477 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004478 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004479#if !BB_MMU
4480 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4481 command->group_as_string = as_string;
4482 debug_printf_parse("end of group, remembering as:'%s'\n",
4483 command->group_as_string);
4484#endif
4485
4486#if ENABLE_HUSH_FUNCTIONS
4487 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4488 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4489 struct command *cmd2;
4490
4491 cmd2 = xzalloc(sizeof(*cmd2));
4492 cmd2->cmd_type = CMD_SUBSHELL;
4493 cmd2->group = pipe_list;
4494# if !BB_MMU
4495//UNTESTED!
4496 cmd2->group_as_string = command->group_as_string;
4497 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4498# endif
4499
4500 pipe_list = new_pipe();
4501 pipe_list->cmds = cmd2;
4502 pipe_list->num_cmds = 1;
4503 }
4504#endif
4505
4506 command->group = pipe_list;
4507
Denys Vlasenko474cb202018-07-24 13:03:03 +02004508 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4509 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004510 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004511#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004512}
4513
Denys Vlasenko0b883582016-12-23 16:49:07 +01004514#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004515/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004516/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004517static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004518{
4519 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004520 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004521 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004522 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004523 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004524 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004525 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004526 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004527 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004528 }
4529}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004530static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4531{
4532 while (1) {
4533 int ch = i_getch(input);
4534 if (ch == EOF) {
4535 syntax_error_unterm_ch('\'');
4536 return 0;
4537 }
4538 if (ch == '\'')
4539 return 1;
4540 o_addqchr(dest, ch);
4541 }
4542}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004543/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004544static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004545static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004546{
4547 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004548 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004549 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004550 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004551 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004552 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004553 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004554 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004555 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004556 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004557 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004558 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004559 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004560 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004561 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4562 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004563 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004564 continue;
4565 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004566 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004567 }
4568}
4569/* Process `cmd` - copy contents until "`" is seen. Complicated by
4570 * \` quoting.
4571 * "Within the backquoted style of command substitution, backslash
4572 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4573 * The search for the matching backquote shall be satisfied by the first
4574 * backquote found without a preceding backslash; during this search,
4575 * if a non-escaped backquote is encountered within a shell comment,
4576 * a here-document, an embedded command substitution of the $(command)
4577 * form, or a quoted string, undefined results occur. A single-quoted
4578 * or double-quoted string that begins, but does not end, within the
4579 * "`...`" sequence produces undefined results."
4580 * Example Output
4581 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4582 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004583static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004584{
4585 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004586 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004587 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004589 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004590 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4591 ch = i_getch(input);
4592 if (ch != '`'
4593 && ch != '$'
4594 && ch != '\\'
4595 && (!in_dquote || ch != '"')
4596 ) {
4597 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004598 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004599 }
4600 if (ch == EOF) {
4601 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004602 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004603 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004604 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004605 }
4606}
4607/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4608 * quoting and nested ()s.
4609 * "With the $(command) style of command substitution, all characters
4610 * following the open parenthesis to the matching closing parenthesis
4611 * constitute the command. Any valid shell script can be used for command,
4612 * except a script consisting solely of redirections which produces
4613 * unspecified results."
4614 * Example Output
4615 * echo $(echo '(TEST)' BEST) (TEST) BEST
4616 * echo $(echo 'TEST)' BEST) TEST) BEST
4617 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004618 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004619 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004620 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004621 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4622 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004623 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004624#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004625static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004626{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004627 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004628 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004629# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004630 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004631# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004632 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4633
Denys Vlasenko817a2022018-06-26 15:35:17 +02004634#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004635 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004636#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004637 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4638
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004639 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004640 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004641 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004642 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004643 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004644 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004645 if (ch == end_ch
4646# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004647 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004648# endif
4649 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004650 if (!dbl)
4651 break;
4652 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004653 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004654 i_getch(input); /* eat second ')' */
4655 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004656 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004657 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004658 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004659 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004660 if (ch == '(' || ch == '{') {
4661 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004662 if (!add_till_closing_bracket(dest, input, ch))
4663 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004664 o_addchr(dest, ch);
4665 continue;
4666 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004667 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004668 if (!add_till_single_quote(dest, input))
4669 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004670 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004671 continue;
4672 }
4673 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004674 if (!add_till_double_quote(dest, input))
4675 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004676 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004677 continue;
4678 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004679 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004680 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4681 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004682 o_addchr(dest, ch);
4683 continue;
4684 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004685 if (ch == '\\') {
4686 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004687 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004688 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004689 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004690 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004691 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004692#if 0
4693 if (ch == '\n') {
4694 /* "backslash+newline", ignore both */
4695 o_delchr(dest); /* undo insertion of '\' */
4696 continue;
4697 }
4698#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004699 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004700 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004701 continue;
4702 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004703 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004704 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004705 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004706}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004707#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004708
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004709/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004710#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004711#define parse_dollar(as_string, dest, input, quote_mask) \
4712 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004713#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004714#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004715static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004716 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004717 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004718{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004719 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004720
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004721 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004722 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004723 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004724 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004725 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004726 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004727 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004728 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004729 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004730 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004731 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004732 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004733 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004734 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004735 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004736 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004737 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004738 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004739 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004740 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004741 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004742 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004743 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004744 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004745 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004746 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004747 o_addchr(dest, ch | quote_mask);
4748 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004749 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004750 case '$': /* pid */
4751 case '!': /* last bg pid */
4752 case '?': /* last exit code */
4753 case '#': /* number of args */
4754 case '*': /* args */
4755 case '@': /* args */
4756 goto make_one_char_var;
4757 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004758 char len_single_ch;
4759
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004760 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4761
Denys Vlasenko74369502010-05-21 19:52:01 +02004762 ch = i_getch(input); /* eat '{' */
4763 nommu_addchr(as_string, ch);
4764
Denys Vlasenko46e64982016-09-29 19:50:55 +02004765 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004766 /* It should be ${?}, or ${#var},
4767 * or even ${?+subst} - operator acting on a special variable,
4768 * or the beginning of variable name.
4769 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004770 if (ch == EOF
4771 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4772 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004773 bad_dollar_syntax:
4774 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004775 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4776 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004777 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004778 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004779 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004780 ch |= quote_mask;
4781
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004782 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004783 * However, this regresses some of our testsuite cases
4784 * which check invalid constructs like ${%}.
4785 * Oh well... let's check that the var name part is fine... */
4786
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004787 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004788 unsigned pos;
4789
Denys Vlasenko74369502010-05-21 19:52:01 +02004790 o_addchr(dest, ch);
4791 debug_printf_parse(": '%c'\n", ch);
4792
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004793 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004794 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004795 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004796 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004797
Denys Vlasenko74369502010-05-21 19:52:01 +02004798 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004799 unsigned end_ch;
4800 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004801 /* handle parameter expansions
4802 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4803 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004804 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4805 if (len_single_ch != '#'
4806 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4807 || i_peek(input) != '}'
4808 ) {
4809 goto bad_dollar_syntax;
4810 }
4811 /* else: it's "length of C" ${#C} op,
4812 * where C is a single char
4813 * special var name, e.g. ${#!}.
4814 */
4815 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004816 /* Eat everything until closing '}' (or ':') */
4817 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004818 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004819 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004820 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004821 ) {
4822 /* It's ${var:N[:M]} thing */
4823 end_ch = '}' * 0x100 + ':';
4824 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004825 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004826 && ch == '/'
4827 ) {
4828 /* It's ${var/[/]pattern[/repl]} thing */
4829 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4830 i_getch(input);
4831 nommu_addchr(as_string, '/');
4832 ch = '\\';
4833 }
4834 end_ch = '}' * 0x100 + '/';
4835 }
4836 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004837 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004838 if (!BB_MMU)
4839 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004840#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004841 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004842 if (last_ch == 0) /* error? */
4843 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004844#else
4845#error Simple code to only allow ${var} is not implemented
4846#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004847 if (as_string) {
4848 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004849 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004850 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004851
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004852 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4853 && (end_ch & 0xff00)
4854 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004855 /* close the first block: */
4856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004857 /* while parsing N from ${var:N[:M]}
4858 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004859 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004860 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004861 end_ch = '}';
4862 goto again;
4863 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004864 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004865 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004866 /* it's ${var:N} - emulate :999999999 */
4867 o_addstr(dest, "999999999");
4868 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004869 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004870 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004871 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004872 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004873 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4875 break;
4876 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004877#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004878 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004879 unsigned pos;
4880
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004881 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004882 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004883# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004884 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004885 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004886 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004887 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4888 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004889 if (!BB_MMU)
4890 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004891 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4892 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004893 if (as_string) {
4894 o_addstr(as_string, dest->data + pos);
4895 o_addchr(as_string, ')');
4896 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004897 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004898 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004899 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004900 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004901# endif
4902# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004903 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4904 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004905 if (!BB_MMU)
4906 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004907 if (!add_till_closing_bracket(dest, input, ')'))
4908 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004909 if (as_string) {
4910 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004911 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004912 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004913 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004914# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004915 break;
4916 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004917#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004918 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004919 goto make_var;
4920#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004921 /* TODO: $_ and $-: */
4922 /* $_ Shell or shell script name; or last argument of last command
4923 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4924 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004925 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004926 ch = i_getch(input);
4927 nommu_addchr(as_string, ch);
4928 ch = i_peek_and_eat_bkslash_nl(input);
4929 if (isalnum(ch)) { /* it's $_name or $_123 */
4930 ch = '_';
4931 goto make_var1;
4932 }
4933 /* else: it's $_ */
4934#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004935 default:
4936 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004937 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004938 debug_printf_parse("parse_dollar return 1 (ok)\n");
4939 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004940#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004941}
4942
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004943#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004944#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004945 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004946#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004947#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004948static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004949 o_string *dest,
4950 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004951 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004952{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004953 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004954 int next;
4955
4956 again:
4957 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004958 if (ch != EOF)
4959 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004960 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004961 debug_printf_parse("encode_string return 1 (ok)\n");
4962 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004963 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004964 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004965 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004966 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004967 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004968 }
4969 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004970 if (ch != '\n') {
4971 next = i_peek(input);
4972 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004973 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004974 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02004975 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004976 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004977 /* Testcase: in interactive shell a file with
4978 * echo "unterminated string\<eof>
4979 * is sourced.
4980 */
4981 syntax_error_unterm_ch('"');
4982 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004983 }
4984 /* bash:
4985 * "The backslash retains its special meaning [in "..."]
4986 * only when followed by one of the following characters:
4987 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004988 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004989 * NB: in (unquoted) heredoc, above does not apply to ",
4990 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004991 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004992 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004993 ch = i_getch(input); /* eat next */
4994 if (ch == '\n')
4995 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004996 } /* else: ch remains == '\\', and we double it below: */
4997 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004998 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004999 goto again;
5000 }
5001 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005002 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5003 debug_printf_parse("encode_string return 0: "
5004 "parse_dollar returned 0 (error)\n");
5005 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005006 }
5007 goto again;
5008 }
5009#if ENABLE_HUSH_TICK
5010 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005011 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005012 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5013 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005014 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5015 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005016 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5017 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005018 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005019 }
5020#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005021 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005022 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005023#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005024}
5025
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005026/*
5027 * Scan input until EOF or end_trigger char.
5028 * Return a list of pipes to execute, or NULL on EOF
5029 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005030 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005031 * reset parsing machinery and start parsing anew,
5032 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005033 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005034static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005035 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005036 struct in_str *input,
5037 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005038{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005039 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005040 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005041
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005042 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005043 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005044 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005045 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005046 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005047 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005048
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005049 initialize_context(&ctx);
5050
5051 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5052 * Preventing this:
5053 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005054 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005055
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005056 /* We used to separate words on $IFS here. This was wrong.
5057 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005058 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005059 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005060
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005061 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005062 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005063 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005064 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005065 int ch;
5066 int next;
5067 int redir_fd;
5068 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005069
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005070 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005071 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005072 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005073 if (ch == EOF) {
5074 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005075
5076 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005077 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005078 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005079 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005080 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005081 syntax_error_unterm_ch('(');
5082 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005083 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005084 if (end_trigger == '}') {
5085 syntax_error_unterm_ch('{');
5086 goto parse_error;
5087 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005088
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005089 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005090 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005091 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005092 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005093 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005094 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005095 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005096 /* (this makes bare "&" cmd a no-op.
5097 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005098 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005099 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005100 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005101 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005102 pi = NULL;
5103 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005104#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005105 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005106 if (pstring)
5107 *pstring = ctx.as_string.data;
5108 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005109 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005110#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005111 // heredoc_cnt must be 0 here anyway
5112 //if (heredoc_cnt_ptr)
5113 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005114 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005115 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005116 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005117 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005118 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005119
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005120 /* Handle "'" and "\" first, as they won't play nice with
5121 * i_peek_and_eat_bkslash_nl() anyway:
5122 * echo z\\
5123 * and
5124 * echo '\
5125 * '
5126 * would break.
5127 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005128 if (ch == '\\') {
5129 ch = i_getch(input);
5130 if (ch == '\n')
5131 continue; /* drop \<newline>, get next char */
5132 nommu_addchr(&ctx.as_string, '\\');
5133 o_addchr(&ctx.word, '\\');
5134 if (ch == EOF) {
5135 /* Testcase: eval 'echo Ok\' */
5136 /* bash-4.3.43 was removing backslash,
5137 * but 4.4.19 retains it, most other shells too
5138 */
5139 continue; /* get next char */
5140 }
5141 /* Example: echo Hello \2>file
5142 * we need to know that word 2 is quoted
5143 */
5144 ctx.word.has_quoted_part = 1;
5145 nommu_addchr(&ctx.as_string, ch);
5146 o_addchr(&ctx.word, ch);
5147 continue; /* get next char */
5148 }
5149 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005150 if (ch == '\'') {
5151 ctx.word.has_quoted_part = 1;
5152 next = i_getch(input);
5153 if (next == '\'' && !ctx.pending_redirect)
5154 goto insert_empty_quoted_str_marker;
5155
5156 ch = next;
5157 while (1) {
5158 if (ch == EOF) {
5159 syntax_error_unterm_ch('\'');
5160 goto parse_error;
5161 }
5162 nommu_addchr(&ctx.as_string, ch);
5163 if (ch == '\'')
5164 break;
5165 if (ch == SPECIAL_VAR_SYMBOL) {
5166 /* Convert raw ^C to corresponding special variable reference */
5167 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5168 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5169 }
5170 o_addqchr(&ctx.word, ch);
5171 ch = i_getch(input);
5172 }
5173 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005174 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005175
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005176 next = '\0';
5177 if (ch != '\n')
5178 next = i_peek_and_eat_bkslash_nl(input);
5179
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005180 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005181 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005182 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005183 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005184 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005185 || ctx.word.length /* word{... - non-special */
5186 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005187 || (next != ';' /* }; - special */
5188 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005189 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005190 && next != '&' /* }& and }&& ... - special */
5191 && next != '|' /* }|| ... - special */
5192 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005193 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005194 ) {
5195 /* They are not special, skip "{}" */
5196 is_special += 2;
5197 }
5198 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005199 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005200
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005201 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005202 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005203 o_addQchr(&ctx.word, ch);
5204 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5205 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005206 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005207 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005208 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005209 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5210 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005211 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005212 continue;
5213 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005214
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005215 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005216#if ENABLE_HUSH_LINENO_VAR
5217/* Case:
5218 * "while ...; do<whitespace><newline>
5219 * cmd ..."
5220 * would think that "cmd" starts in <whitespace> -
5221 * i.e., at the previous line.
5222 * We need to skip all whitespace before newlines.
5223 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005224 while (ch != '\n') {
5225 next = i_peek(input);
5226 if (next != ' ' && next != '\t' && next != '\n')
5227 break; /* next char is not ws */
5228 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005229 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005230 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005231#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005232 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005233 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005234 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005235 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005236 /* Is this a case when newline is simply ignored?
5237 * Some examples:
5238 * "cmd | <newline> cmd ..."
5239 * "case ... in <newline> word) ..."
5240 */
5241 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005242 && ctx.word.length == 0
5243 && !ctx.word.has_quoted_part
5244 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005245 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005246 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005247 * Without check #1, interactive shell
5248 * ignores even bare <newline>,
5249 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005250 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005251 * ps2> _ <=== wrong, should be ps1
5252 * Without check #2, "cmd & <newline>"
5253 * is similarly mistreated.
5254 * (BTW, this makes "cmd & cmd"
5255 * and "cmd && cmd" non-orthogonal.
5256 * Really, ask yourself, why
5257 * "cmd && <newline>" doesn't start
5258 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005259 * The only reason is that it might be
5260 * a "cmd1 && <nl> cmd2 &" construct,
5261 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005262 */
5263 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005264 if (pi->num_cmds != 0 /* check #1 */
5265 && pi->followup != PIPE_BG /* check #2 */
5266 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005267 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005268 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005269 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005270 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005271 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005272 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005273 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005274 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5275 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005276 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005277 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005278 ctx.is_assignment = MAYBE_ASSIGNMENT;
5279 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005280 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005281 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005282 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005283 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005284 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005285
5286 /* "cmd}" or "cmd }..." without semicolon or &:
5287 * } is an ordinary char in this case, even inside { cmd; }
5288 * Pathological example: { ""}; } should exec "}" cmd
5289 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005290 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005291 if (ctx.word.length != 0 /* word} */
5292 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005293 ) {
5294 goto ordinary_char;
5295 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005296 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5297 /* Generally, there should be semicolon: "cmd; }"
5298 * However, bash allows to omit it if "cmd" is
5299 * a group. Examples:
5300 * { { echo 1; } }
5301 * {(echo 1)}
5302 * { echo 0 >&2 | { echo 1; } }
5303 * { while false; do :; done }
5304 * { case a in b) ;; esac }
5305 */
5306 if (ctx.command->group)
5307 goto term_group;
5308 goto ordinary_char;
5309 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005310 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005311 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005312 goto skip_end_trigger;
5313 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005314 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005315 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005316 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005317 && (ch != ';' || heredoc_cnt == 0)
5318#if ENABLE_HUSH_CASE
5319 && (ch != ')'
5320 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005321 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005322 )
5323#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005324 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005325 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005326 goto parse_error;
5327 }
5328 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005329 ctx.is_assignment = MAYBE_ASSIGNMENT;
5330 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005331 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005332 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005333 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005334 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005335 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005336#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005337 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005338 if (pstring)
5339 *pstring = ctx.as_string.data;
5340 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005341 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005342#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005343 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5344 /* Example: bare "{ }", "()" */
5345 G.last_exitcode = 2; /* bash compat */
5346 syntax_error_unexpected_ch(ch);
5347 goto parse_error2;
5348 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005349 if (heredoc_cnt_ptr)
5350 *heredoc_cnt_ptr = heredoc_cnt;
5351 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005352 debug_printf_parse("parse_stream return %p: "
5353 "end_trigger char found\n",
5354 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005355 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005356 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005357 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005358 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005359
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005360 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005361 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005362
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005363 /* Catch <, > before deciding whether this word is
5364 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5365 switch (ch) {
5366 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005367 redir_fd = redirect_opt_num(&ctx.word);
5368 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005369 goto parse_error;
5370 }
5371 redir_style = REDIRECT_OVERWRITE;
5372 if (next == '>') {
5373 redir_style = REDIRECT_APPEND;
5374 ch = i_getch(input);
5375 nommu_addchr(&ctx.as_string, ch);
5376 }
5377#if 0
5378 else if (next == '(') {
5379 syntax_error(">(process) not supported");
5380 goto parse_error;
5381 }
5382#endif
5383 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5384 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005385 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005386 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005387 redir_fd = redirect_opt_num(&ctx.word);
5388 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005389 goto parse_error;
5390 }
5391 redir_style = REDIRECT_INPUT;
5392 if (next == '<') {
5393 redir_style = REDIRECT_HEREDOC;
5394 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005395 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005396 ch = i_getch(input);
5397 nommu_addchr(&ctx.as_string, ch);
5398 } else if (next == '>') {
5399 redir_style = REDIRECT_IO;
5400 ch = i_getch(input);
5401 nommu_addchr(&ctx.as_string, ch);
5402 }
5403#if 0
5404 else if (next == '(') {
5405 syntax_error("<(process) not supported");
5406 goto parse_error;
5407 }
5408#endif
5409 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5410 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005411 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005412 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005413 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005414 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005415 /* note: we do not add it to &ctx.as_string */
5416/* TODO: in bash:
5417 * comment inside $() goes to the next \n, even inside quoted string (!):
5418 * cmd "$(cmd2 #comment)" - syntax error
5419 * cmd "`cmd2 #comment`" - ok
5420 * We accept both (comment ends where command subst ends, in both cases).
5421 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005422 while (1) {
5423 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005424 if (ch == '\n') {
5425 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005426 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005427 }
5428 ch = i_getch(input);
5429 if (ch == EOF)
5430 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005431 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005432 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005433 }
5434 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005435 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005436 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005437
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005438 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005439 /* check that we are not in word in "a=1 2>word b=1": */
5440 && !ctx.pending_redirect
5441 ) {
5442 /* ch is a special char and thus this word
5443 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005444 ctx.is_assignment = NOT_ASSIGNMENT;
5445 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005446 }
5447
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005448 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5449
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005450 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005451 case SPECIAL_VAR_SYMBOL:
5452 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005453 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5454 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005455 /* fall through */
5456 case '#':
5457 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005458 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005459 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005460 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005461 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005462 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005463 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005464 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005465 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005466 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005467 case '"':
5468 ctx.word.has_quoted_part = 1;
5469 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005470 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005471 insert_empty_quoted_str_marker:
5472 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005473 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5474 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005475 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005476 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005477 if (ctx.is_assignment == NOT_ASSIGNMENT)
5478 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005479 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005480 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005481 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005482 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005483#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005484 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005485 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005486
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005487 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5488 o_addchr(&ctx.word, '`');
5489 USE_FOR_NOMMU(pos = ctx.word.length;)
5490 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005491 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005492# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005493 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005494 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005495# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005496 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5497 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005498 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005499 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005500#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005501 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005502#if ENABLE_HUSH_CASE
5503 case_semi:
5504#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005505 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005506 goto parse_error;
5507 }
5508 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005509#if ENABLE_HUSH_CASE
5510 /* Eat multiple semicolons, detect
5511 * whether it means something special */
5512 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005513 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005514 if (ch != ';')
5515 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005516 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005517 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005518 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005519 ctx.ctx_dsemicolon = 1;
5520 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005521 break;
5522 }
5523 }
5524#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005525 new_cmd:
5526 /* We just finished a cmd. New one may start
5527 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005528 ctx.is_assignment = MAYBE_ASSIGNMENT;
5529 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005530 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005531 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005532 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005533 goto parse_error;
5534 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005535 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005536 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005537 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005538 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005539 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005540 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005541 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005542 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005543 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005544 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005545 goto parse_error;
5546 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005547#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005548 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005549 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005550#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005551 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005552 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005553 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005554 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005555 } else {
5556 /* we could pick up a file descriptor choice here
5557 * with redirect_opt_num(), but bash doesn't do it.
5558 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005559 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005560 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005561 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005562 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005563#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005564 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005565 if (ctx.ctx_res_w == RES_MATCH
5566 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005567 && ctx.word.length == 0 /* not word(... */
5568 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005569 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005570 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005571 }
5572#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005573 /* fall through */
5574 case '{': {
5575 int n = parse_group(&ctx, input, ch);
5576 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005577 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005578 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005579 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5580 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005581 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005582 }
Eric Andersen25f27032001-04-26 23:22:31 +00005583 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005584#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005585 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005586 goto case_semi;
5587#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005588
Eric Andersen25f27032001-04-26 23:22:31 +00005589 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005590 /* proper use of this character is caught by end_trigger:
5591 * if we see {, we call parse_group(..., end_trigger='}')
5592 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005593 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005594 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005595 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005596 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005597 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005598 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005599 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005600 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005601
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005602 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005603 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005604 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005605 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005606 struct parse_context *pctx;
5607 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005608
5609 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005610 * Sample for finding leaks on syntax error recovery path.
5611 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005612 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005613 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005614 * while if (true | { true;}); then echo ok; fi; do break; done
5615 * 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 +00005616 */
5617 pctx = &ctx;
5618 do {
5619 /* Update pipe/command counts,
5620 * otherwise freeing may miss some */
5621 done_pipe(pctx, PIPE_SEQ);
5622 debug_printf_clean("freeing list %p from ctx %p\n",
5623 pctx->list_head, pctx);
5624 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005625 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005626 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005627#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005628 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005629#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005630 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005631 if (pctx != &ctx) {
5632 free(pctx);
5633 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005634 IF_HAS_KEYWORDS(pctx = p2;)
5635 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005636
Denys Vlasenko474cb202018-07-24 13:03:03 +02005637 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005638#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005639 if (pstring)
5640 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005641#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005642 debug_leave();
5643 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005644 }
Eric Andersen25f27032001-04-26 23:22:31 +00005645}
5646
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005647
5648/*** Execution routines ***/
5649
5650/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005651#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005652#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005653 expand_string_to_string(str)
5654#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005655static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005656#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005657static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005658#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005659static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005660
5661/* expand_strvec_to_strvec() takes a list of strings, expands
5662 * all variable references within and returns a pointer to
5663 * a list of expanded strings, possibly with larger number
5664 * of strings. (Think VAR="a b"; echo $VAR).
5665 * This new list is allocated as a single malloc block.
5666 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005667 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668 * Caller can deallocate entire list by single free(list). */
5669
Denys Vlasenko238081f2010-10-03 14:26:26 +02005670/* A horde of its helpers come first: */
5671
5672static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5673{
5674 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005675 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005676
Denys Vlasenko9e800222010-10-03 14:28:04 +02005677#if ENABLE_HUSH_BRACE_EXPANSION
5678 if (c == '{' || c == '}') {
5679 /* { -> \{, } -> \} */
5680 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005681 /* And now we want to add { or } and continue:
5682 * o_addchr(o, c);
5683 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005684 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005685 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005686 }
5687#endif
5688 o_addchr(o, c);
5689 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005690 /* \z -> \\\z; \<eol> -> \\<eol> */
5691 o_addchr(o, '\\');
5692 if (len) {
5693 len--;
5694 o_addchr(o, '\\');
5695 o_addchr(o, *str++);
5696 }
5697 }
5698 }
5699}
5700
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005701/* Store given string, finalizing the word and starting new one whenever
5702 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005703 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005704 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005705 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5706 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005707static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005708{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005709 int last_is_ifs = 0;
5710
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005711 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005712 int word_len;
5713
5714 if (!*str) /* EOL - do not finalize word */
5715 break;
5716 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005717 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005718 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005719 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005720 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005721 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005722 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005723 * Example: "v='\*'; echo b$v" prints "b\*"
5724 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005725 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005726 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005727 /*/ Why can't we do it easier? */
5728 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5729 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5730 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005731 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005732 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005733 if (!*str) /* EOL - do not finalize word */
5734 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005735 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005736
5737 /* We know str here points to at least one IFS char */
5738 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005739 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005740 if (!*str) /* EOL - do not finalize word */
5741 break;
5742
Denys Vlasenko96786362018-04-11 16:02:58 +02005743 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5744 && strchr(G.ifs, *str) /* the second check would fail */
5745 ) {
5746 /* This is a non-whitespace $IFS char */
5747 /* Skip it and IFS whitespace chars, start new word */
5748 str++;
5749 str += strspn(str, G.ifs_whitespace);
5750 goto new_word;
5751 }
5752
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005753 /* Start new word... but not always! */
5754 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005755 if (output->has_quoted_part
5756 /* Case "v=' a'; echo $v":
5757 * here nothing precedes the space in $v expansion,
5758 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005759 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005760 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005761 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005762 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005763 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005764 o_addchr(output, '\0');
5765 debug_print_list("expand_on_ifs", output, n);
5766 n = o_save_ptr(output, n);
5767 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005768 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005769
Denys Vlasenko168579a2018-07-19 13:45:54 +02005770 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005771 debug_print_list("expand_on_ifs[1]", output, n);
5772 return n;
5773}
5774
5775/* Helper to expand $((...)) and heredoc body. These act as if
5776 * they are in double quotes, with the exception that they are not :).
5777 * Just the rules are similar: "expand only $var and `cmd`"
5778 *
5779 * Returns malloced string.
5780 * As an optimization, we return NULL if expansion is not needed.
5781 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005782static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005783{
5784 char *exp_str;
5785 struct in_str input;
5786 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005787 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005788
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005789 cp = str;
5790 for (;;) {
5791 if (!*cp) return NULL; /* string has no special chars */
5792 if (*cp == '$') break;
5793 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005794#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005795 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005796#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005797 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005798 }
5799
5800 /* We need to expand. Example:
5801 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5802 */
5803 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005804 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005805//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005806 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005807 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005808 EXP_FLAG_ESC_GLOB_CHARS,
5809 /*unbackslash:*/ 1
5810 );
5811 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005812 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005813 return exp_str;
5814}
5815
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005816/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5817 * These can contain single- and double-quoted strings,
5818 * and treated as if the ARG string is initially unquoted. IOW:
5819 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5820 * a dquoted string: "${var#"zz"}"), the difference only comes later
5821 * (word splitting and globbing of the ${var...} result).
5822 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005823#if !BASH_PATTERN_SUBST
5824#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5825 encode_then_expand_vararg(str, handle_squotes)
5826#endif
5827static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5828{
5829#if !BASH_PATTERN_SUBST
5830 const int do_unbackslash = 0;
5831#endif
5832 char *exp_str;
5833 struct in_str input;
5834 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005835 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005836
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005837 cp = str;
5838 for (;;) {
5839 if (!*cp) return NULL; /* string has no special chars */
5840 if (*cp == '$') break;
5841 if (*cp == '\\') break;
5842 if (*cp == '\'') break;
5843 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005844#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005845 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005846#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005847 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005848 }
5849
Denys Vlasenkob762c782018-07-17 14:21:38 +02005850 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005851 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005852 exp_str = NULL;
5853
5854 for (;;) {
5855 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005856
5857 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005858 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5859 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005860
5861 if (!dest.o_expflags) {
5862 if (ch == EOF)
5863 break;
5864 if (handle_squotes && ch == '\'') {
5865 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02005866 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005867 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005868 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005869 }
5870 if (ch == EOF) {
5871 syntax_error_unterm_ch('"');
5872 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005873 }
5874 if (ch == '"') {
5875 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5876 continue;
5877 }
5878 if (ch == '\\') {
5879 ch = i_getch(&input);
5880 if (ch == EOF) {
5881//example? error message? syntax_error_unterm_ch('"');
5882 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5883 goto ret;
5884 }
5885 o_addqchr(&dest, ch);
5886 continue;
5887 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005888 if (ch == '$') {
5889 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5890 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5891 goto ret;
5892 }
5893 continue;
5894 }
5895#if ENABLE_HUSH_TICK
5896 if (ch == '`') {
5897 //unsigned pos = dest->length;
5898 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5899 o_addchr(&dest, 0x80 | '`');
5900 if (!add_till_backquote(&dest, &input,
5901 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5902 )
5903 ) {
5904 goto ret; /* error */
5905 }
5906 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5907 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5908 continue;
5909 }
5910#endif
5911 o_addQchr(&dest, ch);
5912 } /* for (;;) */
5913
5914 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5915 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005916 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5917 do_unbackslash
5918 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005919 ret:
5920 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005921 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005922 return exp_str;
5923}
5924
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005925/* Expanding ARG in ${var+ARG}, ${var-ARG}
5926 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02005927static int encode_then_append_var_plusminus(o_string *output, int n,
5928 const char *str, int dquoted)
5929{
5930 struct in_str input;
5931 o_string dest = NULL_O_STRING;
5932
5933#if 0 //todo?
5934 const char *cp;
5935 cp = str;
5936 for (;;) {
5937 if (!*cp) return NULL; /* string has no special chars */
5938 if (*cp == '$') break;
5939 if (*cp == '\\') break;
5940 if (*cp == '\'') break;
5941 if (*cp == '"') break;
5942#if ENABLE_HUSH_TICK
5943 if (*cp == '`') break;
5944#endif
5945 cp++;
5946 }
5947#endif
5948
Denys Vlasenko294eb462018-07-20 16:18:59 +02005949 setup_string_in_str(&input, str);
5950
5951 for (;;) {
5952 int ch;
5953
5954 ch = i_getch(&input);
5955 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
5956 __func__, ch, ch, dest.o_expflags);
5957
5958 if (!dest.o_expflags) {
5959 if (ch == EOF)
5960 break;
5961 if (!dquoted && strchr(G.ifs, ch)) {
5962 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
5963 * do not assume we are at the start of the word (PREFIX above).
5964 */
5965 if (dest.data) {
5966 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02005967 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005968 o_addchr(output, '\0');
5969 n = o_save_ptr(output, n); /* create next word */
5970 } else
5971 if (output->length != o_get_last_ptr(output, n)
5972 || output->has_quoted_part
5973 ) {
5974 /* For these cases:
5975 * f() { for i; do echo "|$i|"; done; }; x=x
5976 * f a${x:+ }b # 1st condition
5977 * |a|
5978 * |b|
5979 * f ""${x:+ }b # 2nd condition
5980 * ||
5981 * |b|
5982 */
5983 o_addchr(output, '\0');
5984 n = o_save_ptr(output, n); /* create next word */
5985 }
5986 continue;
5987 }
5988 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005989 if (!add_till_single_quote_dquoted(&dest, &input))
5990 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005991 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5992 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005993 continue;
5994 }
5995 }
5996 if (ch == EOF) {
5997 syntax_error_unterm_ch('"');
5998 goto ret; /* error */
5999 }
6000 if (ch == '"') {
6001 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006002 if (dest.o_expflags) {
6003 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6004 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6005 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006006 continue;
6007 }
6008 if (ch == '\\') {
6009 ch = i_getch(&input);
6010 if (ch == EOF) {
6011//example? error message? syntax_error_unterm_ch('"');
6012 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6013 goto ret;
6014 }
6015 o_addqchr(&dest, ch);
6016 continue;
6017 }
6018 if (ch == '$') {
6019 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6020 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6021 goto ret;
6022 }
6023 continue;
6024 }
6025#if ENABLE_HUSH_TICK
6026 if (ch == '`') {
6027 //unsigned pos = dest->length;
6028 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6029 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6030 if (!add_till_backquote(&dest, &input,
6031 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6032 )
6033 ) {
6034 goto ret; /* error */
6035 }
6036 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6037 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6038 continue;
6039 }
6040#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006041 if (dquoted) {
6042 /* Always glob-protect if in dquotes:
6043 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6044 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6045 */
6046 o_addqchr(&dest, ch);
6047 } else {
6048 /* Glob-protect only if char is quoted:
6049 * x=x; echo ${x:+/bin/c*} - prints many filenames
6050 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6051 */
6052 o_addQchr(&dest, ch);
6053 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006054 } /* for (;;) */
6055
6056 if (dest.data) {
6057 n = expand_vars_to_list(output, n, dest.data);
6058 }
6059 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006060 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006061 return n;
6062}
6063
Denys Vlasenko0b883582016-12-23 16:49:07 +01006064#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006065static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006066{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006067 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006068 arith_t res;
6069 char *exp_str;
6070
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006071 math_state.lookupvar = get_local_var_value;
6072 math_state.setvar = set_local_var_from_halves;
6073 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006074 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006075 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006076 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006077 if (errmsg_p)
6078 *errmsg_p = math_state.errmsg;
6079 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006080 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 return res;
6082}
6083#endif
6084
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006085#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006086/* ${var/[/]pattern[/repl]} helpers */
6087static char *strstr_pattern(char *val, const char *pattern, int *size)
6088{
6089 while (1) {
6090 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6091 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6092 if (end) {
6093 *size = end - val;
6094 return val;
6095 }
6096 if (*val == '\0')
6097 return NULL;
6098 /* Optimization: if "*pat" did not match the start of "string",
6099 * we know that "tring", "ring" etc will not match too:
6100 */
6101 if (pattern[0] == '*')
6102 return NULL;
6103 val++;
6104 }
6105}
6106static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6107{
6108 char *result = NULL;
6109 unsigned res_len = 0;
6110 unsigned repl_len = strlen(repl);
6111
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006112 /* Null pattern never matches, including if "var" is empty */
6113 if (!pattern[0])
6114 return result; /* NULL, no replaces happened */
6115
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006116 while (1) {
6117 int size;
6118 char *s = strstr_pattern(val, pattern, &size);
6119 if (!s)
6120 break;
6121
6122 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006123 strcpy(mempcpy(result + res_len, val, s - val), repl);
6124 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006125 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6126
6127 val = s + size;
6128 if (exp_op == '/')
6129 break;
6130 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006131 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006132 result = xrealloc(result, res_len + strlen(val) + 1);
6133 strcpy(result + res_len, val);
6134 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6135 }
6136 debug_printf_varexp("result:'%s'\n", result);
6137 return result;
6138}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006139#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006140
Denys Vlasenko168579a2018-07-19 13:45:54 +02006141static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006142 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006143{
6144 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6145 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6146 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6147 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006148 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006149 } else { /* quoted "$VAR" */
6150 output->has_quoted_part = 1;
6151 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6152 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6153 if (val && val[0])
6154 o_addQstr(output, val);
6155 }
6156 return n;
6157}
6158
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006159/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006161static NOINLINE int expand_one_var(o_string *output, int n,
6162 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006163{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006164 const char *val;
6165 char *to_be_freed;
6166 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006167 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006168 char exp_op;
6169 char exp_save = exp_save; /* for compiler */
6170 char *exp_saveptr; /* points to expansion operator */
6171 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006172 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006173
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006174 val = NULL;
6175 to_be_freed = NULL;
6176 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006177 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006178 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006179 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006180 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006181 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182 exp_op = 0;
6183
Denys Vlasenkob762c782018-07-17 14:21:38 +02006184 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006185 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6186 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6187 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006188 ) {
6189 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006190 var++;
6191 exp_op = 'L';
6192 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006193 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006194 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006195 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006196 ) {
6197 /* ${?:0}, ${#[:]%0} etc */
6198 exp_saveptr = var + 1;
6199 } else {
6200 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6201 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6202 }
6203 exp_op = exp_save = *exp_saveptr;
6204 if (exp_op) {
6205 exp_word = exp_saveptr + 1;
6206 if (exp_op == ':') {
6207 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006208//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006209 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006210 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006211 ) {
6212 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6213 exp_op = ':';
6214 exp_word--;
6215 }
6216 }
6217 *exp_saveptr = '\0';
6218 } /* else: it's not an expansion op, but bare ${var} */
6219 }
6220
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006221 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006223 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006224 int nn = xatoi_positive(var);
6225 if (nn < G.global_argc)
6226 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006227 /* else val remains NULL: $N with too big N */
6228 } else {
6229 switch (var[0]) {
6230 case '$': /* pid */
6231 val = utoa(G.root_pid);
6232 break;
6233 case '!': /* bg pid */
6234 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6235 break;
6236 case '?': /* exitcode */
6237 val = utoa(G.last_exitcode);
6238 break;
6239 case '#': /* argc */
6240 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6241 break;
6242 default:
6243 val = get_local_var_value(var);
6244 }
6245 }
6246
6247 /* Handle any expansions */
6248 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006249 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006250 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006251 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006252 debug_printf_expand("%s\n", val);
6253 } else if (exp_op) {
6254 if (exp_op == '%' || exp_op == '#') {
6255 /* Standard-mandated substring removal ops:
6256 * ${parameter%word} - remove smallest suffix pattern
6257 * ${parameter%%word} - remove largest suffix pattern
6258 * ${parameter#word} - remove smallest prefix pattern
6259 * ${parameter##word} - remove largest prefix pattern
6260 *
6261 * Word is expanded to produce a glob pattern.
6262 * Then var's value is matched to it and matching part removed.
6263 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006264//FIXME: ${x#...${...}...}
6265//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6266//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006268 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006269 char *exp_exp_word;
6270 char *loc;
6271 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006272 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006273 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006274 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006275 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006276 if (exp_exp_word)
6277 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006278 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6279 /*
6280 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006281 * G.global_argv and results of utoa and get_local_var_value
6282 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006283 * scan_and_match momentarily stores NULs there.
6284 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006285 t = (char*)val;
6286 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006287 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 +02006288 free(exp_exp_word);
6289 if (loc) { /* match was found */
6290 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006291 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006292 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006293 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294 }
6295 }
6296 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006297#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006298 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006299 /* It's ${var/[/]pattern[/repl]} thing.
6300 * Note that in encoded form it has TWO parts:
6301 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006302 * and if // is used, it is encoded as \:
6303 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006304 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006305 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006306 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006307 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006308 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006309 * >az >bz
6310 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6311 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6312 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6313 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006314 * (note that a*z _pattern_ is never globbed!)
6315 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006317 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006318 if (!pattern)
6319 pattern = xstrdup(exp_word);
6320 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6321 *p++ = SPECIAL_VAR_SYMBOL;
6322 exp_word = p;
6323 p = strchr(p, SPECIAL_VAR_SYMBOL);
6324 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006325 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6327 /* HACK ALERT. We depend here on the fact that
6328 * G.global_argv and results of utoa and get_local_var_value
6329 * are actually in writable memory:
6330 * replace_pattern momentarily stores NULs there. */
6331 t = (char*)val;
6332 to_be_freed = replace_pattern(t,
6333 pattern,
6334 (repl ? repl : exp_word),
6335 exp_op);
6336 if (to_be_freed) /* at least one replace happened */
6337 val = to_be_freed;
6338 free(pattern);
6339 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006340 } else {
6341 /* Empty variable always gives nothing */
6342 // "v=''; echo ${v/*/w}" prints "", not "w"
6343 /* Just skip "replace" part */
6344 *p++ = SPECIAL_VAR_SYMBOL;
6345 p = strchr(p, SPECIAL_VAR_SYMBOL);
6346 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006347 }
6348 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006349#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006350 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006351#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352 /* It's ${var:N[:M]} bashism.
6353 * Note that in encoded form it has TWO parts:
6354 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6355 */
6356 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006357 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006358
Denys Vlasenko063847d2010-09-15 13:33:02 +02006359 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6360 if (errmsg)
6361 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006362 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6363 *p++ = SPECIAL_VAR_SYMBOL;
6364 exp_word = p;
6365 p = strchr(p, SPECIAL_VAR_SYMBOL);
6366 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006367 len = expand_and_evaluate_arith(exp_word, &errmsg);
6368 if (errmsg)
6369 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006370 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006371 if (beg < 0) {
6372 /* negative beg counts from the end */
6373 beg = (arith_t)strlen(val) + beg;
6374 if (beg < 0) /* ${v: -999999} is "" */
6375 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006376 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006377 debug_printf_varexp("from val:'%s'\n", val);
6378 if (len < 0) {
6379 /* in bash, len=-n means strlen()-n */
6380 len = (arith_t)strlen(val) - beg + len;
6381 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006382 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006383 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006384 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006385 arith_err:
6386 val = NULL;
6387 } else {
6388 /* Paranoia. What if user entered 9999999999999
6389 * which fits in arith_t but not int? */
6390 if (len >= INT_MAX)
6391 len = INT_MAX;
6392 val = to_be_freed = xstrndup(val + beg, len);
6393 }
6394 debug_printf_varexp("val:'%s'\n", val);
6395#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006396 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006397 val = NULL;
6398#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006399 } else { /* one of "-=+?" */
6400 /* Standard-mandated substitution ops:
6401 * ${var?word} - indicate error if unset
6402 * If var is unset, word (or a message indicating it is unset
6403 * if word is null) is written to standard error
6404 * and the shell exits with a non-zero exit status.
6405 * Otherwise, the value of var is substituted.
6406 * ${var-word} - use default value
6407 * If var is unset, word is substituted.
6408 * ${var=word} - assign and use default value
6409 * If var is unset, word is assigned to var.
6410 * In all cases, final value of var is substituted.
6411 * ${var+word} - use alternative value
6412 * If var is unset, null is substituted.
6413 * Otherwise, word is substituted.
6414 *
6415 * Word is subjected to tilde expansion, parameter expansion,
6416 * command substitution, and arithmetic expansion.
6417 * If word is not needed, it is not expanded.
6418 *
6419 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6420 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006421 *
6422 * Word-splitting and single quote behavior:
6423 *
6424 * $ f() { for i; do echo "|$i|"; done; };
6425 *
6426 * $ x=; f ${x:?'x y' z}
6427 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6428 * $ x=; f "${x:?'x y' z}"
6429 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6430 *
6431 * $ x=; f ${x:='x y' z}
6432 * |x|
6433 * |y|
6434 * |z|
6435 * $ x=; f "${x:='x y' z}"
6436 * |'x y' z|
6437 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006438 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006439 * |x y|
6440 * |z|
6441 * $ x=x; f "${x:+'x y' z}"
6442 * |'x y' z|
6443 *
6444 * $ x=; f ${x:-'x y' z}
6445 * |x y|
6446 * |z|
6447 * $ x=; f "${x:-'x y' z}"
6448 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006449 */
6450 int use_word = (!val || ((exp_save == ':') && !val[0]));
6451 if (exp_op == '+')
6452 use_word = !use_word;
6453 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6454 (exp_save == ':') ? "true" : "false", use_word);
6455 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006456 if (exp_op == '+' || exp_op == '-') {
6457 /* ${var+word} - use alternative value */
6458 /* ${var-word} - use default value */
6459 n = encode_then_append_var_plusminus(output, n, exp_word,
6460 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006461 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006462 val = NULL;
6463 } else {
6464 /* ${var?word} - indicate error if unset */
6465 /* ${var=word} - assign and use default value */
6466 to_be_freed = encode_then_expand_vararg(exp_word,
6467 /*handle_squotes:*/ !(arg0 & 0x80),
6468 /*unbackslash:*/ 0
6469 );
6470 if (to_be_freed)
6471 exp_word = to_be_freed;
6472 if (exp_op == '?') {
6473 /* mimic bash message */
6474 msg_and_die_if_script("%s: %s",
6475 var,
6476 exp_word[0]
6477 ? exp_word
6478 : "parameter null or not set"
6479 /* ash has more specific messages, a-la: */
6480 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6481 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006482//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006483//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006484// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6485// bash: x: x y z
6486// $
6487// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006489 val = exp_word;
6490 }
6491 if (exp_op == '=') {
6492 /* ${var=[word]} or ${var:=[word]} */
6493 if (isdigit(var[0]) || var[0] == '#') {
6494 /* mimic bash message */
6495 msg_and_die_if_script("$%s: cannot assign in this way", var);
6496 val = NULL;
6497 } else {
6498 char *new_var = xasprintf("%s=%s", var, val);
6499 set_local_var(new_var, /*flag:*/ 0);
6500 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006501 }
6502 }
6503 }
6504 } /* one of "-=+?" */
6505
6506 *exp_saveptr = exp_save;
6507 } /* if (exp_op) */
6508
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006509 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006510 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006511
Denys Vlasenko168579a2018-07-19 13:45:54 +02006512 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006513
6514 free(to_be_freed);
6515 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006516}
6517
6518/* Expand all variable references in given string, adding words to list[]
6519 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6520 * to be filled). This routine is extremely tricky: has to deal with
6521 * variables/parameters with whitespace, $* and $@, and constructs like
6522 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006523static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006524{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006525 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006527 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006528 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006529 char *p;
6530
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006531 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6532 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533 debug_print_list("expand_vars_to_list[0]", output, n);
6534
6535 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6536 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006537#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006538 char arith_buf[sizeof(arith_t)*3 + 2];
6539#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006540
Denys Vlasenko168579a2018-07-19 13:45:54 +02006541 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006542 o_addchr(output, '\0');
6543 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006544 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006545 }
6546
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006547 o_addblock(output, arg, p - arg);
6548 debug_print_list("expand_vars_to_list[1]", output, n);
6549 arg = ++p;
6550 p = strchr(p, SPECIAL_VAR_SYMBOL);
6551
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006552 /* Fetch special var name (if it is indeed one of them)
6553 * and quote bit, force the bit on if singleword expansion -
6554 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006555 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006556
6557 /* Is this variable quoted and thus expansion can't be null?
6558 * "$@" is special. Even if quoted, it can still
6559 * expand to nothing (not even an empty string),
6560 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006561 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006562 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006563
6564 switch (first_ch & 0x7f) {
6565 /* Highest bit in first_ch indicates that var is double-quoted */
6566 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006567 case '@': {
6568 int i;
6569 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006570 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006571 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006572 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006573 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006574 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006575 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006576 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6577 if (G.global_argv[i++][0] && G.global_argv[i]) {
6578 /* this argv[] is not empty and not last:
6579 * put terminating NUL, start new word */
6580 o_addchr(output, '\0');
6581 debug_print_list("expand_vars_to_list[2]", output, n);
6582 n = o_save_ptr(output, n);
6583 debug_print_list("expand_vars_to_list[3]", output, n);
6584 }
6585 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006587 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006588 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006589 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006590 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006591 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006592 while (1) {
6593 o_addQstr(output, G.global_argv[i]);
6594 if (++i >= G.global_argc)
6595 break;
6596 o_addchr(output, '\0');
6597 debug_print_list("expand_vars_to_list[4]", output, n);
6598 n = o_save_ptr(output, n);
6599 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006600 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006601 while (1) {
6602 o_addQstr(output, G.global_argv[i]);
6603 if (!G.global_argv[++i])
6604 break;
6605 if (G.ifs[0])
6606 o_addchr(output, G.ifs[0]);
6607 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006608 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006609 }
6610 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006611 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006612 case SPECIAL_VAR_SYMBOL: {
6613 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006614 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006615 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006616 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006617 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006619 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006620 case SPECIAL_VAR_QUOTED_SVS:
6621 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006622 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006623 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006624 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006625 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006626#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006627 case '`': {
6628 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006629 o_string subst_result = NULL_O_STRING;
6630
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006631 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006632 arg++;
6633 /* Can't just stuff it into output o_string,
6634 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006635 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006636 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6637 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006638 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006639 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006640 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006641 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006642 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006643 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006644#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006645#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006646 case '+': {
6647 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006648 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649
6650 arg++; /* skip '+' */
6651 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6652 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006653 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006654 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6655 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006656 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006657 break;
6658 }
6659#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006660 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006661 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006662 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006663 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006664 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6665
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006666 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6667 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006668 if (*p != SPECIAL_VAR_SYMBOL)
6669 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006670 arg = ++p;
6671 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6672
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006673 if (*arg) {
6674 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006675 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006676 o_addchr(output, '\0');
6677 n = o_save_ptr(output, n);
6678 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006679 debug_print_list("expand_vars_to_list[a]", output, n);
6680 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006681 * if needed (much earlier), do not use o_addQstr here!
6682 */
6683 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006684 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006685 } else
6686 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006687 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6688 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 ) {
6690 n--;
6691 /* allow to reuse list[n] later without re-growth */
6692 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 }
6694
6695 return n;
6696}
6697
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006698static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006699{
6700 int n;
6701 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006702 o_string output = NULL_O_STRING;
6703
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006704 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006705
6706 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006707 for (;;) {
6708 /* go to next list[n] */
6709 output.ended_in_ifs = 0;
6710 n = o_save_ptr(&output, n);
6711
6712 if (!*argv)
6713 break;
6714
6715 /* expand argv[i] */
6716 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006717 /* if (!output->has_empty_slot) -- need this?? */
6718 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006719 }
6720 debug_print_list("expand_variables", &output, n);
6721
6722 /* output.data (malloced in one block) gets returned in "list" */
6723 list = o_finalize_list(&output, n);
6724 debug_print_strings("expand_variables[1]", list);
6725 return list;
6726}
6727
6728static char **expand_strvec_to_strvec(char **argv)
6729{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006730 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006731}
6732
Denys Vlasenko11752d42018-04-03 08:20:58 +02006733#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006734static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6735{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006736 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006737}
6738#endif
6739
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006740/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006741 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006742 *
6743 * NB: should NOT do globbing!
6744 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6745 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006746static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006747{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006748#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006749 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006750 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006751#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006752 char *argv[2], **list;
6753
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006754 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006755 /* This is generally an optimization, but it also
6756 * handles "", which otherwise trips over !list[0] check below.
6757 * (is this ever happens that we actually get str="" here?)
6758 */
6759 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6760 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006761 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762 return xstrdup(str);
6763 }
6764
6765 argv[0] = (char*)str;
6766 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006767 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006768 if (!list[0]) {
6769 /* Example where it happens:
6770 * x=; echo ${x:-"$@"}
6771 */
6772 ((char*)list)[0] = '\0';
6773 } else {
6774 if (HUSH_DEBUG)
6775 if (list[1])
6776 bb_error_msg_and_die("BUG in varexp2");
6777 /* actually, just move string 2*sizeof(char*) bytes back */
6778 overlapping_strcpy((char*)list, list[0]);
6779 if (do_unbackslash)
6780 unbackslash((char*)list);
6781 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006782 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006783 return (char*)list;
6784}
6785
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006786#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006787static char* expand_strvec_to_string(char **argv)
6788{
6789 char **list;
6790
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006791 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792 /* Convert all NULs to spaces */
6793 if (list[0]) {
6794 int n = 1;
6795 while (list[n]) {
6796 if (HUSH_DEBUG)
6797 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6798 bb_error_msg_and_die("BUG in varexp3");
6799 /* bash uses ' ' regardless of $IFS contents */
6800 list[n][-1] = ' ';
6801 n++;
6802 }
6803 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006804 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006805 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6806 return (char*)list;
6807}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006808#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809
6810static char **expand_assignments(char **argv, int count)
6811{
6812 int i;
6813 char **p;
6814
6815 G.expanded_assignments = p = NULL;
6816 /* Expand assignments into one string each */
6817 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006818 p = add_string_to_strings(p,
6819 expand_string_to_string(argv[i],
6820 EXP_FLAG_ESC_GLOB_CHARS,
6821 /*unbackslash:*/ 1
6822 )
6823 );
6824 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006825 }
6826 G.expanded_assignments = NULL;
6827 return p;
6828}
6829
6830
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006831static void switch_off_special_sigs(unsigned mask)
6832{
6833 unsigned sig = 0;
6834 while ((mask >>= 1) != 0) {
6835 sig++;
6836 if (!(mask & 1))
6837 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006838#if ENABLE_HUSH_TRAP
6839 if (G_traps) {
6840 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006841 /* trap is '', has to remain SIG_IGN */
6842 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006843 free(G_traps[sig]);
6844 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006845 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006846#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006847 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006848 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006849 }
6850}
6851
Denys Vlasenkob347df92011-08-09 22:49:15 +02006852#if BB_MMU
6853/* never called */
6854void re_execute_shell(char ***to_free, const char *s,
6855 char *g_argv0, char **g_argv,
6856 char **builtin_argv) NORETURN;
6857
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006858static void reset_traps_to_defaults(void)
6859{
6860 /* This function is always called in a child shell
6861 * after fork (not vfork, NOMMU doesn't use this function).
6862 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006863 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006864 unsigned mask;
6865
6866 /* Child shells are not interactive.
6867 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6868 * Testcase: (while :; do :; done) + ^Z should background.
6869 * Same goes for SIGTERM, SIGHUP, SIGINT.
6870 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006871 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006872 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006873 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006874
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006875 /* Switch off special sigs */
6876 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006877# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006878 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006879# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006880 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006881 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6882 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006883
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006884# if ENABLE_HUSH_TRAP
6885 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006886 return;
6887
6888 /* Reset all sigs to default except ones with empty traps */
6889 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006890 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006891 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006892 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006893 continue; /* empty trap: has to remain SIG_IGN */
6894 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006895 free(G_traps[sig]);
6896 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006897 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006898 if (sig == 0)
6899 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006900 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006901 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006902# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006903}
6904
6905#else /* !BB_MMU */
6906
6907static void re_execute_shell(char ***to_free, const char *s,
6908 char *g_argv0, char **g_argv,
6909 char **builtin_argv) NORETURN;
6910static void re_execute_shell(char ***to_free, const char *s,
6911 char *g_argv0, char **g_argv,
6912 char **builtin_argv)
6913{
6914# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6915 /* delims + 2 * (number of bytes in printed hex numbers) */
6916 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6917 char *heredoc_argv[4];
6918 struct variable *cur;
6919# if ENABLE_HUSH_FUNCTIONS
6920 struct function *funcp;
6921# endif
6922 char **argv, **pp;
6923 unsigned cnt;
6924 unsigned long long empty_trap_mask;
6925
6926 if (!g_argv0) { /* heredoc */
6927 argv = heredoc_argv;
6928 argv[0] = (char *) G.argv0_for_re_execing;
6929 argv[1] = (char *) "-<";
6930 argv[2] = (char *) s;
6931 argv[3] = NULL;
6932 pp = &argv[3]; /* used as pointer to empty environment */
6933 goto do_exec;
6934 }
6935
6936 cnt = 0;
6937 pp = builtin_argv;
6938 if (pp) while (*pp++)
6939 cnt++;
6940
6941 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006942 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006943 int sig;
6944 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006945 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006946 empty_trap_mask |= 1LL << sig;
6947 }
6948 }
6949
6950 sprintf(param_buf, NOMMU_HACK_FMT
6951 , (unsigned) G.root_pid
6952 , (unsigned) G.root_ppid
6953 , (unsigned) G.last_bg_pid
6954 , (unsigned) G.last_exitcode
6955 , cnt
6956 , empty_trap_mask
6957 IF_HUSH_LOOPS(, G.depth_of_loop)
6958 );
6959# undef NOMMU_HACK_FMT
6960 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6961 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6962 */
6963 cnt += 6;
6964 for (cur = G.top_var; cur; cur = cur->next) {
6965 if (!cur->flg_export || cur->flg_read_only)
6966 cnt += 2;
6967 }
6968# if ENABLE_HUSH_FUNCTIONS
6969 for (funcp = G.top_func; funcp; funcp = funcp->next)
6970 cnt += 3;
6971# endif
6972 pp = g_argv;
6973 while (*pp++)
6974 cnt++;
6975 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6976 *pp++ = (char *) G.argv0_for_re_execing;
6977 *pp++ = param_buf;
6978 for (cur = G.top_var; cur; cur = cur->next) {
6979 if (strcmp(cur->varstr, hush_version_str) == 0)
6980 continue;
6981 if (cur->flg_read_only) {
6982 *pp++ = (char *) "-R";
6983 *pp++ = cur->varstr;
6984 } else if (!cur->flg_export) {
6985 *pp++ = (char *) "-V";
6986 *pp++ = cur->varstr;
6987 }
6988 }
6989# if ENABLE_HUSH_FUNCTIONS
6990 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6991 *pp++ = (char *) "-F";
6992 *pp++ = funcp->name;
6993 *pp++ = funcp->body_as_string;
6994 }
6995# endif
6996 /* We can pass activated traps here. Say, -Tnn:trap_string
6997 *
6998 * However, POSIX says that subshells reset signals with traps
6999 * to SIG_DFL.
7000 * I tested bash-3.2 and it not only does that with true subshells
7001 * of the form ( list ), but with any forked children shells.
7002 * I set trap "echo W" WINCH; and then tried:
7003 *
7004 * { echo 1; sleep 20; echo 2; } &
7005 * while true; do echo 1; sleep 20; echo 2; break; done &
7006 * true | { echo 1; sleep 20; echo 2; } | cat
7007 *
7008 * In all these cases sending SIGWINCH to the child shell
7009 * did not run the trap. If I add trap "echo V" WINCH;
7010 * _inside_ group (just before echo 1), it works.
7011 *
7012 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007013 */
7014 *pp++ = (char *) "-c";
7015 *pp++ = (char *) s;
7016 if (builtin_argv) {
7017 while (*++builtin_argv)
7018 *pp++ = *builtin_argv;
7019 *pp++ = (char *) "";
7020 }
7021 *pp++ = g_argv0;
7022 while (*g_argv)
7023 *pp++ = *g_argv++;
7024 /* *pp = NULL; - is already there */
7025 pp = environ;
7026
7027 do_exec:
7028 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007029 /* Don't propagate SIG_IGN to the child */
7030 if (SPECIAL_JOBSTOP_SIGS != 0)
7031 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007032 execve(bb_busybox_exec_path, argv, pp);
7033 /* Fallback. Useful for init=/bin/hush usage etc */
7034 if (argv[0][0] == '/')
7035 execve(argv[0], argv, pp);
7036 xfunc_error_retval = 127;
7037 bb_error_msg_and_die("can't re-execute the shell");
7038}
7039#endif /* !BB_MMU */
7040
7041
7042static int run_and_free_list(struct pipe *pi);
7043
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007044/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007045 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7046 * end_trigger controls how often we stop parsing
7047 * NUL: parse all, execute, return
7048 * ';': parse till ';' or newline, execute, repeat till EOF
7049 */
7050static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007051{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007052 /* Why we need empty flag?
7053 * An obscure corner case "false; ``; echo $?":
7054 * empty command in `` should still set $? to 0.
7055 * But we can't just set $? to 0 at the start,
7056 * this breaks "false; echo `echo $?`" case.
7057 */
7058 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007059 while (1) {
7060 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007061
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007062#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007063 if (end_trigger == ';') {
7064 G.promptmode = 0; /* PS1 */
7065 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7066 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007067#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007068 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007069 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7070 /* If we are in "big" script
7071 * (not in `cmd` or something similar)...
7072 */
7073 if (pipe_list == ERR_PTR && end_trigger == ';') {
7074 /* Discard cached input (rest of line) */
7075 int ch = inp->last_char;
7076 while (ch != EOF && ch != '\n') {
7077 //bb_error_msg("Discarded:'%c'", ch);
7078 ch = i_getch(inp);
7079 }
7080 /* Force prompt */
7081 inp->p = NULL;
7082 /* This stream isn't empty */
7083 empty = 0;
7084 continue;
7085 }
7086 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007087 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007088 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007089 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007090 debug_print_tree(pipe_list, 0);
7091 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7092 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007093 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007094 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007095 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007096 }
Eric Andersen25f27032001-04-26 23:22:31 +00007097}
7098
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007099static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007100{
7101 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007102 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7103
Eric Andersen25f27032001-04-26 23:22:31 +00007104 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007105 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007106 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007107}
7108
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007109static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007110{
Eric Andersen25f27032001-04-26 23:22:31 +00007111 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007112 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007113
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007114 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01007115 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007116 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007117 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007118}
7119
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007120#if ENABLE_HUSH_TICK
7121static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
7122{
7123 pid_t pid;
7124 int channel[2];
7125# if !BB_MMU
7126 char **to_free = NULL;
7127# endif
7128
7129 xpipe(channel);
7130 pid = BB_MMU ? xfork() : xvfork();
7131 if (pid == 0) { /* child */
7132 disable_restore_tty_pgrp_on_exit();
7133 /* Process substitution is not considered to be usual
7134 * 'command execution'.
7135 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7136 */
7137 bb_signals(0
7138 + (1 << SIGTSTP)
7139 + (1 << SIGTTIN)
7140 + (1 << SIGTTOU)
7141 , SIG_IGN);
7142 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7143 close(channel[0]); /* NB: close _first_, then move fd! */
7144 xmove_fd(channel[1], 1);
7145 /* Prevent it from trying to handle ctrl-z etc */
7146 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007147# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007148 /* Awful hack for `trap` or $(trap).
7149 *
7150 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7151 * contains an example where "trap" is executed in a subshell:
7152 *
7153 * save_traps=$(trap)
7154 * ...
7155 * eval "$save_traps"
7156 *
7157 * Standard does not say that "trap" in subshell shall print
7158 * parent shell's traps. It only says that its output
7159 * must have suitable form, but then, in the above example
7160 * (which is not supposed to be normative), it implies that.
7161 *
7162 * bash (and probably other shell) does implement it
7163 * (traps are reset to defaults, but "trap" still shows them),
7164 * but as a result, "trap" logic is hopelessly messed up:
7165 *
7166 * # trap
7167 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7168 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7169 * # true | trap <--- trap is in subshell - no output (ditto)
7170 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7171 * trap -- 'echo Ho' SIGWINCH
7172 * # echo `(trap)` <--- in subshell in subshell - output
7173 * trap -- 'echo Ho' SIGWINCH
7174 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7175 * trap -- 'echo Ho' SIGWINCH
7176 *
7177 * The rules when to forget and when to not forget traps
7178 * get really complex and nonsensical.
7179 *
7180 * Our solution: ONLY bare $(trap) or `trap` is special.
7181 */
7182 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007183 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184 && skip_whitespace(s + 4)[0] == '\0'
7185 ) {
7186 static const char *const argv[] = { NULL, NULL };
7187 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007188 fflush_all(); /* important */
7189 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007190 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007191# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007192# if BB_MMU
7193 reset_traps_to_defaults();
7194 parse_and_run_string(s);
7195 _exit(G.last_exitcode);
7196# else
7197 /* We re-execute after vfork on NOMMU. This makes this script safe:
7198 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7199 * huge=`cat BIG` # was blocking here forever
7200 * echo OK
7201 */
7202 re_execute_shell(&to_free,
7203 s,
7204 G.global_argv[0],
7205 G.global_argv + 1,
7206 NULL);
7207# endif
7208 }
7209
7210 /* parent */
7211 *pid_p = pid;
7212# if ENABLE_HUSH_FAST
7213 G.count_SIGCHLD++;
7214//bb_error_msg("[%d] fork in generate_stream_from_string:"
7215// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7216// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7217# endif
7218 enable_restore_tty_pgrp_on_exit();
7219# if !BB_MMU
7220 free(to_free);
7221# endif
7222 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007223 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007224}
7225
7226/* Return code is exit status of the process that is run. */
7227static int process_command_subs(o_string *dest, const char *s)
7228{
7229 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007230 pid_t pid;
7231 int status, ch, eol_cnt;
7232
7233 fp = generate_stream_from_string(s, &pid);
7234
7235 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007236 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007237 while ((ch = getc(fp)) != EOF) {
7238 if (ch == '\0')
7239 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007240 if (ch == '\n') {
7241 eol_cnt++;
7242 continue;
7243 }
7244 while (eol_cnt) {
7245 o_addchr(dest, '\n');
7246 eol_cnt--;
7247 }
7248 o_addQchr(dest, ch);
7249 }
7250
7251 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007252 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007253 /* We need to extract exitcode. Test case
7254 * "true; echo `sleep 1; false` $?"
7255 * should print 1 */
7256 safe_waitpid(pid, &status, 0);
7257 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7258 return WEXITSTATUS(status);
7259}
7260#endif /* ENABLE_HUSH_TICK */
7261
7262
7263static void setup_heredoc(struct redir_struct *redir)
7264{
7265 struct fd_pair pair;
7266 pid_t pid;
7267 int len, written;
7268 /* the _body_ of heredoc (misleading field name) */
7269 const char *heredoc = redir->rd_filename;
7270 char *expanded;
7271#if !BB_MMU
7272 char **to_free;
7273#endif
7274
7275 expanded = NULL;
7276 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007277 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007278 if (expanded)
7279 heredoc = expanded;
7280 }
7281 len = strlen(heredoc);
7282
7283 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7284 xpiped_pair(pair);
7285 xmove_fd(pair.rd, redir->rd_fd);
7286
7287 /* Try writing without forking. Newer kernels have
7288 * dynamically growing pipes. Must use non-blocking write! */
7289 ndelay_on(pair.wr);
7290 while (1) {
7291 written = write(pair.wr, heredoc, len);
7292 if (written <= 0)
7293 break;
7294 len -= written;
7295 if (len == 0) {
7296 close(pair.wr);
7297 free(expanded);
7298 return;
7299 }
7300 heredoc += written;
7301 }
7302 ndelay_off(pair.wr);
7303
7304 /* Okay, pipe buffer was not big enough */
7305 /* Note: we must not create a stray child (bastard? :)
7306 * for the unsuspecting parent process. Child creates a grandchild
7307 * and exits before parent execs the process which consumes heredoc
7308 * (that exec happens after we return from this function) */
7309#if !BB_MMU
7310 to_free = NULL;
7311#endif
7312 pid = xvfork();
7313 if (pid == 0) {
7314 /* child */
7315 disable_restore_tty_pgrp_on_exit();
7316 pid = BB_MMU ? xfork() : xvfork();
7317 if (pid != 0)
7318 _exit(0);
7319 /* grandchild */
7320 close(redir->rd_fd); /* read side of the pipe */
7321#if BB_MMU
7322 full_write(pair.wr, heredoc, len); /* may loop or block */
7323 _exit(0);
7324#else
7325 /* Delegate blocking writes to another process */
7326 xmove_fd(pair.wr, STDOUT_FILENO);
7327 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7328#endif
7329 }
7330 /* parent */
7331#if ENABLE_HUSH_FAST
7332 G.count_SIGCHLD++;
7333//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7334#endif
7335 enable_restore_tty_pgrp_on_exit();
7336#if !BB_MMU
7337 free(to_free);
7338#endif
7339 close(pair.wr);
7340 free(expanded);
7341 wait(NULL); /* wait till child has died */
7342}
7343
Denys Vlasenko2db74612017-07-07 22:07:28 +02007344struct squirrel {
7345 int orig_fd;
7346 int moved_to;
7347 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7348 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7349};
7350
Denys Vlasenko621fc502017-07-24 12:42:17 +02007351static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7352{
7353 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7354 sq[i].orig_fd = orig;
7355 sq[i].moved_to = moved;
7356 sq[i+1].orig_fd = -1; /* end marker */
7357 return sq;
7358}
7359
Denys Vlasenko2db74612017-07-07 22:07:28 +02007360static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7361{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007362 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007363 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007364
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007365 i = 0;
7366 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007367 /* If we collide with an already moved fd... */
7368 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007369 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007370 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7371 if (sq[i].moved_to < 0) /* what? */
7372 xfunc_die();
7373 return sq;
7374 }
7375 if (fd == sq[i].orig_fd) {
7376 /* Example: echo Hello >/dev/null 1>&2 */
7377 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7378 return sq;
7379 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007380 }
7381
Denys Vlasenko2db74612017-07-07 22:07:28 +02007382 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007383 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007384 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7385 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007386 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007387 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007388}
7389
Denys Vlasenko657e9002017-07-30 23:34:04 +02007390static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7391{
7392 int i;
7393
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007394 i = 0;
7395 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007396 /* If we collide with an already moved fd... */
7397 if (fd == sq[i].orig_fd) {
7398 /* Examples:
7399 * "echo 3>FILE 3>&- 3>FILE"
7400 * "echo 3>&- 3>FILE"
7401 * No need for last redirect to insert
7402 * another "need to close 3" indicator.
7403 */
7404 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7405 return sq;
7406 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007407 }
7408
7409 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7410 return append_squirrel(sq, i, fd, -1);
7411}
7412
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007413/* fd: redirect wants this fd to be used (e.g. 3>file).
7414 * Move all conflicting internally used fds,
7415 * and remember them so that we can restore them later.
7416 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007417static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007418{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007419 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7420 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007421
7422#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007423 if (fd == G.interactive_fd) {
7424 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007425 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007426 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7427 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007428 }
7429#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007430 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7431 * (1) Redirect in a forked child. No need to save FILEs' fds,
7432 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007433 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7434 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007435 * "fileno(fd) = new_fd" can't be done.
7436 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007437 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007438 return 0;
7439
Denys Vlasenko2db74612017-07-07 22:07:28 +02007440 /* If this one of script's fds? */
7441 if (save_FILEs_on_redirect(fd, avoid_fd))
7442 return 1; /* yes. "we closed fd" */
7443
7444 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7445 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7446 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007447}
7448
Denys Vlasenko2db74612017-07-07 22:07:28 +02007449static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007450{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007451 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007452 int i;
7453 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007454 if (sq[i].moved_to >= 0) {
7455 /* We simply die on error */
7456 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7457 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7458 } else {
7459 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7460 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7461 close(sq[i].orig_fd);
7462 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007463 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007464 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007465 }
7466
Denys Vlasenko2db74612017-07-07 22:07:28 +02007467 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007468
7469 restore_redirected_FILEs();
7470}
7471
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007472#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007473static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007474{
7475 if (G_interactive_fd)
7476 close(G_interactive_fd);
7477 close_all_FILE_list();
7478}
7479#endif
7480
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007481static int internally_opened_fd(int fd, struct squirrel *sq)
7482{
7483 int i;
7484
7485#if ENABLE_HUSH_INTERACTIVE
7486 if (fd == G.interactive_fd)
7487 return 1;
7488#endif
7489 /* If this one of script's fds? */
7490 if (fd_in_FILEs(fd))
7491 return 1;
7492
7493 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7494 if (fd == sq[i].moved_to)
7495 return 1;
7496 }
7497 return 0;
7498}
7499
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007500/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7501 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007502static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007503{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007504 struct redir_struct *redir;
7505
7506 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007507 int newfd;
7508 int closed;
7509
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007510 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007511 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007512 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007513 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7514 * of the heredoc */
7515 debug_printf_parse("set heredoc '%s'\n",
7516 redir->rd_filename);
7517 setup_heredoc(redir);
7518 continue;
7519 }
7520
7521 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007522 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007523 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007524 int mode;
7525
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007526 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007527 /*
7528 * Examples:
7529 * "cmd >" (no filename)
7530 * "cmd > <file" (2nd redirect starts too early)
7531 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007532 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007533 continue;
7534 }
7535 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007536 p = expand_string_to_string(redir->rd_filename,
7537 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007538 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007539 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007540 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007541 /* Error message from open_or_warn can be lost
7542 * if stderr has been redirected, but bash
7543 * and ash both lose it as well
7544 * (though zsh doesn't!)
7545 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007546 return 1;
7547 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007548 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007549 /* open() gave us precisely the fd we wanted.
7550 * This means that this fd was not busy
7551 * (not opened to anywhere).
7552 * Remember to close it on restore:
7553 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007554 *sqp = add_squirrel_closed(*sqp, newfd);
7555 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007556 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007557 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007558 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7559 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007560 }
7561
Denys Vlasenko657e9002017-07-30 23:34:04 +02007562 if (newfd == redir->rd_fd)
7563 continue;
7564
7565 /* if "N>FILE": move newfd to redir->rd_fd */
7566 /* if "N>&M": dup newfd to redir->rd_fd */
7567 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7568
7569 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7570 if (newfd == REDIRFD_CLOSE) {
7571 /* "N>&-" means "close me" */
7572 if (!closed) {
7573 /* ^^^ optimization: saving may already
7574 * have closed it. If not... */
7575 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007576 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007577 /* Sometimes we do another close on restore, getting EBADF.
7578 * Consider "echo 3>FILE 3>&-"
7579 * first redirect remembers "need to close 3",
7580 * and second redirect closes 3! Restore code then closes 3 again.
7581 */
7582 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007583 /* if newfd is a script fd or saved fd, simulate EBADF */
7584 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7585 //errno = EBADF;
7586 //bb_perror_msg_and_die("can't duplicate file descriptor");
7587 newfd = -1; /* same effect as code above */
7588 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007589 xdup2(newfd, redir->rd_fd);
7590 if (redir->rd_dup == REDIRFD_TO_FILE)
7591 /* "rd_fd > FILE" */
7592 close(newfd);
7593 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007594 }
7595 }
7596 return 0;
7597}
7598
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007599static char *find_in_path(const char *arg)
7600{
7601 char *ret = NULL;
7602 const char *PATH = get_local_var_value("PATH");
7603
7604 if (!PATH)
7605 return NULL;
7606
7607 while (1) {
7608 const char *end = strchrnul(PATH, ':');
7609 int sz = end - PATH; /* must be int! */
7610
7611 free(ret);
7612 if (sz != 0) {
7613 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7614 } else {
7615 /* We have xxx::yyyy in $PATH,
7616 * it means "use current dir" */
7617 ret = xstrdup(arg);
7618 }
7619 if (access(ret, F_OK) == 0)
7620 break;
7621
7622 if (*end == '\0') {
7623 free(ret);
7624 return NULL;
7625 }
7626 PATH = end + 1;
7627 }
7628
7629 return ret;
7630}
7631
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007632static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007633 const struct built_in_command *x,
7634 const struct built_in_command *end)
7635{
7636 while (x != end) {
7637 if (strcmp(name, x->b_cmd) != 0) {
7638 x++;
7639 continue;
7640 }
7641 debug_printf_exec("found builtin '%s'\n", name);
7642 return x;
7643 }
7644 return NULL;
7645}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007646static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007647{
7648 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7649}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007650static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007651{
7652 const struct built_in_command *x = find_builtin1(name);
7653 if (x)
7654 return x;
7655 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7656}
7657
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007658static void remove_nested_vars(void)
7659{
7660 struct variable *cur;
7661 struct variable **cur_pp;
7662
7663 cur_pp = &G.top_var;
7664 while ((cur = *cur_pp) != NULL) {
7665 if (cur->var_nest_level <= G.var_nest_level) {
7666 cur_pp = &cur->next;
7667 continue;
7668 }
7669 /* Unexport */
7670 if (cur->flg_export) {
7671 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7672 bb_unsetenv(cur->varstr);
7673 }
7674 /* Remove from global list */
7675 *cur_pp = cur->next;
7676 /* Free */
7677 if (!cur->max_len) {
7678 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7679 free(cur->varstr);
7680 }
7681 free(cur);
7682 }
7683}
7684
7685static void enter_var_nest_level(void)
7686{
7687 G.var_nest_level++;
7688 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7689
7690 /* Try: f() { echo -n .; f; }; f
7691 * struct variable::var_nest_level is uint16_t,
7692 * thus limiting recursion to < 2^16.
7693 * In any case, with 8 Mbyte stack SEGV happens
7694 * not too long after 2^16 recursions anyway.
7695 */
7696 if (G.var_nest_level > 0xff00)
7697 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7698}
7699
7700static void leave_var_nest_level(void)
7701{
7702 G.var_nest_level--;
7703 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7704 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7705 bb_error_msg_and_die("BUG: nesting underflow");
7706
7707 remove_nested_vars();
7708}
7709
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007710#if ENABLE_HUSH_FUNCTIONS
7711static struct function **find_function_slot(const char *name)
7712{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007713 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007714 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007715
7716 while ((funcp = *funcpp) != NULL) {
7717 if (strcmp(name, funcp->name) == 0) {
7718 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007719 break;
7720 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007721 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007722 }
7723 return funcpp;
7724}
7725
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007726static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007727{
7728 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007729 return funcp;
7730}
7731
7732/* Note: takes ownership on name ptr */
7733static struct function *new_function(char *name)
7734{
7735 struct function **funcpp = find_function_slot(name);
7736 struct function *funcp = *funcpp;
7737
7738 if (funcp != NULL) {
7739 struct command *cmd = funcp->parent_cmd;
7740 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7741 if (!cmd) {
7742 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7743 free(funcp->name);
7744 /* Note: if !funcp->body, do not free body_as_string!
7745 * This is a special case of "-F name body" function:
7746 * body_as_string was not malloced! */
7747 if (funcp->body) {
7748 free_pipe_list(funcp->body);
7749# if !BB_MMU
7750 free(funcp->body_as_string);
7751# endif
7752 }
7753 } else {
7754 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7755 cmd->argv[0] = funcp->name;
7756 cmd->group = funcp->body;
7757# if !BB_MMU
7758 cmd->group_as_string = funcp->body_as_string;
7759# endif
7760 }
7761 } else {
7762 debug_printf_exec("remembering new function '%s'\n", name);
7763 funcp = *funcpp = xzalloc(sizeof(*funcp));
7764 /*funcp->next = NULL;*/
7765 }
7766
7767 funcp->name = name;
7768 return funcp;
7769}
7770
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007771# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007772static void unset_func(const char *name)
7773{
7774 struct function **funcpp = find_function_slot(name);
7775 struct function *funcp = *funcpp;
7776
7777 if (funcp != NULL) {
7778 debug_printf_exec("freeing function '%s'\n", funcp->name);
7779 *funcpp = funcp->next;
7780 /* funcp is unlinked now, deleting it.
7781 * Note: if !funcp->body, the function was created by
7782 * "-F name body", do not free ->body_as_string
7783 * and ->name as they were not malloced. */
7784 if (funcp->body) {
7785 free_pipe_list(funcp->body);
7786 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007787# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007788 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007789# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007790 }
7791 free(funcp);
7792 }
7793}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007794# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007795
7796# if BB_MMU
7797#define exec_function(to_free, funcp, argv) \
7798 exec_function(funcp, argv)
7799# endif
7800static void exec_function(char ***to_free,
7801 const struct function *funcp,
7802 char **argv) NORETURN;
7803static void exec_function(char ***to_free,
7804 const struct function *funcp,
7805 char **argv)
7806{
7807# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007808 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007809
7810 argv[0] = G.global_argv[0];
7811 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007812 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007813
7814// Example when we are here: "cmd | func"
7815// func will run with saved-redirect fds open.
7816// $ f() { echo /proc/self/fd/*; }
7817// $ true | f
7818// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7819// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7820// Same in script:
7821// $ . ./SCRIPT
7822// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7823// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7824// They are CLOEXEC so external programs won't see them, but
7825// for "more correctness" we might want to close those extra fds here:
7826//? close_saved_fds_and_FILE_fds();
7827
Denys Vlasenko332e4112018-04-04 22:32:59 +02007828 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007829 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007830 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007831 IF_HUSH_LOCAL(G.func_nest_level++;)
7832
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007833 /* On MMU, funcp->body is always non-NULL */
7834 n = run_list(funcp->body);
7835 fflush_all();
7836 _exit(n);
7837# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007838//? close_saved_fds_and_FILE_fds();
7839
7840//TODO: check whether "true | func_with_return" works
7841
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007842 re_execute_shell(to_free,
7843 funcp->body_as_string,
7844 G.global_argv[0],
7845 argv + 1,
7846 NULL);
7847# endif
7848}
7849
7850static int run_function(const struct function *funcp, char **argv)
7851{
7852 int rc;
7853 save_arg_t sv;
7854 smallint sv_flg;
7855
7856 save_and_replace_G_args(&sv, argv);
7857
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007858 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007859 sv_flg = G_flag_return_in_progress;
7860 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007861
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007862 /* Make "local" variables properly shadow previous ones */
7863 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007864 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007865
7866 /* On MMU, funcp->body is always non-NULL */
7867# if !BB_MMU
7868 if (!funcp->body) {
7869 /* Function defined by -F */
7870 parse_and_run_string(funcp->body_as_string);
7871 rc = G.last_exitcode;
7872 } else
7873# endif
7874 {
7875 rc = run_list(funcp->body);
7876 }
7877
Denys Vlasenko332e4112018-04-04 22:32:59 +02007878 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007879 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007880
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007881 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007882
7883 restore_G_args(&sv, argv);
7884
7885 return rc;
7886}
7887#endif /* ENABLE_HUSH_FUNCTIONS */
7888
7889
7890#if BB_MMU
7891#define exec_builtin(to_free, x, argv) \
7892 exec_builtin(x, argv)
7893#else
7894#define exec_builtin(to_free, x, argv) \
7895 exec_builtin(to_free, argv)
7896#endif
7897static void exec_builtin(char ***to_free,
7898 const struct built_in_command *x,
7899 char **argv) NORETURN;
7900static void exec_builtin(char ***to_free,
7901 const struct built_in_command *x,
7902 char **argv)
7903{
7904#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007905 int rcode;
7906 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007907//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007908 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007909 fflush_all();
7910 _exit(rcode);
7911#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007912 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007913 /* On NOMMU, we must never block!
7914 * Example: { sleep 99 | read line; } & echo Ok
7915 */
7916 re_execute_shell(to_free,
7917 argv[0],
7918 G.global_argv[0],
7919 G.global_argv + 1,
7920 argv);
7921#endif
7922}
7923
7924
7925static void execvp_or_die(char **argv) NORETURN;
7926static void execvp_or_die(char **argv)
7927{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007928 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007929 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007930 /* Don't propagate SIG_IGN to the child */
7931 if (SPECIAL_JOBSTOP_SIGS != 0)
7932 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007933 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007934 e = 2;
7935 if (errno == EACCES) e = 126;
7936 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007937 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007938 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007939}
7940
7941#if ENABLE_HUSH_MODE_X
7942static void dump_cmd_in_x_mode(char **argv)
7943{
7944 if (G_x_mode && argv) {
7945 /* We want to output the line in one write op */
7946 char *buf, *p;
7947 int len;
7948 int n;
7949
7950 len = 3;
7951 n = 0;
7952 while (argv[n])
7953 len += strlen(argv[n++]) + 1;
7954 buf = xmalloc(len);
7955 buf[0] = '+';
7956 p = buf + 1;
7957 n = 0;
7958 while (argv[n])
7959 p += sprintf(p, " %s", argv[n++]);
7960 *p++ = '\n';
7961 *p = '\0';
7962 fputs(buf, stderr);
7963 free(buf);
7964 }
7965}
7966#else
7967# define dump_cmd_in_x_mode(argv) ((void)0)
7968#endif
7969
Denys Vlasenko57000292018-01-12 14:41:45 +01007970#if ENABLE_HUSH_COMMAND
7971static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7972{
7973 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007974
Denys Vlasenko57000292018-01-12 14:41:45 +01007975 if (!opt_vV)
7976 return;
7977
7978 to_free = NULL;
7979 if (!explanation) {
7980 char *path = getenv("PATH");
7981 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007982 if (!explanation)
7983 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007984 if (opt_vV != 'V')
7985 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7986 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007987 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007988 free(to_free);
7989 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007990 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007991}
7992#else
7993# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7994#endif
7995
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007996#if BB_MMU
7997#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7998 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7999#define pseudo_exec(nommu_save, command, argv_expanded) \
8000 pseudo_exec(command, argv_expanded)
8001#endif
8002
8003/* Called after [v]fork() in run_pipe, or from builtin_exec.
8004 * Never returns.
8005 * Don't exit() here. If you don't exec, use _exit instead.
8006 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008007 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008008 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008009static void pseudo_exec_argv(nommu_save_t *nommu_save,
8010 char **argv, int assignment_cnt,
8011 char **argv_expanded) NORETURN;
8012static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8013 char **argv, int assignment_cnt,
8014 char **argv_expanded)
8015{
Denys Vlasenko57000292018-01-12 14:41:45 +01008016 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008017 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008018 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008019 IF_HUSH_COMMAND(char opt_vV = 0;)
8020 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008021
8022 new_env = expand_assignments(argv, assignment_cnt);
8023 dump_cmd_in_x_mode(new_env);
8024
8025 if (!argv[assignment_cnt]) {
8026 /* Case when we are here: ... | var=val | ...
8027 * (note that we do not exit early, i.e., do not optimize out
8028 * expand_assignments(): think about ... | var=`sleep 1` | ...
8029 */
8030 free_strings(new_env);
8031 _exit(EXIT_SUCCESS);
8032 }
8033
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008034 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008035#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008036 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008037#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008038 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008039 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008040#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008041 set_vars_and_save_old(new_env);
8042 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008043
8044 if (argv_expanded) {
8045 argv = argv_expanded;
8046 } else {
8047 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8048#if !BB_MMU
8049 nommu_save->argv = argv;
8050#endif
8051 }
8052 dump_cmd_in_x_mode(argv);
8053
8054#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8055 if (strchr(argv[0], '/') != NULL)
8056 goto skip;
8057#endif
8058
Denys Vlasenko75481d32017-07-31 05:27:09 +02008059#if ENABLE_HUSH_FUNCTIONS
8060 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008061 funcp = find_function(argv[0]);
8062 if (funcp)
8063 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008064#endif
8065
Denys Vlasenko57000292018-01-12 14:41:45 +01008066#if ENABLE_HUSH_COMMAND
8067 /* "command BAR": run BAR without looking it up among functions
8068 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8069 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8070 */
8071 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8072 char *p;
8073
8074 argv++;
8075 p = *argv;
8076 if (p[0] != '-' || !p[1])
8077 continue; /* bash allows "command command command [-OPT] BAR" */
8078
8079 for (;;) {
8080 p++;
8081 switch (*p) {
8082 case '\0':
8083 argv++;
8084 p = *argv;
8085 if (p[0] != '-' || !p[1])
8086 goto after_opts;
8087 continue; /* next arg is also -opts, process it too */
8088 case 'v':
8089 case 'V':
8090 opt_vV = *p;
8091 continue;
8092 default:
8093 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8094 }
8095 }
8096 }
8097 after_opts:
8098# if ENABLE_HUSH_FUNCTIONS
8099 if (opt_vV && find_function(argv[0]))
8100 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8101# endif
8102#endif
8103
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008104 /* Check if the command matches any of the builtins.
8105 * Depending on context, this might be redundant. But it's
8106 * easier to waste a few CPU cycles than it is to figure out
8107 * if this is one of those cases.
8108 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008109 /* Why "BB_MMU ? :" difference in logic? -
8110 * On NOMMU, it is more expensive to re-execute shell
8111 * just in order to run echo or test builtin.
8112 * It's better to skip it here and run corresponding
8113 * non-builtin later. */
8114 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8115 if (x) {
8116 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8117 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008118 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008119
8120#if ENABLE_FEATURE_SH_STANDALONE
8121 /* Check if the command matches any busybox applets */
8122 {
8123 int a = find_applet_by_name(argv[0]);
8124 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008125 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008126# if BB_MMU /* see above why on NOMMU it is not allowed */
8127 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008128 /* Do not leak open fds from opened script files etc.
8129 * Testcase: interactive "ls -l /proc/self/fd"
8130 * should not show tty fd open.
8131 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008132 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008133//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008134//This casuses test failures in
8135//redir_children_should_not_see_saved_fd_2.tests
8136//redir_children_should_not_see_saved_fd_3.tests
8137//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008138 /* Without this, "rm -i FILE" can't be ^C'ed: */
8139 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008140 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008141 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008142 }
8143# endif
8144 /* Re-exec ourselves */
8145 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008146 /* Don't propagate SIG_IGN to the child */
8147 if (SPECIAL_JOBSTOP_SIGS != 0)
8148 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008149 execv(bb_busybox_exec_path, argv);
8150 /* If they called chroot or otherwise made the binary no longer
8151 * executable, fall through */
8152 }
8153 }
8154#endif
8155
8156#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8157 skip:
8158#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008159 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008160 execvp_or_die(argv);
8161}
8162
8163/* Called after [v]fork() in run_pipe
8164 */
8165static void pseudo_exec(nommu_save_t *nommu_save,
8166 struct command *command,
8167 char **argv_expanded) NORETURN;
8168static void pseudo_exec(nommu_save_t *nommu_save,
8169 struct command *command,
8170 char **argv_expanded)
8171{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008172#if ENABLE_HUSH_FUNCTIONS
8173 if (command->cmd_type == CMD_FUNCDEF) {
8174 /* Ignore funcdefs in pipes:
8175 * true | f() { cmd }
8176 */
8177 _exit(0);
8178 }
8179#endif
8180
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008181 if (command->argv) {
8182 pseudo_exec_argv(nommu_save, command->argv,
8183 command->assignment_cnt, argv_expanded);
8184 }
8185
8186 if (command->group) {
8187 /* Cases when we are here:
8188 * ( list )
8189 * { list } &
8190 * ... | ( list ) | ...
8191 * ... | { list } | ...
8192 */
8193#if BB_MMU
8194 int rcode;
8195 debug_printf_exec("pseudo_exec: run_list\n");
8196 reset_traps_to_defaults();
8197 rcode = run_list(command->group);
8198 /* OK to leak memory by not calling free_pipe_list,
8199 * since this process is about to exit */
8200 _exit(rcode);
8201#else
8202 re_execute_shell(&nommu_save->argv_from_re_execing,
8203 command->group_as_string,
8204 G.global_argv[0],
8205 G.global_argv + 1,
8206 NULL);
8207#endif
8208 }
8209
8210 /* Case when we are here: ... | >file */
8211 debug_printf_exec("pseudo_exec'ed null command\n");
8212 _exit(EXIT_SUCCESS);
8213}
8214
8215#if ENABLE_HUSH_JOB
8216static const char *get_cmdtext(struct pipe *pi)
8217{
8218 char **argv;
8219 char *p;
8220 int len;
8221
8222 /* This is subtle. ->cmdtext is created only on first backgrounding.
8223 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8224 * On subsequent bg argv is trashed, but we won't use it */
8225 if (pi->cmdtext)
8226 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008227
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008228 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008229 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008230 pi->cmdtext = xzalloc(1);
8231 return pi->cmdtext;
8232 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008233 len = 0;
8234 do {
8235 len += strlen(*argv) + 1;
8236 } while (*++argv);
8237 p = xmalloc(len);
8238 pi->cmdtext = p;
8239 argv = pi->cmds[0].argv;
8240 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008241 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008242 *p++ = ' ';
8243 } while (*++argv);
8244 p[-1] = '\0';
8245 return pi->cmdtext;
8246}
8247
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008248static void remove_job_from_table(struct pipe *pi)
8249{
8250 struct pipe *prev_pipe;
8251
8252 if (pi == G.job_list) {
8253 G.job_list = pi->next;
8254 } else {
8255 prev_pipe = G.job_list;
8256 while (prev_pipe->next != pi)
8257 prev_pipe = prev_pipe->next;
8258 prev_pipe->next = pi->next;
8259 }
8260 G.last_jobid = 0;
8261 if (G.job_list)
8262 G.last_jobid = G.job_list->jobid;
8263}
8264
8265static void delete_finished_job(struct pipe *pi)
8266{
8267 remove_job_from_table(pi);
8268 free_pipe(pi);
8269}
8270
8271static void clean_up_last_dead_job(void)
8272{
8273 if (G.job_list && !G.job_list->alive_cmds)
8274 delete_finished_job(G.job_list);
8275}
8276
Denys Vlasenko16096292017-07-10 10:00:28 +02008277static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008278{
8279 struct pipe *job, **jobp;
8280 int i;
8281
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008282 clean_up_last_dead_job();
8283
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008284 /* Find the end of the list, and find next job ID to use */
8285 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008286 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008287 while ((job = *jobp) != NULL) {
8288 if (job->jobid > i)
8289 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008290 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008291 }
8292 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008293
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008294 /* Create a new job struct at the end */
8295 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008296 job->next = NULL;
8297 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8298 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8299 for (i = 0; i < pi->num_cmds; i++) {
8300 job->cmds[i].pid = pi->cmds[i].pid;
8301 /* all other fields are not used and stay zero */
8302 }
8303 job->cmdtext = xstrdup(get_cmdtext(pi));
8304
8305 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008306 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008307 G.last_jobid = job->jobid;
8308}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008309#endif /* JOB */
8310
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008311static int job_exited_or_stopped(struct pipe *pi)
8312{
8313 int rcode, i;
8314
8315 if (pi->alive_cmds != pi->stopped_cmds)
8316 return -1;
8317
8318 /* All processes in fg pipe have exited or stopped */
8319 rcode = 0;
8320 i = pi->num_cmds;
8321 while (--i >= 0) {
8322 rcode = pi->cmds[i].cmd_exitcode;
8323 /* usually last process gives overall exitstatus,
8324 * but with "set -o pipefail", last *failed* process does */
8325 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8326 break;
8327 }
8328 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8329 return rcode;
8330}
8331
Denys Vlasenko7e675362016-10-28 21:57:31 +02008332static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008333{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008334#if ENABLE_HUSH_JOB
8335 struct pipe *pi;
8336#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008337 int i, dead;
8338
8339 dead = WIFEXITED(status) || WIFSIGNALED(status);
8340
8341#if DEBUG_JOBS
8342 if (WIFSTOPPED(status))
8343 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8344 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8345 if (WIFSIGNALED(status))
8346 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8347 childpid, WTERMSIG(status), WEXITSTATUS(status));
8348 if (WIFEXITED(status))
8349 debug_printf_jobs("pid %d exited, exitcode %d\n",
8350 childpid, WEXITSTATUS(status));
8351#endif
8352 /* Were we asked to wait for a fg pipe? */
8353 if (fg_pipe) {
8354 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008355
Denys Vlasenko7e675362016-10-28 21:57:31 +02008356 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008357 int rcode;
8358
Denys Vlasenko7e675362016-10-28 21:57:31 +02008359 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8360 if (fg_pipe->cmds[i].pid != childpid)
8361 continue;
8362 if (dead) {
8363 int ex;
8364 fg_pipe->cmds[i].pid = 0;
8365 fg_pipe->alive_cmds--;
8366 ex = WEXITSTATUS(status);
8367 /* bash prints killer signal's name for *last*
8368 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8369 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8370 */
8371 if (WIFSIGNALED(status)) {
8372 int sig = WTERMSIG(status);
8373 if (i == fg_pipe->num_cmds-1)
8374 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8375 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8376 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8377 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8378 * Maybe we need to use sig | 128? */
8379 ex = sig + 128;
8380 }
8381 fg_pipe->cmds[i].cmd_exitcode = ex;
8382 } else {
8383 fg_pipe->stopped_cmds++;
8384 }
8385 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8386 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008387 rcode = job_exited_or_stopped(fg_pipe);
8388 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008389/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8390 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8391 * and "killall -STOP cat" */
8392 if (G_interactive_fd) {
8393#if ENABLE_HUSH_JOB
8394 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008395 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008396#endif
8397 return rcode;
8398 }
8399 if (fg_pipe->alive_cmds == 0)
8400 return rcode;
8401 }
8402 /* There are still running processes in the fg_pipe */
8403 return -1;
8404 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008405 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008406 }
8407
8408#if ENABLE_HUSH_JOB
8409 /* We were asked to wait for bg or orphaned children */
8410 /* No need to remember exitcode in this case */
8411 for (pi = G.job_list; pi; pi = pi->next) {
8412 for (i = 0; i < pi->num_cmds; i++) {
8413 if (pi->cmds[i].pid == childpid)
8414 goto found_pi_and_prognum;
8415 }
8416 }
8417 /* Happens when shell is used as init process (init=/bin/sh) */
8418 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8419 return -1; /* this wasn't a process from fg_pipe */
8420
8421 found_pi_and_prognum:
8422 if (dead) {
8423 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008424 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008425 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008426 rcode = 128 + WTERMSIG(status);
8427 pi->cmds[i].cmd_exitcode = rcode;
8428 if (G.last_bg_pid == pi->cmds[i].pid)
8429 G.last_bg_pid_exitcode = rcode;
8430 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008431 pi->alive_cmds--;
8432 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008433 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008434 printf(JOB_STATUS_FORMAT, pi->jobid,
8435 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008436 delete_finished_job(pi);
8437 } else {
8438/*
8439 * bash deletes finished jobs from job table only in interactive mode,
8440 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8441 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8442 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8443 * We only retain one "dead" job, if it's the single job on the list.
8444 * This covers most of real-world scenarios where this is useful.
8445 */
8446 if (pi != G.job_list)
8447 delete_finished_job(pi);
8448 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008449 }
8450 } else {
8451 /* child stopped */
8452 pi->stopped_cmds++;
8453 }
8454#endif
8455 return -1; /* this wasn't a process from fg_pipe */
8456}
8457
8458/* Check to see if any processes have exited -- if they have,
8459 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008460 *
8461 * If non-NULL fg_pipe: wait for its completion or stop.
8462 * Return its exitcode or zero if stopped.
8463 *
8464 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8465 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8466 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8467 * or 0 if no children changed status.
8468 *
8469 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8470 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8471 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008472 */
8473static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8474{
8475 int attributes;
8476 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008477 int rcode = 0;
8478
8479 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8480
8481 attributes = WUNTRACED;
8482 if (fg_pipe == NULL)
8483 attributes |= WNOHANG;
8484
8485 errno = 0;
8486#if ENABLE_HUSH_FAST
8487 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8488//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8489//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8490 /* There was neither fork nor SIGCHLD since last waitpid */
8491 /* Avoid doing waitpid syscall if possible */
8492 if (!G.we_have_children) {
8493 errno = ECHILD;
8494 return -1;
8495 }
8496 if (fg_pipe == NULL) { /* is WNOHANG set? */
8497 /* We have children, but they did not exit
8498 * or stop yet (we saw no SIGCHLD) */
8499 return 0;
8500 }
8501 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8502 }
8503#endif
8504
8505/* Do we do this right?
8506 * bash-3.00# sleep 20 | false
8507 * <ctrl-Z pressed>
8508 * [3]+ Stopped sleep 20 | false
8509 * bash-3.00# echo $?
8510 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8511 * [hush 1.14.0: yes we do it right]
8512 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008513 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008514 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008515#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008516 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008517 i = G.count_SIGCHLD;
8518#endif
8519 childpid = waitpid(-1, &status, attributes);
8520 if (childpid <= 0) {
8521 if (childpid && errno != ECHILD)
8522 bb_perror_msg("waitpid");
8523#if ENABLE_HUSH_FAST
8524 else { /* Until next SIGCHLD, waitpid's are useless */
8525 G.we_have_children = (childpid == 0);
8526 G.handled_SIGCHLD = i;
8527//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8528 }
8529#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008530 /* ECHILD (no children), or 0 (no change in children status) */
8531 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008532 break;
8533 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008534 rcode = process_wait_result(fg_pipe, childpid, status);
8535 if (rcode >= 0) {
8536 /* fg_pipe exited or stopped */
8537 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008538 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008539 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008540 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008541 rcode = WEXITSTATUS(status);
8542 if (WIFSIGNALED(status))
8543 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008544 if (WIFSTOPPED(status))
8545 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8546 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008547 rcode++;
8548 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008549 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008550 /* This wasn't one of our processes, or */
8551 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008552 } /* while (waitpid succeeds)... */
8553
8554 return rcode;
8555}
8556
8557#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008558static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008559{
8560 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008561 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008562 if (G_saved_tty_pgrp) {
8563 /* Job finished, move the shell to the foreground */
8564 p = getpgrp(); /* our process group id */
8565 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8566 tcsetpgrp(G_interactive_fd, p);
8567 }
8568 return rcode;
8569}
8570#endif
8571
8572/* Start all the jobs, but don't wait for anything to finish.
8573 * See checkjobs().
8574 *
8575 * Return code is normally -1, when the caller has to wait for children
8576 * to finish to determine the exit status of the pipe. If the pipe
8577 * is a simple builtin command, however, the action is done by the
8578 * time run_pipe returns, and the exit code is provided as the
8579 * return value.
8580 *
8581 * Returns -1 only if started some children. IOW: we have to
8582 * mask out retvals of builtins etc with 0xff!
8583 *
8584 * The only case when we do not need to [v]fork is when the pipe
8585 * is single, non-backgrounded, non-subshell command. Examples:
8586 * cmd ; ... { list } ; ...
8587 * cmd && ... { list } && ...
8588 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008589 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008590 * or (if SH_STANDALONE) an applet, and we can run the { list }
8591 * with run_list. If it isn't one of these, we fork and exec cmd.
8592 *
8593 * Cases when we must fork:
8594 * non-single: cmd | cmd
8595 * backgrounded: cmd & { list } &
8596 * subshell: ( list ) [&]
8597 */
8598#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008599#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8600 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008601#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008602static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008603 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008604 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008605 char **argv_expanded)
8606{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008607 /* Assignments occur before redirects. Try:
8608 * a=`sleep 1` sleep 2 3>/qwe/rty
8609 */
8610
8611 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8612 dump_cmd_in_x_mode(new_env);
8613 dump_cmd_in_x_mode(argv_expanded);
8614 /* this takes ownership of new_env[i] elements, and frees new_env: */
8615 set_vars_and_save_old(new_env);
8616
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008617 /* setup_redirects acts on file descriptors, not FILEs.
8618 * This is perfect for work that comes after exec().
8619 * Is it really safe for inline use? Experimentally,
8620 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008621 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008622}
8623static NOINLINE int run_pipe(struct pipe *pi)
8624{
8625 static const char *const null_ptr = NULL;
8626
8627 int cmd_no;
8628 int next_infd;
8629 struct command *command;
8630 char **argv_expanded;
8631 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008632 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008633 int rcode;
8634
8635 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8636 debug_enter();
8637
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008638 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8639 * Result should be 3 lines: q w e, qwe, q w e
8640 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008641 if (G.ifs_whitespace != G.ifs)
8642 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008643 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008644 if (G.ifs) {
8645 char *p;
8646 G.ifs_whitespace = (char*)G.ifs;
8647 p = skip_whitespace(G.ifs);
8648 if (*p) {
8649 /* Not all $IFS is whitespace */
8650 char *d;
8651 int len = p - G.ifs;
8652 p = skip_non_whitespace(p);
8653 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8654 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8655 while (*p) {
8656 if (isspace(*p))
8657 *d++ = *p;
8658 p++;
8659 }
8660 *d = '\0';
8661 }
8662 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008663 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008664 G.ifs_whitespace = (char*)G.ifs;
8665 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008666
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008667 IF_HUSH_JOB(pi->pgrp = -1;)
8668 pi->stopped_cmds = 0;
8669 command = &pi->cmds[0];
8670 argv_expanded = NULL;
8671
8672 if (pi->num_cmds != 1
8673 || pi->followup == PIPE_BG
8674 || command->cmd_type == CMD_SUBSHELL
8675 ) {
8676 goto must_fork;
8677 }
8678
8679 pi->alive_cmds = 1;
8680
8681 debug_printf_exec(": group:%p argv:'%s'\n",
8682 command->group, command->argv ? command->argv[0] : "NONE");
8683
8684 if (command->group) {
8685#if ENABLE_HUSH_FUNCTIONS
8686 if (command->cmd_type == CMD_FUNCDEF) {
8687 /* "executing" func () { list } */
8688 struct function *funcp;
8689
8690 funcp = new_function(command->argv[0]);
8691 /* funcp->name is already set to argv[0] */
8692 funcp->body = command->group;
8693# if !BB_MMU
8694 funcp->body_as_string = command->group_as_string;
8695 command->group_as_string = NULL;
8696# endif
8697 command->group = NULL;
8698 command->argv[0] = NULL;
8699 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8700 funcp->parent_cmd = command;
8701 command->child_func = funcp;
8702
8703 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8704 debug_leave();
8705 return EXIT_SUCCESS;
8706 }
8707#endif
8708 /* { list } */
8709 debug_printf("non-subshell group\n");
8710 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008711 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008712 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008713//FIXME: we need to pass squirrel down into run_list()
8714//for SH_STANDALONE case, or else this construct:
8715// { find /proc/self/fd; true; } >FILE; cmd2
8716//has no way of closing saved fd#1 for "find",
8717//and in SH_STANDALONE mode, "find" is not execed,
8718//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008719 rcode = run_list(command->group) & 0xff;
8720 }
8721 restore_redirects(squirrel);
8722 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8723 debug_leave();
8724 debug_printf_exec("run_pipe: return %d\n", rcode);
8725 return rcode;
8726 }
8727
8728 argv = command->argv ? command->argv : (char **) &null_ptr;
8729 {
8730 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008731 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8732 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008733 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008734 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008735
Denys Vlasenko5807e182018-02-08 19:19:04 +01008736#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008737 if (G.lineno_var)
8738 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8739#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008740
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008741 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008742 /* Assignments, but no command.
8743 * Ensure redirects take effect (that is, create files).
8744 * Try "a=t >file"
8745 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008746 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008747 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008748 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008749 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008750 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008751
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008752 /* Set shell variables */
8753 if (G_x_mode)
8754 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008755 i = 0;
8756 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008757 char *p = expand_string_to_string(argv[i],
8758 EXP_FLAG_ESC_GLOB_CHARS,
8759 /*unbackslash:*/ 1
8760 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008761 if (G_x_mode)
8762 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008763 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008764 if (set_local_var(p, /*flag:*/ 0)) {
8765 /* assignment to readonly var / putenv error? */
8766 rcode = 1;
8767 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008768 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008769 }
8770 if (G_x_mode)
8771 bb_putchar_stderr('\n');
8772 /* Redirect error sets $? to 1. Otherwise,
8773 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008774 * Else, clear $?:
8775 * false; q=`exit 2`; echo $? - should print 2
8776 * false; x=1; echo $? - should print 0
8777 * Because of the 2nd case, we can't just use G.last_exitcode.
8778 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008779 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008780 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008781 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8782 debug_leave();
8783 debug_printf_exec("run_pipe: return %d\n", rcode);
8784 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008785 }
8786
8787 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008788#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008789 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008790 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008791 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008792#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008793 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008794
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008795 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008796 if (!argv_expanded[0]) {
8797 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008798 /* `false` still has to set exitcode 1 */
8799 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008800 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008801 }
8802
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008803 old_vars = NULL;
8804 sv_shadowed = G.shadowed_vars_pp;
8805
Denys Vlasenko75481d32017-07-31 05:27:09 +02008806 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008807 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8808 IF_HUSH_FUNCTIONS(x = NULL;)
8809 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008810 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008811 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008812 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8813 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008814 /*
8815 * Variable assignments are executed, but then "forgotten":
8816 * a=`sleep 1;echo A` exec 3>&-; echo $a
8817 * sleeps, but prints nothing.
8818 */
8819 enter_var_nest_level();
8820 G.shadowed_vars_pp = &old_vars;
8821 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8822 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008823 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008824
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008825 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008826 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008827
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008828 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008829 * a=b true; env | grep ^a=
8830 */
8831 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008832 /* Collect all variables "shadowed" by helper
8833 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8834 * into old_vars list:
8835 */
8836 G.shadowed_vars_pp = &old_vars;
8837 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008838 if (rcode == 0) {
8839 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008840 /* Do not collect *to old_vars list* vars shadowed
8841 * by e.g. "local VAR" builtin (collect them
8842 * in the previously nested list instead):
8843 * don't want them to be restored immediately
8844 * after "local" completes.
8845 */
8846 G.shadowed_vars_pp = sv_shadowed;
8847
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008848 debug_printf_exec(": builtin '%s' '%s'...\n",
8849 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008850 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008851 rcode = x->b_function(argv_expanded) & 0xff;
8852 fflush_all();
8853 }
8854#if ENABLE_HUSH_FUNCTIONS
8855 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008856 debug_printf_exec(": function '%s' '%s'...\n",
8857 funcp->name, argv_expanded[1]);
8858 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008859 /*
8860 * But do collect *to old_vars list* vars shadowed
8861 * within function execution. To that end, restore
8862 * this pointer _after_ function run:
8863 */
8864 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008865 }
8866#endif
8867 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008868 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008869 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008870 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008871 if (n < 0 || !APPLET_IS_NOFORK(n))
8872 goto must_fork;
8873
8874 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008875 /* Collect all variables "shadowed" by helper into old_vars list */
8876 G.shadowed_vars_pp = &old_vars;
8877 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8878 G.shadowed_vars_pp = sv_shadowed;
8879
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008880 if (rcode == 0) {
8881 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8882 argv_expanded[0], argv_expanded[1]);
8883 /*
8884 * Note: signals (^C) can't interrupt here.
8885 * We remember them and they will be acted upon
8886 * after applet returns.
8887 * This makes applets which can run for a long time
8888 * and/or wait for user input ineligible for NOFORK:
8889 * for example, "yes" or "rm" (rm -i waits for input).
8890 */
8891 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008892 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008893 } else
8894 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008895
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008896 restore_redirects(squirrel);
8897 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008898 leave_var_nest_level();
8899 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008900
8901 /*
8902 * Try "usleep 99999999" + ^C + "echo $?"
8903 * with FEATURE_SH_NOFORK=y.
8904 */
8905 if (!funcp) {
8906 /* It was builtin or nofork.
8907 * if this would be a real fork/execed program,
8908 * it should have died if a fatal sig was received.
8909 * But OTOH, there was no separate process,
8910 * the sig was sent to _shell_, not to non-existing
8911 * child.
8912 * Let's just handle ^C only, this one is obvious:
8913 * we aren't ok with exitcode 0 when ^C was pressed
8914 * during builtin/nofork.
8915 */
8916 if (sigismember(&G.pending_set, SIGINT))
8917 rcode = 128 + SIGINT;
8918 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008919 free(argv_expanded);
8920 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8921 debug_leave();
8922 debug_printf_exec("run_pipe return %d\n", rcode);
8923 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008924 }
8925
8926 must_fork:
8927 /* NB: argv_expanded may already be created, and that
8928 * might include `cmd` runs! Do not rerun it! We *must*
8929 * use argv_expanded if it's non-NULL */
8930
8931 /* Going to fork a child per each pipe member */
8932 pi->alive_cmds = 0;
8933 next_infd = 0;
8934
8935 cmd_no = 0;
8936 while (cmd_no < pi->num_cmds) {
8937 struct fd_pair pipefds;
8938#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008939 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008940 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008941 nommu_save.old_vars = NULL;
8942 nommu_save.argv = NULL;
8943 nommu_save.argv_from_re_execing = NULL;
8944#endif
8945 command = &pi->cmds[cmd_no];
8946 cmd_no++;
8947 if (command->argv) {
8948 debug_printf_exec(": pipe member '%s' '%s'...\n",
8949 command->argv[0], command->argv[1]);
8950 } else {
8951 debug_printf_exec(": pipe member with no argv\n");
8952 }
8953
8954 /* pipes are inserted between pairs of commands */
8955 pipefds.rd = 0;
8956 pipefds.wr = 1;
8957 if (cmd_no < pi->num_cmds)
8958 xpiped_pair(pipefds);
8959
Denys Vlasenko5807e182018-02-08 19:19:04 +01008960#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008961 if (G.lineno_var)
8962 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8963#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008964
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008965 command->pid = BB_MMU ? fork() : vfork();
8966 if (!command->pid) { /* child */
8967#if ENABLE_HUSH_JOB
8968 disable_restore_tty_pgrp_on_exit();
8969 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8970
8971 /* Every child adds itself to new process group
8972 * with pgid == pid_of_first_child_in_pipe */
8973 if (G.run_list_level == 1 && G_interactive_fd) {
8974 pid_t pgrp;
8975 pgrp = pi->pgrp;
8976 if (pgrp < 0) /* true for 1st process only */
8977 pgrp = getpid();
8978 if (setpgid(0, pgrp) == 0
8979 && pi->followup != PIPE_BG
8980 && G_saved_tty_pgrp /* we have ctty */
8981 ) {
8982 /* We do it in *every* child, not just first,
8983 * to avoid races */
8984 tcsetpgrp(G_interactive_fd, pgrp);
8985 }
8986 }
8987#endif
8988 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8989 /* 1st cmd in backgrounded pipe
8990 * should have its stdin /dev/null'ed */
8991 close(0);
8992 if (open(bb_dev_null, O_RDONLY))
8993 xopen("/", O_RDONLY);
8994 } else {
8995 xmove_fd(next_infd, 0);
8996 }
8997 xmove_fd(pipefds.wr, 1);
8998 if (pipefds.rd > 1)
8999 close(pipefds.rd);
9000 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009001 * and the pipe fd (fd#1) is available for dup'ing:
9002 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9003 * of cmd1 goes into pipe.
9004 */
9005 if (setup_redirects(command, NULL)) {
9006 /* Happens when redir file can't be opened:
9007 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9008 * FOO
9009 * hush: can't open '/qwe/rty': No such file or directory
9010 * BAZ
9011 * (echo BAR is not executed, it hits _exit(1) below)
9012 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009013 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009014 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009015
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009016 /* Stores to nommu_save list of env vars putenv'ed
9017 * (NOMMU, on MMU we don't need that) */
9018 /* cast away volatility... */
9019 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9020 /* pseudo_exec() does not return */
9021 }
9022
9023 /* parent or error */
9024#if ENABLE_HUSH_FAST
9025 G.count_SIGCHLD++;
9026//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9027#endif
9028 enable_restore_tty_pgrp_on_exit();
9029#if !BB_MMU
9030 /* Clean up after vforked child */
9031 free(nommu_save.argv);
9032 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009033 G.var_nest_level = sv_var_nest_level;
9034 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009035 add_vars(nommu_save.old_vars);
9036#endif
9037 free(argv_expanded);
9038 argv_expanded = NULL;
9039 if (command->pid < 0) { /* [v]fork failed */
9040 /* Clearly indicate, was it fork or vfork */
9041 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9042 } else {
9043 pi->alive_cmds++;
9044#if ENABLE_HUSH_JOB
9045 /* Second and next children need to know pid of first one */
9046 if (pi->pgrp < 0)
9047 pi->pgrp = command->pid;
9048#endif
9049 }
9050
9051 if (cmd_no > 1)
9052 close(next_infd);
9053 if (cmd_no < pi->num_cmds)
9054 close(pipefds.wr);
9055 /* Pass read (output) pipe end to next iteration */
9056 next_infd = pipefds.rd;
9057 }
9058
9059 if (!pi->alive_cmds) {
9060 debug_leave();
9061 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9062 return 1;
9063 }
9064
9065 debug_leave();
9066 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9067 return -1;
9068}
9069
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009070/* NB: called by pseudo_exec, and therefore must not modify any
9071 * global data until exec/_exit (we can be a child after vfork!) */
9072static int run_list(struct pipe *pi)
9073{
9074#if ENABLE_HUSH_CASE
9075 char *case_word = NULL;
9076#endif
9077#if ENABLE_HUSH_LOOPS
9078 struct pipe *loop_top = NULL;
9079 char **for_lcur = NULL;
9080 char **for_list = NULL;
9081#endif
9082 smallint last_followup;
9083 smalluint rcode;
9084#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9085 smalluint cond_code = 0;
9086#else
9087 enum { cond_code = 0 };
9088#endif
9089#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009090 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009091 smallint last_rword; /* ditto */
9092#endif
9093
9094 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9095 debug_enter();
9096
9097#if ENABLE_HUSH_LOOPS
9098 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009099 {
9100 struct pipe *cpipe;
9101 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9102 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9103 continue;
9104 /* current word is FOR or IN (BOLD in comments below) */
9105 if (cpipe->next == NULL) {
9106 syntax_error("malformed for");
9107 debug_leave();
9108 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9109 return 1;
9110 }
9111 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9112 if (cpipe->next->res_word == RES_DO)
9113 continue;
9114 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9115 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9116 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9117 ) {
9118 syntax_error("malformed for");
9119 debug_leave();
9120 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9121 return 1;
9122 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009123 }
9124 }
9125#endif
9126
9127 /* Past this point, all code paths should jump to ret: label
9128 * in order to return, no direct "return" statements please.
9129 * This helps to ensure that no memory is leaked. */
9130
9131#if ENABLE_HUSH_JOB
9132 G.run_list_level++;
9133#endif
9134
9135#if HAS_KEYWORDS
9136 rword = RES_NONE;
9137 last_rword = RES_XXXX;
9138#endif
9139 last_followup = PIPE_SEQ;
9140 rcode = G.last_exitcode;
9141
9142 /* Go through list of pipes, (maybe) executing them. */
9143 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009144 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009145 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009146
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009147 if (G.flag_SIGINT)
9148 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009149 if (G_flag_return_in_progress == 1)
9150 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009151
9152 IF_HAS_KEYWORDS(rword = pi->res_word;)
9153 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9154 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009155
9156 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009157 if (
9158#if ENABLE_HUSH_IF
9159 rword == RES_IF || rword == RES_ELIF ||
9160#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009161 pi->followup != PIPE_SEQ
9162 ) {
9163 G.errexit_depth++;
9164 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009165#if ENABLE_HUSH_LOOPS
9166 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9167 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9168 ) {
9169 /* start of a loop: remember where loop starts */
9170 loop_top = pi;
9171 G.depth_of_loop++;
9172 }
9173#endif
9174 /* Still in the same "if...", "then..." or "do..." branch? */
9175 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9176 if ((rcode == 0 && last_followup == PIPE_OR)
9177 || (rcode != 0 && last_followup == PIPE_AND)
9178 ) {
9179 /* It is "<true> || CMD" or "<false> && CMD"
9180 * and we should not execute CMD */
9181 debug_printf_exec("skipped cmd because of || or &&\n");
9182 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009183 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009184 }
9185 }
9186 last_followup = pi->followup;
9187 IF_HAS_KEYWORDS(last_rword = rword;)
9188#if ENABLE_HUSH_IF
9189 if (cond_code) {
9190 if (rword == RES_THEN) {
9191 /* if false; then ... fi has exitcode 0! */
9192 G.last_exitcode = rcode = EXIT_SUCCESS;
9193 /* "if <false> THEN cmd": skip cmd */
9194 continue;
9195 }
9196 } else {
9197 if (rword == RES_ELSE || rword == RES_ELIF) {
9198 /* "if <true> then ... ELSE/ELIF cmd":
9199 * skip cmd and all following ones */
9200 break;
9201 }
9202 }
9203#endif
9204#if ENABLE_HUSH_LOOPS
9205 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9206 if (!for_lcur) {
9207 /* first loop through for */
9208
9209 static const char encoded_dollar_at[] ALIGN1 = {
9210 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9211 }; /* encoded representation of "$@" */
9212 static const char *const encoded_dollar_at_argv[] = {
9213 encoded_dollar_at, NULL
9214 }; /* argv list with one element: "$@" */
9215 char **vals;
9216
9217 vals = (char**)encoded_dollar_at_argv;
9218 if (pi->next->res_word == RES_IN) {
9219 /* if no variable values after "in" we skip "for" */
9220 if (!pi->next->cmds[0].argv) {
9221 G.last_exitcode = rcode = EXIT_SUCCESS;
9222 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9223 break;
9224 }
9225 vals = pi->next->cmds[0].argv;
9226 } /* else: "for var; do..." -> assume "$@" list */
9227 /* create list of variable values */
9228 debug_print_strings("for_list made from", vals);
9229 for_list = expand_strvec_to_strvec(vals);
9230 for_lcur = for_list;
9231 debug_print_strings("for_list", for_list);
9232 }
9233 if (!*for_lcur) {
9234 /* "for" loop is over, clean up */
9235 free(for_list);
9236 for_list = NULL;
9237 for_lcur = NULL;
9238 break;
9239 }
9240 /* Insert next value from for_lcur */
9241 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009242 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009243 continue;
9244 }
9245 if (rword == RES_IN) {
9246 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9247 }
9248 if (rword == RES_DONE) {
9249 continue; /* "done" has no cmds too */
9250 }
9251#endif
9252#if ENABLE_HUSH_CASE
9253 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009254 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009255 case_word = expand_string_to_string(pi->cmds->argv[0],
9256 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009257 debug_printf_exec("CASE word1:'%s'\n", case_word);
9258 //unbackslash(case_word);
9259 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009260 continue;
9261 }
9262 if (rword == RES_MATCH) {
9263 char **argv;
9264
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009265 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009266 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9267 break;
9268 /* all prev words didn't match, does this one match? */
9269 argv = pi->cmds->argv;
9270 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009271 char *pattern;
9272 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9273 pattern = expand_string_to_string(*argv,
9274 EXP_FLAG_ESC_GLOB_CHARS,
9275 /*unbackslash:*/ 0
9276 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009277 /* TODO: which FNM_xxx flags to use? */
9278 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009279 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9280 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009281 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009282 if (cond_code == 0) {
9283 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009284 free(case_word);
9285 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009286 break;
9287 }
9288 argv++;
9289 }
9290 continue;
9291 }
9292 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009293 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009294 if (cond_code != 0)
9295 continue; /* not matched yet, skip this pipe */
9296 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009297 if (rword == RES_ESAC) {
9298 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9299 if (case_word) {
9300 /* "case" did not match anything: still set $? (to 0) */
9301 G.last_exitcode = rcode = EXIT_SUCCESS;
9302 }
9303 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009304#endif
9305 /* Just pressing <enter> in shell should check for jobs.
9306 * OTOH, in non-interactive shell this is useless
9307 * and only leads to extra job checks */
9308 if (pi->num_cmds == 0) {
9309 if (G_interactive_fd)
9310 goto check_jobs_and_continue;
9311 continue;
9312 }
9313
9314 /* After analyzing all keywords and conditions, we decided
9315 * to execute this pipe. NB: have to do checkjobs(NULL)
9316 * after run_pipe to collect any background children,
9317 * even if list execution is to be stopped. */
9318 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009319#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009320 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009321#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009322 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9323 if (r != -1) {
9324 /* We ran a builtin, function, or group.
9325 * rcode is already known
9326 * and we don't need to wait for anything. */
9327 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9328 G.last_exitcode = rcode;
9329 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009330#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009331 /* Was it "break" or "continue"? */
9332 if (G.flag_break_continue) {
9333 smallint fbc = G.flag_break_continue;
9334 /* We might fall into outer *loop*,
9335 * don't want to break it too */
9336 if (loop_top) {
9337 G.depth_break_continue--;
9338 if (G.depth_break_continue == 0)
9339 G.flag_break_continue = 0;
9340 /* else: e.g. "continue 2" should *break* once, *then* continue */
9341 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9342 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009343 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009344 break;
9345 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009346 /* "continue": simulate end of loop */
9347 rword = RES_DONE;
9348 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009349 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009350#endif
9351 if (G_flag_return_in_progress == 1) {
9352 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9353 break;
9354 }
9355 } else if (pi->followup == PIPE_BG) {
9356 /* What does bash do with attempts to background builtins? */
9357 /* even bash 3.2 doesn't do that well with nested bg:
9358 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9359 * I'm NOT treating inner &'s as jobs */
9360#if ENABLE_HUSH_JOB
9361 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009362 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009363#endif
9364 /* Last command's pid goes to $! */
9365 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009366 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009367 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009368/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009369 rcode = EXIT_SUCCESS;
9370 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009371 } else {
9372#if ENABLE_HUSH_JOB
9373 if (G.run_list_level == 1 && G_interactive_fd) {
9374 /* Waits for completion, then fg's main shell */
9375 rcode = checkjobs_and_fg_shell(pi);
9376 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009377 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009378 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009379#endif
9380 /* This one just waits for completion */
9381 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9382 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9383 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009384 G.last_exitcode = rcode;
9385 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009386 }
9387
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009388 /* Handle "set -e" */
9389 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9390 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9391 if (G.errexit_depth == 0)
9392 hush_exit(rcode);
9393 }
9394 G.errexit_depth = sv_errexit_depth;
9395
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009396 /* Analyze how result affects subsequent commands */
9397#if ENABLE_HUSH_IF
9398 if (rword == RES_IF || rword == RES_ELIF)
9399 cond_code = rcode;
9400#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009401 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009402 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009403 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009404#if ENABLE_HUSH_LOOPS
9405 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009406 if (pi->next
9407 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009408 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009409 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009410 if (rword == RES_WHILE) {
9411 if (rcode) {
9412 /* "while false; do...done" - exitcode 0 */
9413 G.last_exitcode = rcode = EXIT_SUCCESS;
9414 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009415 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009416 }
9417 }
9418 if (rword == RES_UNTIL) {
9419 if (!rcode) {
9420 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009421 break;
9422 }
9423 }
9424 }
9425#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009426 } /* for (pi) */
9427
9428#if ENABLE_HUSH_JOB
9429 G.run_list_level--;
9430#endif
9431#if ENABLE_HUSH_LOOPS
9432 if (loop_top)
9433 G.depth_of_loop--;
9434 free(for_list);
9435#endif
9436#if ENABLE_HUSH_CASE
9437 free(case_word);
9438#endif
9439 debug_leave();
9440 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9441 return rcode;
9442}
9443
9444/* Select which version we will use */
9445static int run_and_free_list(struct pipe *pi)
9446{
9447 int rcode = 0;
9448 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009449 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009450 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9451 rcode = run_list(pi);
9452 }
9453 /* free_pipe_list has the side effect of clearing memory.
9454 * In the long run that function can be merged with run_list,
9455 * but doing that now would hobble the debugging effort. */
9456 free_pipe_list(pi);
9457 debug_printf_exec("run_and_free_list return %d\n", rcode);
9458 return rcode;
9459}
9460
9461
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009462static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009463{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009464 sighandler_t old_handler;
9465 unsigned sig = 0;
9466 while ((mask >>= 1) != 0) {
9467 sig++;
9468 if (!(mask & 1))
9469 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009470 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009471 /* POSIX allows shell to re-enable SIGCHLD
9472 * even if it was SIG_IGN on entry.
9473 * Therefore we skip IGN check for it:
9474 */
9475 if (sig == SIGCHLD)
9476 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009477 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9478 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9479 */
9480 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009481 if (old_handler == SIG_IGN) {
9482 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009483 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009484#if ENABLE_HUSH_TRAP
9485 if (!G_traps)
9486 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9487 free(G_traps[sig]);
9488 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9489#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009490 }
9491 }
9492}
9493
9494/* Called a few times only (or even once if "sh -c") */
9495static void install_special_sighandlers(void)
9496{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009497 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009498
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009499 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009500 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009501 if (G_interactive_fd) {
9502 mask |= SPECIAL_INTERACTIVE_SIGS;
9503 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009504 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009505 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009506 /* Careful, do not re-install handlers we already installed */
9507 if (G.special_sig_mask != mask) {
9508 unsigned diff = mask & ~G.special_sig_mask;
9509 G.special_sig_mask = mask;
9510 install_sighandlers(diff);
9511 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009512}
9513
9514#if ENABLE_HUSH_JOB
9515/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009516/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009517static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009518{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009519 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009520
9521 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009522 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009523 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9524 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009525 + (1 << SIGBUS ) * HUSH_DEBUG
9526 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009527 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009528 + (1 << SIGABRT)
9529 /* bash 3.2 seems to handle these just like 'fatal' ones */
9530 + (1 << SIGPIPE)
9531 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009532 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009533 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009534 * we never want to restore pgrp on exit, and this fn is not called
9535 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009536 /*+ (1 << SIGHUP )*/
9537 /*+ (1 << SIGTERM)*/
9538 /*+ (1 << SIGINT )*/
9539 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009540 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009541
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009542 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009543}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009544#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009545
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009546static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009547{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009548 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009549 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009550 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009551 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009552 break;
9553 case 'x':
9554 IF_HUSH_MODE_X(G_x_mode = state;)
9555 break;
9556 case 'o':
9557 if (!o_opt) {
9558 /* "set -+o" without parameter.
9559 * in bash, set -o produces this output:
9560 * pipefail off
9561 * and set +o:
9562 * set +o pipefail
9563 * We always use the second form.
9564 */
9565 const char *p = o_opt_strings;
9566 idx = 0;
9567 while (*p) {
9568 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9569 idx++;
9570 p += strlen(p) + 1;
9571 }
9572 break;
9573 }
9574 idx = index_in_strings(o_opt_strings, o_opt);
9575 if (idx >= 0) {
9576 G.o_opt[idx] = state;
9577 break;
9578 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009579 case 'e':
9580 G.o_opt[OPT_O_ERREXIT] = state;
9581 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009582 default:
9583 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009584 }
9585 return EXIT_SUCCESS;
9586}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009587
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009588int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009589int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009590{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009591 enum {
9592 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009593 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009594 };
9595 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009596 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009597 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009598 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009599 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009600
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009601 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009602 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009603 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009604
Denys Vlasenko10c01312011-05-11 11:49:21 +02009605#if ENABLE_HUSH_FAST
9606 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9607#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009608#if !BB_MMU
9609 G.argv0_for_re_execing = argv[0];
9610#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009611
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009612 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009613 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9614 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009615 shell_ver = xzalloc(sizeof(*shell_ver));
9616 shell_ver->flg_export = 1;
9617 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009618 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009619 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009620 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009621
Denys Vlasenko605067b2010-09-06 12:10:51 +02009622 /* Create shell local variables from the values
9623 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009624 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009625 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009626 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009627 if (e) while (*e) {
9628 char *value = strchr(*e, '=');
9629 if (value) { /* paranoia */
9630 cur_var->next = xzalloc(sizeof(*cur_var));
9631 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009632 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009633 cur_var->max_len = strlen(*e);
9634 cur_var->flg_export = 1;
9635 }
9636 e++;
9637 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009638 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009639 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9640 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009641
9642 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009643 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009644
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009645#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9646 /* Set (but not export) PS1/2 unless already set */
9647 if (!get_local_var_value("PS1"))
9648 set_local_var_from_halves("PS1", "\\w \\$ ");
9649 if (!get_local_var_value("PS2"))
9650 set_local_var_from_halves("PS2", "> ");
9651#endif
9652
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009653#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009654 /* Set (but not export) HOSTNAME unless already set */
9655 if (!get_local_var_value("HOSTNAME")) {
9656 struct utsname uts;
9657 uname(&uts);
9658 set_local_var_from_halves("HOSTNAME", uts.nodename);
9659 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009660 /* bash also exports SHLVL and _,
9661 * and sets (but doesn't export) the following variables:
9662 * BASH=/bin/bash
9663 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9664 * BASH_VERSION='3.2.0(1)-release'
9665 * HOSTTYPE=i386
9666 * MACHTYPE=i386-pc-linux-gnu
9667 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009668 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009669 * EUID=<NNNNN>
9670 * UID=<NNNNN>
9671 * GROUPS=()
9672 * LINES=<NNN>
9673 * COLUMNS=<NNN>
9674 * BASH_ARGC=()
9675 * BASH_ARGV=()
9676 * BASH_LINENO=()
9677 * BASH_SOURCE=()
9678 * DIRSTACK=()
9679 * PIPESTATUS=([0]="0")
9680 * HISTFILE=/<xxx>/.bash_history
9681 * HISTFILESIZE=500
9682 * HISTSIZE=500
9683 * MAILCHECK=60
9684 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9685 * SHELL=/bin/bash
9686 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9687 * TERM=dumb
9688 * OPTERR=1
9689 * OPTIND=1
9690 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009691 * PS4='+ '
9692 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009693#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009694
Denys Vlasenko5807e182018-02-08 19:19:04 +01009695#if ENABLE_HUSH_LINENO_VAR
9696 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009697 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9698 set_local_var(p, /*flags*/ 0);
9699 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9700 }
9701#endif
9702
Denis Vlasenko38f63192007-01-22 09:03:07 +00009703#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009704 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009705#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009706
Eric Andersen94ac2442001-05-22 19:05:18 +00009707 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009708 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009709
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009710 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009711
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009712 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009713 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009714 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009715 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009716 * in order to intercept (more) signals.
9717 */
9718
9719 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009720 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009721 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009722 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009723 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009724 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009725#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009726 "<:$:R:V:"
9727# if ENABLE_HUSH_FUNCTIONS
9728 "F:"
9729# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009730#endif
9731 );
9732 if (opt <= 0)
9733 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009734 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009735 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009736 /* Possibilities:
9737 * sh ... -c 'script'
9738 * sh ... -c 'script' ARG0 [ARG1...]
9739 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009740 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009741 * "" needs to be replaced with NULL
9742 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009743 * Note: the form without ARG0 never happens:
9744 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009745 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009746 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009747 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009748 G.root_ppid = getppid();
9749 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009750 G.global_argv = argv + optind;
9751 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009752 if (builtin_argc) {
9753 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9754 const struct built_in_command *x;
9755
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009756 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009757 x = find_builtin(optarg);
9758 if (x) { /* paranoia */
9759 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9760 G.global_argv += builtin_argc;
9761 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009762 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009763 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009764 }
9765 goto final_return;
9766 }
9767 if (!G.global_argv[0]) {
9768 /* -c 'script' (no params): prevent empty $0 */
9769 G.global_argv--; /* points to argv[i] of 'script' */
9770 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009771 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009772 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009773 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009774 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009775 goto final_return;
9776 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009777 /* Well, we cannot just declare interactiveness,
9778 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009779 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009780 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009781 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009782 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009783 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009784 case 'l':
9785 flags |= OPT_login;
9786 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009787#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009788 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009789 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009790 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009791 case '$': {
9792 unsigned long long empty_trap_mask;
9793
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009794 G.root_pid = bb_strtou(optarg, &optarg, 16);
9795 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009796 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9797 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009798 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9799 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009800 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009801 optarg++;
9802 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009803 optarg++;
9804 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9805 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009806 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009807 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009808# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009809 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009810 for (sig = 1; sig < NSIG; sig++) {
9811 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009812 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009813 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009814 }
9815 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009816# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009817 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009818# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009819 optarg++;
9820 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009821# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009822# if ENABLE_HUSH_FUNCTIONS
9823 /* nommu uses re-exec trick for "... | func | ...",
9824 * should allow "return".
9825 * This accidentally allows returns in subshells.
9826 */
9827 G_flag_return_in_progress = -1;
9828# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009829 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009830 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009831 case 'R':
9832 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009833 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009834 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009835# if ENABLE_HUSH_FUNCTIONS
9836 case 'F': {
9837 struct function *funcp = new_function(optarg);
9838 /* funcp->name is already set to optarg */
9839 /* funcp->body is set to NULL. It's a special case. */
9840 funcp->body_as_string = argv[optind];
9841 optind++;
9842 break;
9843 }
9844# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009845#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009846 case 'n':
9847 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009848 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009849 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009850 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009851 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009852#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009853 fprintf(stderr, "Usage: sh [FILE]...\n"
9854 " or: sh -c command [args]...\n\n");
9855 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009856#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009857 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009858#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009859 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009860 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009861
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009862 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9863 G.global_argc = argc - (optind - 1);
9864 G.global_argv = argv + (optind - 1);
9865 G.global_argv[0] = argv[0];
9866
Denys Vlasenkodea47882009-10-09 15:40:49 +02009867 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009868 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009869 G.root_ppid = getppid();
9870 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009871
9872 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009873 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009874 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009875 debug_printf("sourcing /etc/profile\n");
9876 input = fopen_for_read("/etc/profile");
9877 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009878 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009879 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009880 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009881 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009882 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009883 /* bash: after sourcing /etc/profile,
9884 * tries to source (in the given order):
9885 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009886 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009887 * bash also sources ~/.bash_logout on exit.
9888 * If called as sh, skips .bash_XXX files.
9889 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009890 }
9891
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009892 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9893 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009894 FILE *input;
9895 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009896 * "bash <script>" (which is never interactive (unless -i?))
9897 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009898 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009899 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009900 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009901 G.global_argc--;
9902 G.global_argv++;
9903 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009904 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009905 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009906 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009907 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009908 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009909 parse_and_run_file(input);
9910#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009911 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009912#endif
9913 goto final_return;
9914 }
9915
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009916 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009917 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009918 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009919
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009920 /* A shell is interactive if the '-i' flag was given,
9921 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009922 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009923 * no arguments remaining or the -s flag given
9924 * standard input is a terminal
9925 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009926 * Refer to Posix.2, the description of the 'sh' utility.
9927 */
9928#if ENABLE_HUSH_JOB
9929 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009930 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9931 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9932 if (G_saved_tty_pgrp < 0)
9933 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009934
9935 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009936 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009937 if (G_interactive_fd < 0) {
9938 /* try to dup to any fd */
9939 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009940 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009941 /* give up */
9942 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009943 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009944 }
9945 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009946// TODO: track & disallow any attempts of user
9947// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009948 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009949 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009950 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009951 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009952
Mike Frysinger38478a62009-05-20 04:48:06 -04009953 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009954 /* If we were run as 'hush &', sleep until we are
9955 * in the foreground (tty pgrp == our pgrp).
9956 * If we get started under a job aware app (like bash),
9957 * make sure we are now in charge so we don't fight over
9958 * who gets the foreground */
9959 while (1) {
9960 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009961 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9962 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009963 break;
9964 /* send TTIN to ourself (should stop us) */
9965 kill(- shell_pgrp, SIGTTIN);
9966 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009967 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009968
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009969 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009970 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009971
Mike Frysinger38478a62009-05-20 04:48:06 -04009972 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009973 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009974 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009975 /* Put ourselves in our own process group
9976 * (bash, too, does this only if ctty is available) */
9977 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9978 /* Grab control of the terminal */
9979 tcsetpgrp(G_interactive_fd, getpid());
9980 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009981 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009982
9983# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9984 {
9985 const char *hp = get_local_var_value("HISTFILE");
9986 if (!hp) {
9987 hp = get_local_var_value("HOME");
9988 if (hp)
9989 hp = concat_path_file(hp, ".hush_history");
9990 } else {
9991 hp = xstrdup(hp);
9992 }
9993 if (hp) {
9994 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009995 //set_local_var(xasprintf("HISTFILE=%s", ...));
9996 }
9997# if ENABLE_FEATURE_SH_HISTFILESIZE
9998 hp = get_local_var_value("HISTFILESIZE");
9999 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10000# endif
10001 }
10002# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010003 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010004 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010005 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010006#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010007 /* No job control compiled in, only prompt/line editing */
10008 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010009 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010010 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010011 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010012 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010013 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010014 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010015 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010016 }
10017 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010018 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010019 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010020 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010021 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010022#else
10023 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010024 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010025#endif
10026 /* bash:
10027 * if interactive but not a login shell, sources ~/.bashrc
10028 * (--norc turns this off, --rcfile <file> overrides)
10029 */
10030
10031 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010032 /* note: ash and hush share this string */
10033 printf("\n\n%s %s\n"
10034 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10035 "\n",
10036 bb_banner,
10037 "hush - the humble shell"
10038 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010039 }
10040
Denis Vlasenkof9375282009-04-05 19:13:39 +000010041 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +000010042
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010043 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010044 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010045}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010046
10047
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010048/*
10049 * Built-ins
10050 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010051static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010052{
10053 return 0;
10054}
10055
Denys Vlasenko265062d2017-01-10 15:13:30 +010010056#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010057static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010058{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010059 int argc = string_array_len(argv);
10060 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010061}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010062#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010063#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010064static int FAST_FUNC builtin_test(char **argv)
10065{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010066 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010067}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010068#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010069#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010070static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010071{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010072 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010073}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010074#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010075#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010076static int FAST_FUNC builtin_printf(char **argv)
10077{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010078 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010079}
10080#endif
10081
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010082#if ENABLE_HUSH_HELP
10083static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10084{
10085 const struct built_in_command *x;
10086
10087 printf(
10088 "Built-in commands:\n"
10089 "------------------\n");
10090 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10091 if (x->b_descr)
10092 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10093 }
10094 return EXIT_SUCCESS;
10095}
10096#endif
10097
10098#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10099static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10100{
10101 show_history(G.line_input_state);
10102 return EXIT_SUCCESS;
10103}
10104#endif
10105
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010106static char **skip_dash_dash(char **argv)
10107{
10108 argv++;
10109 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10110 argv++;
10111 return argv;
10112}
10113
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010114static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010115{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010116 const char *newdir;
10117
10118 argv = skip_dash_dash(argv);
10119 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010120 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010121 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010122 * bash says "bash: cd: HOME not set" and does nothing
10123 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010124 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010125 const char *home = get_local_var_value("HOME");
10126 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010127 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010128 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010129 /* Mimic bash message exactly */
10130 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010131 return EXIT_FAILURE;
10132 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010133 /* Read current dir (get_cwd(1) is inside) and set PWD.
10134 * Note: do not enforce exporting. If PWD was unset or unexported,
10135 * set it again, but do not export. bash does the same.
10136 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010137 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010138 return EXIT_SUCCESS;
10139}
10140
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010141static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10142{
10143 puts(get_cwd(0));
10144 return EXIT_SUCCESS;
10145}
10146
10147static int FAST_FUNC builtin_eval(char **argv)
10148{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010149 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010150
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010151 if (!argv[0])
10152 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010153
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010154 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010155 /* bash:
10156 * eval "echo Hi; done" ("done" is syntax error):
10157 * "echo Hi" will not execute too.
10158 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010159 parse_and_run_string(argv[0]);
10160 } else {
10161 /* "The eval utility shall construct a command by
10162 * concatenating arguments together, separating
10163 * each with a <space> character."
10164 */
10165 char *str, *p;
10166 unsigned len = 0;
10167 char **pp = argv;
10168 do
10169 len += strlen(*pp) + 1;
10170 while (*++pp);
10171 str = p = xmalloc(len);
10172 pp = argv;
10173 for (;;) {
10174 p = stpcpy(p, *pp);
10175 pp++;
10176 if (!*pp)
10177 break;
10178 *p++ = ' ';
10179 }
10180 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010181 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010182 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010183 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010184}
10185
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010186static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010187{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010188 argv = skip_dash_dash(argv);
10189 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010190 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010191
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010192 /* Careful: we can end up here after [v]fork. Do not restore
10193 * tty pgrp then, only top-level shell process does that */
10194 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10195 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10196
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010197 /* Saved-redirect fds, script fds and G_interactive_fd are still
10198 * open here. However, they are all CLOEXEC, and execv below
10199 * closes them. Try interactive "exec ls -l /proc/self/fd",
10200 * it should show no extra open fds in the "ls" process.
10201 * If we'd try to run builtins/NOEXECs, this would need improving.
10202 */
10203 //close_saved_fds_and_FILE_fds();
10204
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010205 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010206 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010207 * and tcsetpgrp, and this is inherently racy.
10208 */
10209 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010210}
10211
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010212static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010213{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010214 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010215
10216 /* interactive bash:
10217 * # trap "echo EEE" EXIT
10218 * # exit
10219 * exit
10220 * There are stopped jobs.
10221 * (if there are _stopped_ jobs, running ones don't count)
10222 * # exit
10223 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010224 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010225 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010226 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010227 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010228
10229 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010230 argv = skip_dash_dash(argv);
10231 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010232 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010233 /* mimic bash: exit 123abc == exit 255 + error msg */
10234 xfunc_error_retval = 255;
10235 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010236 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010237}
10238
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010239#if ENABLE_HUSH_TYPE
10240/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10241static int FAST_FUNC builtin_type(char **argv)
10242{
10243 int ret = EXIT_SUCCESS;
10244
10245 while (*++argv) {
10246 const char *type;
10247 char *path = NULL;
10248
10249 if (0) {} /* make conditional compile easier below */
10250 /*else if (find_alias(*argv))
10251 type = "an alias";*/
10252#if ENABLE_HUSH_FUNCTIONS
10253 else if (find_function(*argv))
10254 type = "a function";
10255#endif
10256 else if (find_builtin(*argv))
10257 type = "a shell builtin";
10258 else if ((path = find_in_path(*argv)) != NULL)
10259 type = path;
10260 else {
10261 bb_error_msg("type: %s: not found", *argv);
10262 ret = EXIT_FAILURE;
10263 continue;
10264 }
10265
10266 printf("%s is %s\n", *argv, type);
10267 free(path);
10268 }
10269
10270 return ret;
10271}
10272#endif
10273
10274#if ENABLE_HUSH_READ
10275/* Interruptibility of read builtin in bash
10276 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10277 *
10278 * Empty trap makes read ignore corresponding signal, for any signal.
10279 *
10280 * SIGINT:
10281 * - terminates non-interactive shell;
10282 * - interrupts read in interactive shell;
10283 * if it has non-empty trap:
10284 * - executes trap and returns to command prompt in interactive shell;
10285 * - executes trap and returns to read in non-interactive shell;
10286 * SIGTERM:
10287 * - is ignored (does not interrupt) read in interactive shell;
10288 * - terminates non-interactive shell;
10289 * if it has non-empty trap:
10290 * - executes trap and returns to read;
10291 * SIGHUP:
10292 * - terminates shell (regardless of interactivity);
10293 * if it has non-empty trap:
10294 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010295 * SIGCHLD from children:
10296 * - does not interrupt read regardless of interactivity:
10297 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010298 */
10299static int FAST_FUNC builtin_read(char **argv)
10300{
10301 const char *r;
10302 char *opt_n = NULL;
10303 char *opt_p = NULL;
10304 char *opt_t = NULL;
10305 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010306 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010307 const char *ifs;
10308 int read_flags;
10309
10310 /* "!": do not abort on errors.
10311 * Option string must start with "sr" to match BUILTIN_READ_xxx
10312 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010313 read_flags = getopt32(argv,
10314#if BASH_READ_D
10315 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10316#else
10317 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10318#endif
10319 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010320 if (read_flags == (uint32_t)-1)
10321 return EXIT_FAILURE;
10322 argv += optind;
10323 ifs = get_local_var_value("IFS"); /* can be NULL */
10324
10325 again:
10326 r = shell_builtin_read(set_local_var_from_halves,
10327 argv,
10328 ifs,
10329 read_flags,
10330 opt_n,
10331 opt_p,
10332 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010333 opt_u,
10334 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010335 );
10336
10337 if ((uintptr_t)r == 1 && errno == EINTR) {
10338 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010339 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010340 goto again;
10341 }
10342
10343 if ((uintptr_t)r > 1) {
10344 bb_error_msg("%s", r);
10345 r = (char*)(uintptr_t)1;
10346 }
10347
10348 return (uintptr_t)r;
10349}
10350#endif
10351
10352#if ENABLE_HUSH_UMASK
10353static int FAST_FUNC builtin_umask(char **argv)
10354{
10355 int rc;
10356 mode_t mask;
10357
10358 rc = 1;
10359 mask = umask(0);
10360 argv = skip_dash_dash(argv);
10361 if (argv[0]) {
10362 mode_t old_mask = mask;
10363
10364 /* numeric umasks are taken as-is */
10365 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10366 if (!isdigit(argv[0][0]))
10367 mask ^= 0777;
10368 mask = bb_parse_mode(argv[0], mask);
10369 if (!isdigit(argv[0][0]))
10370 mask ^= 0777;
10371 if ((unsigned)mask > 0777) {
10372 mask = old_mask;
10373 /* bash messages:
10374 * bash: umask: 'q': invalid symbolic mode operator
10375 * bash: umask: 999: octal number out of range
10376 */
10377 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10378 rc = 0;
10379 }
10380 } else {
10381 /* Mimic bash */
10382 printf("%04o\n", (unsigned) mask);
10383 /* fall through and restore mask which we set to 0 */
10384 }
10385 umask(mask);
10386
10387 return !rc; /* rc != 0 - success */
10388}
10389#endif
10390
Denys Vlasenko41ade052017-01-08 18:56:24 +010010391#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010392static void print_escaped(const char *s)
10393{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010394 if (*s == '\'')
10395 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010396 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010397 const char *p = strchrnul(s, '\'');
10398 /* print 'xxxx', possibly just '' */
10399 printf("'%.*s'", (int)(p - s), s);
10400 if (*p == '\0')
10401 break;
10402 s = p;
10403 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010404 /* s points to '; print "'''...'''" */
10405 putchar('"');
10406 do putchar('\''); while (*++s == '\'');
10407 putchar('"');
10408 } while (*s);
10409}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010410#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010411
Denys Vlasenko1e660422017-07-17 21:10:50 +020010412#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010413static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010414{
10415 do {
10416 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010417 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010418
10419 /* So far we do not check that name is valid (TODO?) */
10420
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010421 if (*name_end == '\0') {
10422 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010423
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010424 vpp = get_ptr_to_local_var(name, name_end - name);
10425 var = vpp ? *vpp : NULL;
10426
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010427 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010428 /* export -n NAME (without =VALUE) */
10429 if (var) {
10430 var->flg_export = 0;
10431 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10432 unsetenv(name);
10433 } /* else: export -n NOT_EXISTING_VAR: no-op */
10434 continue;
10435 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010436 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010437 /* export NAME (without =VALUE) */
10438 if (var) {
10439 var->flg_export = 1;
10440 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10441 putenv(var->varstr);
10442 continue;
10443 }
10444 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010445 if (flags & SETFLAG_MAKE_RO) {
10446 /* readonly NAME (without =VALUE) */
10447 if (var) {
10448 var->flg_read_only = 1;
10449 continue;
10450 }
10451 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010452# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010453 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010454 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010455 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10456 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010457 /* "local x=abc; ...; local x" - ignore second local decl */
10458 continue;
10459 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010460 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010461# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010462 /* Exporting non-existing variable.
10463 * bash does not put it in environment,
10464 * but remembers that it is exported,
10465 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010466 * We just set it to "" and export.
10467 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010468 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010469 * bash sets the value to "".
10470 */
10471 /* Or, it's "readonly NAME" (without =VALUE).
10472 * bash remembers NAME and disallows its creation
10473 * in the future.
10474 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010475 name = xasprintf("%s=", name);
10476 } else {
10477 /* (Un)exporting/making local NAME=VALUE */
10478 name = xstrdup(name);
10479 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010480 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010481 if (set_local_var(name, flags))
10482 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010483 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010484 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010485}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010486#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010487
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010488#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010489static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010490{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010491 unsigned opt_unexport;
10492
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010493#if ENABLE_HUSH_EXPORT_N
10494 /* "!": do not abort on errors */
10495 opt_unexport = getopt32(argv, "!n");
10496 if (opt_unexport == (uint32_t)-1)
10497 return EXIT_FAILURE;
10498 argv += optind;
10499#else
10500 opt_unexport = 0;
10501 argv++;
10502#endif
10503
10504 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010505 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010506 if (e) {
10507 while (*e) {
10508#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010509 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010510#else
10511 /* ash emits: export VAR='VAL'
10512 * bash: declare -x VAR="VAL"
10513 * we follow ash example */
10514 const char *s = *e++;
10515 const char *p = strchr(s, '=');
10516
10517 if (!p) /* wtf? take next variable */
10518 continue;
10519 /* export var= */
10520 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010521 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010522 putchar('\n');
10523#endif
10524 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010525 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010526 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010527 return EXIT_SUCCESS;
10528 }
10529
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010530 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010531}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010532#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010533
Denys Vlasenko295fef82009-06-03 12:47:26 +020010534#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010535static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010536{
10537 if (G.func_nest_level == 0) {
10538 bb_error_msg("%s: not in a function", argv[0]);
10539 return EXIT_FAILURE; /* bash compat */
10540 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010541 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010542 /* Since all builtins run in a nested variable level,
10543 * need to use level - 1 here. Or else the variable will be removed at once
10544 * after builtin returns.
10545 */
10546 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010547}
10548#endif
10549
Denys Vlasenko1e660422017-07-17 21:10:50 +020010550#if ENABLE_HUSH_READONLY
10551static int FAST_FUNC builtin_readonly(char **argv)
10552{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010553 argv++;
10554 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010555 /* bash: readonly [-p]: list all readonly VARs
10556 * (-p has no effect in bash)
10557 */
10558 struct variable *e;
10559 for (e = G.top_var; e; e = e->next) {
10560 if (e->flg_read_only) {
10561//TODO: quote value: readonly VAR='VAL'
10562 printf("readonly %s\n", e->varstr);
10563 }
10564 }
10565 return EXIT_SUCCESS;
10566 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010567 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010568}
10569#endif
10570
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010571#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010572/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10573static int FAST_FUNC builtin_unset(char **argv)
10574{
10575 int ret;
10576 unsigned opts;
10577
10578 /* "!": do not abort on errors */
10579 /* "+": stop at 1st non-option */
10580 opts = getopt32(argv, "!+vf");
10581 if (opts == (unsigned)-1)
10582 return EXIT_FAILURE;
10583 if (opts == 3) {
10584 bb_error_msg("unset: -v and -f are exclusive");
10585 return EXIT_FAILURE;
10586 }
10587 argv += optind;
10588
10589 ret = EXIT_SUCCESS;
10590 while (*argv) {
10591 if (!(opts & 2)) { /* not -f */
10592 if (unset_local_var(*argv)) {
10593 /* unset <nonexistent_var> doesn't fail.
10594 * Error is when one tries to unset RO var.
10595 * Message was printed by unset_local_var. */
10596 ret = EXIT_FAILURE;
10597 }
10598 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010599# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010600 else {
10601 unset_func(*argv);
10602 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010603# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010604 argv++;
10605 }
10606 return ret;
10607}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010608#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010609
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010610#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010611/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10612 * built-in 'set' handler
10613 * SUSv3 says:
10614 * set [-abCefhmnuvx] [-o option] [argument...]
10615 * set [+abCefhmnuvx] [+o option] [argument...]
10616 * set -- [argument...]
10617 * set -o
10618 * set +o
10619 * Implementations shall support the options in both their hyphen and
10620 * plus-sign forms. These options can also be specified as options to sh.
10621 * Examples:
10622 * Write out all variables and their values: set
10623 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10624 * Turn on the -x and -v options: set -xv
10625 * Unset all positional parameters: set --
10626 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10627 * Set the positional parameters to the expansion of x, even if x expands
10628 * with a leading '-' or '+': set -- $x
10629 *
10630 * So far, we only support "set -- [argument...]" and some of the short names.
10631 */
10632static int FAST_FUNC builtin_set(char **argv)
10633{
10634 int n;
10635 char **pp, **g_argv;
10636 char *arg = *++argv;
10637
10638 if (arg == NULL) {
10639 struct variable *e;
10640 for (e = G.top_var; e; e = e->next)
10641 puts(e->varstr);
10642 return EXIT_SUCCESS;
10643 }
10644
10645 do {
10646 if (strcmp(arg, "--") == 0) {
10647 ++argv;
10648 goto set_argv;
10649 }
10650 if (arg[0] != '+' && arg[0] != '-')
10651 break;
10652 for (n = 1; arg[n]; ++n) {
10653 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10654 goto error;
10655 if (arg[n] == 'o' && argv[1])
10656 argv++;
10657 }
10658 } while ((arg = *++argv) != NULL);
10659 /* Now argv[0] is 1st argument */
10660
10661 if (arg == NULL)
10662 return EXIT_SUCCESS;
10663 set_argv:
10664
10665 /* NB: G.global_argv[0] ($0) is never freed/changed */
10666 g_argv = G.global_argv;
10667 if (G.global_args_malloced) {
10668 pp = g_argv;
10669 while (*++pp)
10670 free(*pp);
10671 g_argv[1] = NULL;
10672 } else {
10673 G.global_args_malloced = 1;
10674 pp = xzalloc(sizeof(pp[0]) * 2);
10675 pp[0] = g_argv[0]; /* retain $0 */
10676 g_argv = pp;
10677 }
10678 /* This realloc's G.global_argv */
10679 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10680
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010681 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010682
10683 return EXIT_SUCCESS;
10684
10685 /* Nothing known, so abort */
10686 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010687 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010688 return EXIT_FAILURE;
10689}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010690#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010691
10692static int FAST_FUNC builtin_shift(char **argv)
10693{
10694 int n = 1;
10695 argv = skip_dash_dash(argv);
10696 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010697 n = bb_strtou(argv[0], NULL, 10);
10698 if (errno || n < 0) {
10699 /* shared string with ash.c */
10700 bb_error_msg("Illegal number: %s", argv[0]);
10701 /*
10702 * ash aborts in this case.
10703 * bash prints error message and set $? to 1.
10704 * Interestingly, for "shift 99999" bash does not
10705 * print error message, but does set $? to 1
10706 * (and does no shifting at all).
10707 */
10708 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010709 }
10710 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010711 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010712 int m = 1;
10713 while (m <= n)
10714 free(G.global_argv[m++]);
10715 }
10716 G.global_argc -= n;
10717 memmove(&G.global_argv[1], &G.global_argv[n+1],
10718 G.global_argc * sizeof(G.global_argv[0]));
10719 return EXIT_SUCCESS;
10720 }
10721 return EXIT_FAILURE;
10722}
10723
Denys Vlasenko74d40582017-08-11 01:32:46 +020010724#if ENABLE_HUSH_GETOPTS
10725static int FAST_FUNC builtin_getopts(char **argv)
10726{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010727/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10728
Denys Vlasenko74d40582017-08-11 01:32:46 +020010729TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010730If a required argument is not found, and getopts is not silent,
10731a question mark (?) is placed in VAR, OPTARG is unset, and a
10732diagnostic message is printed. If getopts is silent, then a
10733colon (:) is placed in VAR and OPTARG is set to the option
10734character found.
10735
10736Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010737
10738"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010739*/
10740 char cbuf[2];
10741 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010742 int c, n, exitcode, my_opterr;
10743 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010744
10745 optstring = *++argv;
10746 if (!optstring || !(var = *++argv)) {
10747 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10748 return EXIT_FAILURE;
10749 }
10750
Denys Vlasenko238ff982017-08-29 13:38:30 +020010751 if (argv[1])
10752 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10753 else
10754 argv = G.global_argv;
10755 cbuf[1] = '\0';
10756
10757 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010758 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010759 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010760 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010761 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010762 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010763
10764 /* getopts stops on first non-option. Add "+" to force that */
10765 /*if (optstring[0] != '+')*/ {
10766 char *s = alloca(strlen(optstring) + 2);
10767 sprintf(s, "+%s", optstring);
10768 optstring = s;
10769 }
10770
Denys Vlasenko238ff982017-08-29 13:38:30 +020010771 /* Naively, now we should just
10772 * cp = get_local_var_value("OPTIND");
10773 * optind = cp ? atoi(cp) : 0;
10774 * optarg = NULL;
10775 * opterr = my_opterr;
10776 * c = getopt(string_array_len(argv), argv, optstring);
10777 * and be done? Not so fast...
10778 * Unlike normal getopt() usage in C programs, here
10779 * each successive call will (usually) have the same argv[] CONTENTS,
10780 * but not the ADDRESSES. Worse yet, it's possible that between
10781 * invocations of "getopts", there will be calls to shell builtins
10782 * which use getopt() internally. Example:
10783 * while getopts "abc" RES -a -bc -abc de; do
10784 * unset -ff func
10785 * done
10786 * This would not work correctly: getopt() call inside "unset"
10787 * modifies internal libc state which is tracking position in
10788 * multi-option strings ("-abc"). At best, it can skip options
10789 * or return the same option infinitely. With glibc implementation
10790 * of getopt(), it would use outright invalid pointers and return
10791 * garbage even _without_ "unset" mangling internal state.
10792 *
10793 * We resort to resetting getopt() state and calling it N times,
10794 * until we get Nth result (or failure).
10795 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10796 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010797 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010798 count = 0;
10799 n = string_array_len(argv);
10800 do {
10801 optarg = NULL;
10802 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10803 c = getopt(n, argv, optstring);
10804 if (c < 0)
10805 break;
10806 count++;
10807 } while (count <= G.getopt_count);
10808
10809 /* Set OPTIND. Prevent resetting of the magic counter! */
10810 set_local_var_from_halves("OPTIND", utoa(optind));
10811 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010812 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010813
10814 /* Set OPTARG */
10815 /* Always set or unset, never left as-is, even on exit/error:
10816 * "If no option was found, or if the option that was found
10817 * does not have an option-argument, OPTARG shall be unset."
10818 */
10819 cp = optarg;
10820 if (c == '?') {
10821 /* If ":optstring" and unknown option is seen,
10822 * it is stored to OPTARG.
10823 */
10824 if (optstring[1] == ':') {
10825 cbuf[0] = optopt;
10826 cp = cbuf;
10827 }
10828 }
10829 if (cp)
10830 set_local_var_from_halves("OPTARG", cp);
10831 else
10832 unset_local_var("OPTARG");
10833
10834 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010835 exitcode = EXIT_SUCCESS;
10836 if (c < 0) { /* -1: end of options */
10837 exitcode = EXIT_FAILURE;
10838 c = '?';
10839 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010840
Denys Vlasenko238ff982017-08-29 13:38:30 +020010841 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010842 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010843 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010844
Denys Vlasenko74d40582017-08-11 01:32:46 +020010845 return exitcode;
10846}
10847#endif
10848
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010849static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010850{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010851 char *arg_path, *filename;
10852 FILE *input;
10853 save_arg_t sv;
10854 char *args_need_save;
10855#if ENABLE_HUSH_FUNCTIONS
10856 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010857#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010858
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010859 argv = skip_dash_dash(argv);
10860 filename = argv[0];
10861 if (!filename) {
10862 /* bash says: "bash: .: filename argument required" */
10863 return 2; /* bash compat */
10864 }
10865 arg_path = NULL;
10866 if (!strchr(filename, '/')) {
10867 arg_path = find_in_path(filename);
10868 if (arg_path)
10869 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010870 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010871 errno = ENOENT;
10872 bb_simple_perror_msg(filename);
10873 return EXIT_FAILURE;
10874 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010875 }
10876 input = remember_FILE(fopen_or_warn(filename, "r"));
10877 free(arg_path);
10878 if (!input) {
10879 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10880 /* POSIX: non-interactive shell should abort here,
10881 * not merely fail. So far no one complained :)
10882 */
10883 return EXIT_FAILURE;
10884 }
10885
10886#if ENABLE_HUSH_FUNCTIONS
10887 sv_flg = G_flag_return_in_progress;
10888 /* "we are inside sourced file, ok to use return" */
10889 G_flag_return_in_progress = -1;
10890#endif
10891 args_need_save = argv[1]; /* used as a boolean variable */
10892 if (args_need_save)
10893 save_and_replace_G_args(&sv, argv);
10894
10895 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10896 G.last_exitcode = 0;
10897 parse_and_run_file(input);
10898 fclose_and_forget(input);
10899
10900 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10901 restore_G_args(&sv, argv);
10902#if ENABLE_HUSH_FUNCTIONS
10903 G_flag_return_in_progress = sv_flg;
10904#endif
10905
10906 return G.last_exitcode;
10907}
10908
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010909#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010910static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010911{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010912 int sig;
10913 char *new_cmd;
10914
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010915 if (!G_traps)
10916 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010917
10918 argv++;
10919 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010920 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010921 /* No args: print all trapped */
10922 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010923 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010924 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010925 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010926 /* note: bash adds "SIG", but only if invoked
10927 * as "bash". If called as "sh", or if set -o posix,
10928 * then it prints short signal names.
10929 * We are printing short names: */
10930 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010931 }
10932 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010933 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010934 return EXIT_SUCCESS;
10935 }
10936
10937 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010938 /* If first arg is a number: reset all specified signals */
10939 sig = bb_strtou(*argv, NULL, 10);
10940 if (errno == 0) {
10941 int ret;
10942 process_sig_list:
10943 ret = EXIT_SUCCESS;
10944 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010945 sighandler_t handler;
10946
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010947 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010948 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010949 ret = EXIT_FAILURE;
10950 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010951 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010952 continue;
10953 }
10954
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010955 free(G_traps[sig]);
10956 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010957
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010958 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010959 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010960
10961 /* There is no signal for 0 (EXIT) */
10962 if (sig == 0)
10963 continue;
10964
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010965 if (new_cmd)
10966 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10967 else
10968 /* We are removing trap handler */
10969 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010970 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010971 }
10972 return ret;
10973 }
10974
10975 if (!argv[1]) { /* no second arg */
10976 bb_error_msg("trap: invalid arguments");
10977 return EXIT_FAILURE;
10978 }
10979
10980 /* First arg is "-": reset all specified to default */
10981 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10982 /* Everything else: set arg as signal handler
10983 * (includes "" case, which ignores signal) */
10984 if (argv[0][0] == '-') {
10985 if (argv[0][1] == '\0') { /* "-" */
10986 /* new_cmd remains NULL: "reset these sigs" */
10987 goto reset_traps;
10988 }
10989 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10990 argv++;
10991 }
10992 /* else: "-something", no special meaning */
10993 }
10994 new_cmd = *argv;
10995 reset_traps:
10996 argv++;
10997 goto process_sig_list;
10998}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010999#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011000
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011001#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011002static struct pipe *parse_jobspec(const char *str)
11003{
11004 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011005 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011006
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011007 if (sscanf(str, "%%%u", &jobnum) != 1) {
11008 if (str[0] != '%'
11009 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11010 ) {
11011 bb_error_msg("bad argument '%s'", str);
11012 return NULL;
11013 }
11014 /* It is "%%", "%+" or "%" - current job */
11015 jobnum = G.last_jobid;
11016 if (jobnum == 0) {
11017 bb_error_msg("no current job");
11018 return NULL;
11019 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011020 }
11021 for (pi = G.job_list; pi; pi = pi->next) {
11022 if (pi->jobid == jobnum) {
11023 return pi;
11024 }
11025 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011026 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011027 return NULL;
11028}
11029
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011030static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11031{
11032 struct pipe *job;
11033 const char *status_string;
11034
11035 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11036 for (job = G.job_list; job; job = job->next) {
11037 if (job->alive_cmds == job->stopped_cmds)
11038 status_string = "Stopped";
11039 else
11040 status_string = "Running";
11041
11042 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11043 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011044
11045 clean_up_last_dead_job();
11046
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011047 return EXIT_SUCCESS;
11048}
11049
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011050/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011051static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011052{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011053 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011054 struct pipe *pi;
11055
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011056 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011057 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011058
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011059 /* If they gave us no args, assume they want the last backgrounded task */
11060 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011061 for (pi = G.job_list; pi; pi = pi->next) {
11062 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011063 goto found;
11064 }
11065 }
11066 bb_error_msg("%s: no current job", argv[0]);
11067 return EXIT_FAILURE;
11068 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011069
11070 pi = parse_jobspec(argv[1]);
11071 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011072 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011073 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011074 /* TODO: bash prints a string representation
11075 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011076 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011077 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011078 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011079 }
11080
11081 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011082 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11083 for (i = 0; i < pi->num_cmds; i++) {
11084 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011085 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011086 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011087
11088 i = kill(- pi->pgrp, SIGCONT);
11089 if (i < 0) {
11090 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011091 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011092 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011093 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011094 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011095 }
11096
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011097 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011098 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011099 return checkjobs_and_fg_shell(pi);
11100 }
11101 return EXIT_SUCCESS;
11102}
11103#endif
11104
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011105#if ENABLE_HUSH_KILL
11106static int FAST_FUNC builtin_kill(char **argv)
11107{
11108 int ret = 0;
11109
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011110# if ENABLE_HUSH_JOB
11111 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11112 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011113
11114 do {
11115 struct pipe *pi;
11116 char *dst;
11117 int j, n;
11118
11119 if (argv[i][0] != '%')
11120 continue;
11121 /*
11122 * "kill %N" - job kill
11123 * Converting to pgrp / pid kill
11124 */
11125 pi = parse_jobspec(argv[i]);
11126 if (!pi) {
11127 /* Eat bad jobspec */
11128 j = i;
11129 do {
11130 j++;
11131 argv[j - 1] = argv[j];
11132 } while (argv[j]);
11133 ret = 1;
11134 i--;
11135 continue;
11136 }
11137 /*
11138 * In jobs started under job control, we signal
11139 * entire process group by kill -PGRP_ID.
11140 * This happens, f.e., in interactive shell.
11141 *
11142 * Otherwise, we signal each child via
11143 * kill PID1 PID2 PID3.
11144 * Testcases:
11145 * sh -c 'sleep 1|sleep 1 & kill %1'
11146 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11147 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11148 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011149 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011150 dst = alloca(n * sizeof(int)*4);
11151 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011152 if (G_interactive_fd)
11153 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011154 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011155 struct command *cmd = &pi->cmds[j];
11156 /* Skip exited members of the job */
11157 if (cmd->pid == 0)
11158 continue;
11159 /*
11160 * kill_main has matching code to expect
11161 * leading space. Needed to not confuse
11162 * negative pids with "kill -SIGNAL_NO" syntax
11163 */
11164 dst += sprintf(dst, " %u", (int)cmd->pid);
11165 }
11166 *dst = '\0';
11167 } while (argv[++i]);
11168 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011169# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011170
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011171 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011172 ret = run_applet_main(argv, kill_main);
11173 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011174 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011175 return ret;
11176}
11177#endif
11178
11179#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011180/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011181#if !ENABLE_HUSH_JOB
11182# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11183#endif
11184static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011185{
11186 int ret = 0;
11187 for (;;) {
11188 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011189 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011190
Denys Vlasenko830ea352016-11-08 04:59:11 +010011191 if (!sigisemptyset(&G.pending_set))
11192 goto check_sig;
11193
Denys Vlasenko7e675362016-10-28 21:57:31 +020011194 /* waitpid is not interruptible by SA_RESTARTed
11195 * signals which we use. Thus, this ugly dance:
11196 */
11197
11198 /* Make sure possible SIGCHLD is stored in kernel's
11199 * pending signal mask before we call waitpid.
11200 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011201 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011202 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011203 sigfillset(&oldset); /* block all signals, remember old set */
11204 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011205
11206 if (!sigisemptyset(&G.pending_set)) {
11207 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011208 goto restore;
11209 }
11210
11211 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011212/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011213 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011214 debug_printf_exec("checkjobs:%d\n", ret);
11215#if ENABLE_HUSH_JOB
11216 if (waitfor_pipe) {
11217 int rcode = job_exited_or_stopped(waitfor_pipe);
11218 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11219 if (rcode >= 0) {
11220 ret = rcode;
11221 sigprocmask(SIG_SETMASK, &oldset, NULL);
11222 break;
11223 }
11224 }
11225#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011226 /* if ECHILD, there are no children (ret is -1 or 0) */
11227 /* if ret == 0, no children changed state */
11228 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011229 if (errno == ECHILD || ret) {
11230 ret--;
11231 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011232 ret = 0;
11233 sigprocmask(SIG_SETMASK, &oldset, NULL);
11234 break;
11235 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011236 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011237 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11238 /* Note: sigsuspend invokes signal handler */
11239 sigsuspend(&oldset);
11240 restore:
11241 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011242 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011243 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011244 sig = check_and_run_traps();
11245 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011246 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011247 ret = 128 + sig;
11248 break;
11249 }
11250 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11251 }
11252 return ret;
11253}
11254
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011255static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011256{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011257 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011258 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011259
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011260 argv = skip_dash_dash(argv);
11261 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011262 /* Don't care about wait results */
11263 /* Note 1: must wait until there are no more children */
11264 /* Note 2: must be interruptible */
11265 /* Examples:
11266 * $ sleep 3 & sleep 6 & wait
11267 * [1] 30934 sleep 3
11268 * [2] 30935 sleep 6
11269 * [1] Done sleep 3
11270 * [2] Done sleep 6
11271 * $ sleep 3 & sleep 6 & wait
11272 * [1] 30936 sleep 3
11273 * [2] 30937 sleep 6
11274 * [1] Done sleep 3
11275 * ^C <-- after ~4 sec from keyboard
11276 * $
11277 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011278 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011279 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011280
Denys Vlasenko7e675362016-10-28 21:57:31 +020011281 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011282 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011283 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011284#if ENABLE_HUSH_JOB
11285 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011286 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011287 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011288 wait_pipe = parse_jobspec(*argv);
11289 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011290 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011291 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011292 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011293 } else {
11294 /* waiting on "last dead job" removes it */
11295 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011296 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011297 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011298 /* else: parse_jobspec() already emitted error msg */
11299 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011300 }
11301#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011302 /* mimic bash message */
11303 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011304 ret = EXIT_FAILURE;
11305 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011306 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011307
Denys Vlasenko7e675362016-10-28 21:57:31 +020011308 /* Do we have such child? */
11309 ret = waitpid(pid, &status, WNOHANG);
11310 if (ret < 0) {
11311 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011312 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011313 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011314 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011315 /* "wait $!" but last bg task has already exited. Try:
11316 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11317 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011318 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011319 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011320 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011321 } else {
11322 /* Example: "wait 1". mimic bash message */
11323 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011324 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011325 } else {
11326 /* ??? */
11327 bb_perror_msg("wait %s", *argv);
11328 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011329 continue; /* bash checks all argv[] */
11330 }
11331 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011332 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011333 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011334 } else {
11335 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011336 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011337 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011338 if (WIFSIGNALED(status))
11339 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011340 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011341 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011342
11343 return ret;
11344}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011345#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011346
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011347#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11348static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11349{
11350 if (argv[1]) {
11351 def = bb_strtou(argv[1], NULL, 10);
11352 if (errno || def < def_min || argv[2]) {
11353 bb_error_msg("%s: bad arguments", argv[0]);
11354 def = UINT_MAX;
11355 }
11356 }
11357 return def;
11358}
11359#endif
11360
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011361#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011362static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011363{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011364 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011365 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011366 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011367 /* if we came from builtin_continue(), need to undo "= 1" */
11368 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011369 return EXIT_SUCCESS; /* bash compat */
11370 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011371 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011372
11373 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11374 if (depth == UINT_MAX)
11375 G.flag_break_continue = BC_BREAK;
11376 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011377 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011378
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011379 return EXIT_SUCCESS;
11380}
11381
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011382static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011383{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011384 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11385 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011386}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011387#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011388
11389#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011390static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011391{
11392 int rc;
11393
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011394 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011395 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11396 return EXIT_FAILURE; /* bash compat */
11397 }
11398
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011399 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011400
11401 /* bash:
11402 * out of range: wraps around at 256, does not error out
11403 * non-numeric param:
11404 * f() { false; return qwe; }; f; echo $?
11405 * bash: return: qwe: numeric argument required <== we do this
11406 * 255 <== we also do this
11407 */
11408 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11409 return rc;
11410}
11411#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011412
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011413#if ENABLE_HUSH_TIMES
11414static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11415{
11416 static const uint8_t times_tbl[] ALIGN1 = {
11417 ' ', offsetof(struct tms, tms_utime),
11418 '\n', offsetof(struct tms, tms_stime),
11419 ' ', offsetof(struct tms, tms_cutime),
11420 '\n', offsetof(struct tms, tms_cstime),
11421 0
11422 };
11423 const uint8_t *p;
11424 unsigned clk_tck;
11425 struct tms buf;
11426
11427 clk_tck = bb_clk_tck();
11428
11429 times(&buf);
11430 p = times_tbl;
11431 do {
11432 unsigned sec, frac;
11433 unsigned long t;
11434 t = *(clock_t *)(((char *) &buf) + p[1]);
11435 sec = t / clk_tck;
11436 frac = t % clk_tck;
11437 printf("%um%u.%03us%c",
11438 sec / 60, sec % 60,
11439 (frac * 1000) / clk_tck,
11440 p[0]);
11441 p += 2;
11442 } while (*p);
11443
11444 return EXIT_SUCCESS;
11445}
11446#endif
11447
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011448#if ENABLE_HUSH_MEMLEAK
11449static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11450{
11451 void *p;
11452 unsigned long l;
11453
11454# ifdef M_TRIM_THRESHOLD
11455 /* Optional. Reduces probability of false positives */
11456 malloc_trim(0);
11457# endif
11458 /* Crude attempt to find where "free memory" starts,
11459 * sans fragmentation. */
11460 p = malloc(240);
11461 l = (unsigned long)p;
11462 free(p);
11463 p = malloc(3400);
11464 if (l < (unsigned long)p) l = (unsigned long)p;
11465 free(p);
11466
11467
11468# if 0 /* debug */
11469 {
11470 struct mallinfo mi = mallinfo();
11471 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11472 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11473 }
11474# endif
11475
11476 if (!G.memleak_value)
11477 G.memleak_value = l;
11478
11479 l -= G.memleak_value;
11480 if ((long)l < 0)
11481 l = 0;
11482 l /= 1024;
11483 if (l > 127)
11484 l = 127;
11485
11486 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11487 return l;
11488}
11489#endif