blob: 3c6718648d0b8750c34fe38e4c49717ca7d42416 [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
Eric Andersen25f27032001-04-26 23:22:31 +000082 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020083//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020084//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020085//config: default y
86//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020087//config: hush is a small shell. It handles the normal flow control
88//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
89//config: case/esac. Redirections, here documents, $((arithmetic))
90//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +020091//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +020092//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +020093//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +020094//config: It does not handle select, aliases, tilde expansion,
95//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +020096//config:
97//config:config HUSH_BASH_COMPAT
98//config: bool "bash-compatible extensions"
99//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100100//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200101//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200102//config:config HUSH_BRACE_EXPANSION
103//config: bool "Brace expansion"
104//config: default y
105//config: depends on HUSH_BASH_COMPAT
106//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200107//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200108//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100109//config:config HUSH_LINENO_VAR
110//config: bool "$LINENO variable"
111//config: default y
112//config: depends on HUSH_BASH_COMPAT
113//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100114//config:config HUSH_BASH_SOURCE_CURDIR
115//config: bool "'source' and '.' builtins search current directory after $PATH"
116//config: default n # do not encourage non-standard behavior
117//config: depends on HUSH_BASH_COMPAT
118//config: help
119//config: This is not compliant with standards. Avoid if possible.
120//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200121//config:config HUSH_INTERACTIVE
122//config: bool "Interactive mode"
123//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100124//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200125//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200126//config: Enable interactive mode (prompt and command editing).
127//config: Without this, hush simply reads and executes commands
128//config: from stdin just like a shell script from a file.
129//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200130//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200131//config:config HUSH_SAVEHISTORY
132//config: bool "Save command history to .hush_history"
133//config: default y
134//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200135//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200136//config:config HUSH_JOB
137//config: bool "Job control"
138//config: default y
139//config: depends on HUSH_INTERACTIVE
140//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200141//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
142//config: command (not entire shell), fg/bg builtins work. Without this option,
143//config: "cmd &" still works by simply spawning a process and immediately
144//config: prompting for next command (or executing next command in a script),
145//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200146//config:
147//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100148//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200149//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100150//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200151//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200152//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200153//config:
154//config:config HUSH_IF
155//config: bool "Support if/then/elif/else/fi"
156//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100157//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_LOOPS
160//config: bool "Support for, while and until loops"
161//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:
164//config:config HUSH_CASE
165//config: bool "Support case ... esac statement"
166//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100167//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200168//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200169//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_FUNCTIONS
172//config: bool "Support funcname() { commands; } syntax"
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: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200176//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200177//config:
178//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100179//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: default y
181//config: depends on HUSH_FUNCTIONS
182//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200183//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200184//config:
185//config:config HUSH_RANDOM_SUPPORT
186//config: bool "Pseudorandom generator and $RANDOM variable"
187//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100188//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200190//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
191//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200193//config:config HUSH_MODE_X
194//config: bool "Support 'hush -x' option and 'set -x' command"
195//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100196//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200197//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200198//config: This instructs hush to print commands before execution.
199//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200200//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100201//config:config HUSH_ECHO
202//config: bool "echo builtin"
203//config: default y
204//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100205//config:
206//config:config HUSH_PRINTF
207//config: bool "printf builtin"
208//config: default y
209//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100210//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100211//config:config HUSH_TEST
212//config: bool "test builtin"
213//config: default y
214//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
215//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100216//config:config HUSH_HELP
217//config: bool "help builtin"
218//config: default y
219//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100220//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100221//config:config HUSH_EXPORT
222//config: bool "export builtin"
223//config: default y
224//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100225//config:
226//config:config HUSH_EXPORT_N
227//config: bool "Support 'export -n' option"
228//config: default y
229//config: depends on HUSH_EXPORT
230//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200231//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100232//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200233//config:config HUSH_READONLY
234//config: bool "readonly builtin"
235//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200237//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200238//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200239//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100240//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100241//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100242//config: default y
243//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100244//config:
245//config:config HUSH_WAIT
246//config: bool "wait builtin"
247//config: default y
248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100249//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100250//config:config HUSH_COMMAND
251//config: bool "command builtin"
252//config: default y
253//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
254//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100255//config:config HUSH_TRAP
256//config: bool "trap builtin"
257//config: default y
258//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100259//config:
260//config:config HUSH_TYPE
261//config: bool "type builtin"
262//config: default y
263//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100264//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200265//config:config HUSH_TIMES
266//config: bool "times builtin"
267//config: default y
268//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
269//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100270//config:config HUSH_READ
271//config: bool "read builtin"
272//config: default y
273//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100274//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100275//config:config HUSH_SET
276//config: bool "set builtin"
277//config: default y
278//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100279//config:
280//config:config HUSH_UNSET
281//config: bool "unset builtin"
282//config: default y
283//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100284//config:
285//config:config HUSH_ULIMIT
286//config: bool "ulimit builtin"
287//config: default y
288//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100289//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100290//config:config HUSH_UMASK
291//config: bool "umask builtin"
292//config: default y
293//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100294//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200295//config:config HUSH_GETOPTS
296//config: bool "getopts builtin"
297//config: default y
298//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
299//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100300//config:config HUSH_MEMLEAK
301//config: bool "memleak builtin (debugging)"
302//config: default n
303//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200304
Denys Vlasenko20704f02011-03-23 17:59:27 +0100305//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100306// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100307//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100308//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100309
310//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100311//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
312//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100313//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
314
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200315/* -i (interactive) is also accepted,
316 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100317 * NOMMU-specific options are not meant to be used by users,
318 * therefore we don't show them either.
319 */
320//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200321//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100322//usage:#define hush_full_usage "\n\n"
323//usage: "Unix shell interpreter"
324
Denys Vlasenko67047462016-12-22 15:21:58 +0100325#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
326 || defined(__APPLE__) \
327 )
328# include <malloc.h> /* for malloc_trim */
329#endif
330#include <glob.h>
331/* #include <dmalloc.h> */
332#if ENABLE_HUSH_CASE
333# include <fnmatch.h>
334#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200335#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100336#include <sys/utsname.h> /* for setting $HOSTNAME */
337
338#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
339#include "unicode.h"
340#include "shell_common.h"
341#include "math.h"
342#include "match.h"
343#if ENABLE_HUSH_RANDOM_SUPPORT
344# include "random.h"
345#else
346# define CLEAR_RANDOM_T(rnd) ((void)0)
347#endif
348#ifndef F_DUPFD_CLOEXEC
349# define F_DUPFD_CLOEXEC F_DUPFD
350#endif
351#ifndef PIPE_BUF
352# define PIPE_BUF 4096 /* amount of buffering in a pipe */
353#endif
354
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000355
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100356/* So far, all bash compat is controlled by one config option */
357/* Separate defines document which part of code implements what */
358#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
359#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100360#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
361#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200362#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200363#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100364
365
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200366/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000367#define LEAK_HUNTING 0
368#define BUILD_AS_NOMMU 0
369/* Enable/disable sanity checks. Ok to enable in production,
370 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
371 * Keeping 1 for now even in released versions.
372 */
373#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200374/* Slightly bigger (+200 bytes), but faster hush.
375 * So far it only enables a trick with counting SIGCHLDs and forks,
376 * which allows us to do fewer waitpid's.
377 * (we can detect a case where neither forks were done nor SIGCHLDs happened
378 * and therefore waitpid will return the same result as last time)
379 */
380#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200381/* TODO: implement simplified code for users which do not need ${var%...} ops
382 * So far ${var%...} ops are always enabled:
383 */
384#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000385
386
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000387#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000388# undef BB_MMU
389# undef USE_FOR_NOMMU
390# undef USE_FOR_MMU
391# define BB_MMU 0
392# define USE_FOR_NOMMU(...) __VA_ARGS__
393# define USE_FOR_MMU(...)
394#endif
395
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200396#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100397#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000398/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000399# undef CONFIG_FEATURE_SH_STANDALONE
400# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000401# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100402# undef IF_NOT_FEATURE_SH_STANDALONE
403# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000404# define IF_FEATURE_SH_STANDALONE(...)
405# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000406#endif
407
Denis Vlasenko05743d72008-02-10 12:10:08 +0000408#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000409# undef ENABLE_FEATURE_EDITING
410# define ENABLE_FEATURE_EDITING 0
411# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
412# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200413# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
414# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000415#endif
416
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000417/* Do we support ANY keywords? */
418#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000419# define HAS_KEYWORDS 1
420# define IF_HAS_KEYWORDS(...) __VA_ARGS__
421# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000422#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000423# define HAS_KEYWORDS 0
424# define IF_HAS_KEYWORDS(...)
425# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000426#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000428/* If you comment out one of these below, it will be #defined later
429 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000430#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000431/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000432#define debug_printf_parse(...) do {} while (0)
433#define debug_print_tree(a, b) do {} while (0)
434#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000435#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000436#define debug_printf_jobs(...) do {} while (0)
437#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200438#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000439#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200440#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000441#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000442#define debug_printf_subst(...) do {} while (0)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200443#define debug_printf_prompt(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000445
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000446#define ERR_PTR ((void*)(long)1)
447
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100448#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000449
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200450#define _SPECIAL_VARS_STR "_*@$!?#"
451#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
452#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100453#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200454/* Support / and // replace ops */
455/* Note that // is stored as \ in "encoded" string representation */
456# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
457# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
458# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
459#else
460# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
461# define VAR_SUBST_OPS "%#:-=+?"
462# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
463#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200464
Denys Vlasenko932b9972018-01-11 12:39:48 +0100465#define SPECIAL_VAR_SYMBOL_STR "\3"
466#define SPECIAL_VAR_SYMBOL 3
467/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
468#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000469
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200470struct variable;
471
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000472static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
473
474/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000475 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000476 */
477#if !BB_MMU
478typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200479 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000480 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000481 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000482} nommu_save_t;
483#endif
484
Denys Vlasenko9b782552010-09-08 13:33:26 +0200485enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000486 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000487#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000488 RES_IF ,
489 RES_THEN ,
490 RES_ELIF ,
491 RES_ELSE ,
492 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000493#endif
494#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000495 RES_FOR ,
496 RES_WHILE ,
497 RES_UNTIL ,
498 RES_DO ,
499 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000500#endif
501#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000502 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000503#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000504#if ENABLE_HUSH_CASE
505 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200506 /* three pseudo-keywords support contrived "case" syntax: */
507 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
508 RES_MATCH , /* "word)" */
509 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000510 RES_ESAC ,
511#endif
512 RES_XXXX ,
513 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200514};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000515
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000516typedef struct o_string {
517 char *data;
518 int length; /* position where data is appended */
519 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200520 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000521 /* At least some part of the string was inside '' or "",
522 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200523 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000524 smallint has_empty_slot;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000525} o_string;
526enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200527 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
528 EXP_FLAG_GLOB = 0x2,
529 /* Protect newly added chars against globbing
530 * by prepending \ to *, ?, [, \ */
531 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
532};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000533/* Used for initialization: o_string foo = NULL_O_STRING; */
534#define NULL_O_STRING { NULL }
535
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200536#ifndef debug_printf_parse
537static const char *const assignment_flag[] = {
538 "MAYBE_ASSIGNMENT",
539 "DEFINITELY_ASSIGNMENT",
540 "NOT_ASSIGNMENT",
541 "WORD_IS_KEYWORD",
542};
543#endif
544
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545typedef struct in_str {
546 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200547 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200548 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000549 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000550} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000551
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200552/* The descrip member of this structure is only used to make
553 * debugging output pretty */
554static const struct {
555 int mode;
556 signed char default_fd;
557 char descrip[3];
558} redir_table[] = {
559 { O_RDONLY, 0, "<" },
560 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
561 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
562 { O_CREAT|O_RDWR, 1, "<>" },
563 { O_RDONLY, 0, "<<" },
564/* Should not be needed. Bogus default_fd helps in debugging */
565/* { O_RDONLY, 77, "<<" }, */
566};
567
Eric Andersen25f27032001-04-26 23:22:31 +0000568struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000569 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000570 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000571 int rd_fd; /* fd to redirect */
572 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
573 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000574 smallint rd_type; /* (enum redir_type) */
575 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000576 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200577 * bit 0: do we need to trim leading tabs?
578 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000579 */
Eric Andersen25f27032001-04-26 23:22:31 +0000580};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000581typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200582 REDIRECT_INPUT = 0,
583 REDIRECT_OVERWRITE = 1,
584 REDIRECT_APPEND = 2,
585 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000586 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200587 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000588
589 REDIRFD_CLOSE = -3,
590 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000591 REDIRFD_TO_FILE = -1,
592 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000593
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000594 HEREDOC_SKIPTABS = 1,
595 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000596} redir_type;
597
Eric Andersen25f27032001-04-26 23:22:31 +0000598
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000599struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000600 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200601 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100602#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100603 unsigned lineno;
604#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200605 smallint cmd_type; /* CMD_xxx */
606#define CMD_NORMAL 0
607#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200608#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
609/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
610 * "export v=t*"
611 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200612# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000613#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200614#if ENABLE_HUSH_FUNCTIONS
615# define CMD_FUNCDEF 3
616#endif
617
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100618 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200619 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
620 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000621#if !BB_MMU
622 char *group_as_string;
623#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000624#if ENABLE_HUSH_FUNCTIONS
625 struct function *child_func;
626/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200627 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000628 * When we execute "f1() {a;}" cmd, we create new function and clear
629 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200630 * When we execute "f1() {b;}", we notice that f1 exists,
631 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000632 * we put those fields back into cmd->xxx
633 * (struct function has ->parent_cmd ptr to facilitate that).
634 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
635 * Without this trick, loop would execute a;b;b;b;...
636 * instead of correct sequence a;b;a;b;...
637 * When command is freed, it severs the link
638 * (sets ->child_func->parent_cmd to NULL).
639 */
640#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000641 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000642/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
643 * and on execution these are substituted with their values.
644 * Substitution can make _several_ words out of one argv[n]!
645 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000646 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000647 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000648 struct redir_struct *redirects; /* I/O redirections */
649};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000650/* Is there anything in this command at all? */
651#define IS_NULL_CMD(cmd) \
652 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
653
Eric Andersen25f27032001-04-26 23:22:31 +0000654struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000655 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000656 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000657 int alive_cmds; /* number of commands running (not exited) */
658 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000659#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100660 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000661 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000662 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000663#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000664 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000665 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000666 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
667 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000668};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000669typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100670 PIPE_SEQ = 0,
671 PIPE_AND = 1,
672 PIPE_OR = 2,
673 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000674} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000675/* Is there anything in this pipe at all? */
676#define IS_NULL_PIPE(pi) \
677 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000678
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000679/* This holds pointers to the various results of parsing */
680struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000681 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000682 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000683 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000684 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000685 /* last command in pipe (being constructed right now) */
686 struct command *command;
687 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000688 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200689 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000690#if !BB_MMU
691 o_string as_string;
692#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200693 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000694#if HAS_KEYWORDS
695 smallint ctx_res_w;
696 smallint ctx_inverted; /* "! cmd | cmd" */
697#if ENABLE_HUSH_CASE
698 smallint ctx_dsemicolon; /* ";;" seen */
699#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000700 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
701 int old_flag;
702 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000703 * example: "if pipe1; pipe2; then pipe3; fi"
704 * when we see "if" or "then", we malloc and copy current context,
705 * and make ->stack point to it. then we parse pipeN.
706 * when closing "then" / fi" / whatever is found,
707 * we move list_head into ->stack->command->group,
708 * copy ->stack into current context, and delete ->stack.
709 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000710 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000711 struct parse_context *stack;
712#endif
713};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200714enum {
715 MAYBE_ASSIGNMENT = 0,
716 DEFINITELY_ASSIGNMENT = 1,
717 NOT_ASSIGNMENT = 2,
718 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
719 WORD_IS_KEYWORD = 3,
720};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000721
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000722/* On program start, environ points to initial environment.
723 * putenv adds new pointers into it, unsetenv removes them.
724 * Neither of these (de)allocates the strings.
725 * setenv allocates new strings in malloc space and does putenv,
726 * and thus setenv is unusable (leaky) for shell's purposes */
727#define setenv(...) setenv_is_leaky_dont_use()
728struct variable {
729 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000730 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000731 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200732 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000733 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000734 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000735};
736
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000738 BC_BREAK = 1,
739 BC_CONTINUE = 2,
740};
741
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000742#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000743struct function {
744 struct function *next;
745 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000746 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000747 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200748# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000749 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200750# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000751};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000752#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000753
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000754
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100755/* set -/+o OPT support. (TODO: make it optional)
756 * bash supports the following opts:
757 * allexport off
758 * braceexpand on
759 * emacs on
760 * errexit off
761 * errtrace off
762 * functrace off
763 * hashall on
764 * histexpand off
765 * history on
766 * ignoreeof off
767 * interactive-comments on
768 * keyword off
769 * monitor on
770 * noclobber off
771 * noexec off
772 * noglob off
773 * nolog off
774 * notify off
775 * nounset off
776 * onecmd off
777 * physical off
778 * pipefail off
779 * posix off
780 * privileged off
781 * verbose off
782 * vi off
783 * xtrace off
784 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800785static const char o_opt_strings[] ALIGN1 =
786 "pipefail\0"
787 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200788 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800789#if ENABLE_HUSH_MODE_X
790 "xtrace\0"
791#endif
792 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100793enum {
794 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800795 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200796 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800797#if ENABLE_HUSH_MODE_X
798 OPT_O_XTRACE,
799#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100800 NUM_OPT_O
801};
802
803
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200804struct FILE_list {
805 struct FILE_list *next;
806 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200807 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200808};
809
810
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000811/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000812/* Sorted roughly by size (smaller offsets == smaller code) */
813struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000814 /* interactive_fd != 0 means we are an interactive shell.
815 * If we are, then saved_tty_pgrp can also be != 0, meaning
816 * that controlling tty is available. With saved_tty_pgrp == 0,
817 * job control still works, but terminal signals
818 * (^C, ^Z, ^Y, ^\) won't work at all, and background
819 * process groups can only be created with "cmd &".
820 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
821 * to give tty to the foreground process group,
822 * and will take it back when the group is stopped (^Z)
823 * or killed (^C).
824 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825#if ENABLE_HUSH_INTERACTIVE
826 /* 'interactive_fd' is a fd# open to ctty, if we have one
827 * _AND_ if we decided to act interactively */
828 int interactive_fd;
829 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200830 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000831# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000832#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000833# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000834#endif
835#if ENABLE_FEATURE_EDITING
836 line_input_t *line_input_state;
837#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000838 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200839 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000840 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200841#if ENABLE_HUSH_RANDOM_SUPPORT
842 random_t random_gen;
843#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000844#if ENABLE_HUSH_JOB
845 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100846 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000847 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000848 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400849# define G_saved_tty_pgrp (G.saved_tty_pgrp)
850#else
851# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000852#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200853 /* How deeply are we in context where "set -e" is ignored */
854 int errexit_depth;
855 /* "set -e" rules (do we follow them correctly?):
856 * Exit if pipe, list, or compound command exits with a non-zero status.
857 * Shell does not exit if failed command is part of condition in
858 * if/while, part of && or || list except the last command, any command
859 * in a pipe but the last, or if the command's return value is being
860 * inverted with !. If a compound command other than a subshell returns a
861 * non-zero status because a command failed while -e was being ignored, the
862 * shell does not exit. A trap on ERR, if set, is executed before the shell
863 * exits [ERR is a bashism].
864 *
865 * If a compound command or function executes in a context where -e is
866 * ignored, none of the commands executed within are affected by the -e
867 * setting. If a compound command or function sets -e while executing in a
868 * context where -e is ignored, that setting does not have any effect until
869 * the compound command or the command containing the function call completes.
870 */
871
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100872 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100873#if ENABLE_HUSH_MODE_X
874# define G_x_mode (G.o_opt[OPT_O_XTRACE])
875#else
876# define G_x_mode 0
877#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200878#if ENABLE_HUSH_INTERACTIVE
879 smallint promptmode; /* 0: PS1, 1: PS2 */
880#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000881 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000882#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000883 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000884#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000885#if ENABLE_HUSH_FUNCTIONS
886 /* 0: outside of a function (or sourced file)
887 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000888 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000889 */
890 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200891# define G_flag_return_in_progress (G.flag_return_in_progress)
892#else
893# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000894#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000895 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200896 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000897 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200898 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200899 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100900#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000901 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000902 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100903# define G_global_args_malloced (G.global_args_malloced)
904#else
905# define G_global_args_malloced 0
906#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000907 /* how many non-NULL argv's we have. NB: $# + 1 */
908 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000909 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000910#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000911 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000912#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000913#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000914 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000915 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000916#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200917#if ENABLE_HUSH_GETOPTS
918 unsigned getopt_count;
919#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000920 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000921 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200922 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200923 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200924 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200925 unsigned var_nest_level;
926#if ENABLE_HUSH_FUNCTIONS
927# if ENABLE_HUSH_LOCAL
928 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200929# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200930 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000931#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000932 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200933#if ENABLE_HUSH_FAST
934 unsigned count_SIGCHLD;
935 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200936 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200937#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100938#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100939 unsigned lineno;
940 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100941#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200942 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200943 /* Which signals have non-DFL handler (even with no traps set)?
944 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200945 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200946 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200947 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200948 * Other than these two times, never modified.
949 */
950 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200951#if ENABLE_HUSH_JOB
952 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100953# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200954#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200955# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200956#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100957#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000958 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100959# define G_traps G.traps
960#else
961# define G_traps ((char**)NULL)
962#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200963 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100964#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000965 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100966#endif
967#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000969#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200970 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200971#if ENABLE_FEATURE_EDITING
972 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
973#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000974};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000975#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000976/* Not #defining name to G.name - this quickly gets unwieldy
977 * (too many defines). Also, I actually prefer to see when a variable
978 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000979#define INIT_G() do { \
980 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200981 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
982 sigfillset(&G.sa.sa_mask); \
983 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000984} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000985
986
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000987/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200988static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100989#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200990static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100991#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200992static int builtin_eval(char **argv) FAST_FUNC;
993static int builtin_exec(char **argv) FAST_FUNC;
994static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100995#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200996static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100997#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +0200998#if ENABLE_HUSH_READONLY
999static int builtin_readonly(char **argv) FAST_FUNC;
1000#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001001#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001002static int builtin_fg_bg(char **argv) FAST_FUNC;
1003static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001004#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001005#if ENABLE_HUSH_GETOPTS
1006static int builtin_getopts(char **argv) FAST_FUNC;
1007#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001008#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001009static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001010#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001011#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001012static int builtin_history(char **argv) FAST_FUNC;
1013#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001014#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001015static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001016#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001017#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001018static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001019#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001020#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001021static int builtin_printf(char **argv) FAST_FUNC;
1022#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001023static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001024#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001025static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001026#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001027#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001028static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001029#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_shift(char **argv) FAST_FUNC;
1031static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001032#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001033static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001034#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001035#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001036static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001037#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001038#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001039static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001040#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001041#if ENABLE_HUSH_TIMES
1042static int builtin_times(char **argv) FAST_FUNC;
1043#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001045#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001046static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001047#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001048#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001049static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001050#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001051#if ENABLE_HUSH_KILL
1052static int builtin_kill(char **argv) FAST_FUNC;
1053#endif
1054#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001055static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001056#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001057#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_break(char **argv) FAST_FUNC;
1059static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001060#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001061#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001063#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001064
1065/* Table of built-in functions. They can be forked or not, depending on
1066 * context: within pipes, they fork. As simple commands, they do not.
1067 * When used in non-forking context, they can change global variables
1068 * in the parent shell process. If forked, of course they cannot.
1069 * For example, 'unset foo | whatever' will parse and run, but foo will
1070 * still be set at the end. */
1071struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001072 const char *b_cmd;
1073 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001074#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001075 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001076# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001077#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001078# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001079#endif
1080};
1081
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001082static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001083 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001084 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001085#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001086 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001087#endif
1088#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001089 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001090#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001091 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001093 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001094#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001095 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1096 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001097 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001098#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001099 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001100#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001102 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001104#if ENABLE_HUSH_GETOPTS
1105 BLTIN("getopts" , builtin_getopts , NULL),
1106#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001109#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001110#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001111 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001112#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001113#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001114 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001115#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001116#if ENABLE_HUSH_KILL
1117 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1118#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001119#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001120 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001121#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001122#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001123 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001124#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001125#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001126 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001127#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001128#if ENABLE_HUSH_READONLY
1129 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1130#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001131#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001132 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001133#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001134#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001135 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001136#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001138#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001139 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001140#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001141#if ENABLE_HUSH_TIMES
1142 BLTIN("times" , builtin_times , NULL),
1143#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001144#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001145 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001146#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001147 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001148#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001149 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001150#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001151#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001152 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001153#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001154#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001156#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001157#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001159#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001160#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001161 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001162#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001163};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001164/* These builtins won't be used if we are on NOMMU and need to re-exec
1165 * (it's cheaper to run an external program in this case):
1166 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001168#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001169 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001170#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001171#if BASH_TEST2
1172 BLTIN("[[" , builtin_test , NULL),
1173#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001174#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001175 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001176#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001178 BLTIN("printf" , builtin_printf , NULL),
1179#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001180 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001181#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001183#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001184};
1185
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001186
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001187/* Debug printouts.
1188 */
1189#if HUSH_DEBUG
1190/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001191# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001192# define debug_enter() (G.debug_indent++)
1193# define debug_leave() (G.debug_indent--)
1194#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001195# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001196# define debug_enter() ((void)0)
1197# define debug_leave() ((void)0)
1198#endif
1199
1200#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001201# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001202#endif
1203
1204#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001205# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001206#endif
1207
1208#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001209#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001210#endif
1211
1212#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001213# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001214#endif
1215
1216#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001217# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001218# define DEBUG_JOBS 1
1219#else
1220# define DEBUG_JOBS 0
1221#endif
1222
1223#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001224# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225# define DEBUG_EXPAND 1
1226#else
1227# define DEBUG_EXPAND 0
1228#endif
1229
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001230#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001231# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001232#endif
1233
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001234#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001235# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001236# define DEBUG_GLOB 1
1237#else
1238# define DEBUG_GLOB 0
1239#endif
1240
Denys Vlasenko2db74612017-07-07 22:07:28 +02001241#ifndef debug_printf_redir
1242# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1243#endif
1244
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001245#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247#endif
1248
1249#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251#endif
1252
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001253#ifndef debug_printf_prompt
1254# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1255#endif
1256
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001258# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259# define DEBUG_CLEAN 1
1260#else
1261# define DEBUG_CLEAN 0
1262#endif
1263
1264#if DEBUG_EXPAND
1265static void debug_print_strings(const char *prefix, char **vv)
1266{
1267 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001268 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001270 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001271}
1272#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001273# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001274#endif
1275
1276
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001277/* Leak hunting. Use hush_leaktool.sh for post-processing.
1278 */
1279#if LEAK_HUNTING
1280static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001281{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001282 void *ptr = xmalloc((size + 0xff) & ~0xff);
1283 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1284 return ptr;
1285}
1286static void *xxrealloc(int lineno, void *ptr, size_t size)
1287{
1288 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1289 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1290 return ptr;
1291}
1292static char *xxstrdup(int lineno, const char *str)
1293{
1294 char *ptr = xstrdup(str);
1295 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1296 return ptr;
1297}
1298static void xxfree(void *ptr)
1299{
1300 fdprintf(2, "free %p\n", ptr);
1301 free(ptr);
1302}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001303# define xmalloc(s) xxmalloc(__LINE__, s)
1304# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1305# define xstrdup(s) xxstrdup(__LINE__, s)
1306# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001307#endif
1308
1309
1310/* Syntax and runtime errors. They always abort scripts.
1311 * In interactive use they usually discard unparsed and/or unexecuted commands
1312 * and return to the prompt.
1313 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1314 */
1315#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001316# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001317# define syntax_error(lineno, msg) syntax_error(msg)
1318# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1319# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1320# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1321# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001322#endif
1323
Denys Vlasenko39701202017-08-02 19:44:05 +02001324static void die_if_script(void)
1325{
1326 if (!G_interactive_fd) {
1327 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1328 xfunc_error_retval = G.last_exitcode;
1329 xfunc_die();
1330 }
1331}
1332
1333static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001334{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001335 va_list p;
1336
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001337#if HUSH_DEBUG >= 2
1338 bb_error_msg("hush.c:%u", lineno);
1339#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001340 va_start(p, fmt);
1341 bb_verror_msg(fmt, p, NULL);
1342 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001343 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001344}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001345
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001346static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001347{
1348 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001349 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001350 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001351 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001352 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001353}
1354
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001355static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001356{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001357 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001358 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001359}
1360
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001361static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001362{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001363 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001364//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1365// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001366}
1367
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001368static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001369{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001370 char msg[2] = { ch, '\0' };
1371 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372}
1373
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001374static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001375{
1376 char msg[2];
1377 msg[0] = ch;
1378 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001379#if HUSH_DEBUG >= 2
1380 bb_error_msg("hush.c:%u", lineno);
1381#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001382 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001383 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001384}
1385
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001387# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388# undef syntax_error
1389# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001390# undef syntax_error_unterm_ch
1391# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001392# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001393#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001394# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001395# define syntax_error(msg) syntax_error(__LINE__, msg)
1396# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1397# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1398# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1399# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001400#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001401
Denis Vlasenko552433b2009-04-04 19:29:21 +00001402
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001403#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001404static void cmdedit_update_prompt(void);
1405#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001406# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001407#endif
1408
1409
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001410/* Utility functions
1411 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001412/* Replace each \x with x in place, return ptr past NUL. */
1413static char *unbackslash(char *src)
1414{
Denys Vlasenko71885402009-09-24 01:44:13 +02001415 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001416 while (1) {
1417 if (*src == '\\')
1418 src++;
1419 if ((*dst++ = *src++) == '\0')
1420 break;
1421 }
1422 return dst;
1423}
1424
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001425static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001426{
1427 int i;
1428 unsigned count1;
1429 unsigned count2;
1430 char **v;
1431
1432 v = strings;
1433 count1 = 0;
1434 if (v) {
1435 while (*v) {
1436 count1++;
1437 v++;
1438 }
1439 }
1440 count2 = 0;
1441 v = add;
1442 while (*v) {
1443 count2++;
1444 v++;
1445 }
1446 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1447 v[count1 + count2] = NULL;
1448 i = count2;
1449 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001450 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001451 return v;
1452}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001453#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001454static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1455{
1456 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1457 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1458 return ptr;
1459}
1460#define add_strings_to_strings(strings, add, need_to_dup) \
1461 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1462#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001463
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001464/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001465static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001466{
1467 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001468 v[0] = add;
1469 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001470 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001471}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001472#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001473static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1474{
1475 char **ptr = add_string_to_strings(strings, add);
1476 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1477 return ptr;
1478}
1479#define add_string_to_strings(strings, add) \
1480 xx_add_string_to_strings(__LINE__, strings, add)
1481#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001482
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001483static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001484{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001485 char **v;
1486
1487 if (!strings)
1488 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001489 v = strings;
1490 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001491 free(*v);
1492 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001493 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001494 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001495}
1496
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001497static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001498{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001499 int newfd;
1500 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001501 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1502 if (newfd >= 0) {
1503 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1504 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1505 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001506 if (errno == EBUSY)
1507 goto repeat;
1508 if (errno == EINTR)
1509 goto repeat;
1510 }
1511 return newfd;
1512}
1513
Denys Vlasenko657e9002017-07-30 23:34:04 +02001514static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001515{
1516 int newfd;
1517 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001518 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001519 if (newfd < 0) {
1520 if (errno == EBUSY)
1521 goto repeat;
1522 if (errno == EINTR)
1523 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001524 /* fd was not open? */
1525 if (errno == EBADF)
1526 return fd;
1527 xfunc_die();
1528 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001529 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1530 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001531 close(fd);
1532 return newfd;
1533}
1534
1535
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001536/* Manipulating the list of open FILEs */
1537static FILE *remember_FILE(FILE *fp)
1538{
1539 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001540 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001541 n->next = G.FILE_list;
1542 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001543 n->fp = fp;
1544 n->fd = fileno(fp);
1545 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001546 }
1547 return fp;
1548}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001549static void fclose_and_forget(FILE *fp)
1550{
1551 struct FILE_list **pp = &G.FILE_list;
1552 while (*pp) {
1553 struct FILE_list *cur = *pp;
1554 if (cur->fp == fp) {
1555 *pp = cur->next;
1556 free(cur);
1557 break;
1558 }
1559 pp = &cur->next;
1560 }
1561 fclose(fp);
1562}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001563static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001564{
1565 struct FILE_list *fl = G.FILE_list;
1566 while (fl) {
1567 if (fd == fl->fd) {
1568 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001569 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001570 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 +02001571 return 1;
1572 }
1573 fl = fl->next;
1574 }
1575 return 0;
1576}
1577static void restore_redirected_FILEs(void)
1578{
1579 struct FILE_list *fl = G.FILE_list;
1580 while (fl) {
1581 int should_be = fileno(fl->fp);
1582 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001583 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001584 xmove_fd(fl->fd, should_be);
1585 fl->fd = should_be;
1586 }
1587 fl = fl->next;
1588 }
1589}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001590#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001591static void close_all_FILE_list(void)
1592{
1593 struct FILE_list *fl = G.FILE_list;
1594 while (fl) {
1595 /* fclose would also free FILE object.
1596 * It is disastrous if we share memory with a vforked parent.
1597 * I'm not sure we never come here after vfork.
1598 * Therefore just close fd, nothing more.
1599 */
1600 /*fclose(fl->fp); - unsafe */
1601 close(fl->fd);
1602 fl = fl->next;
1603 }
1604}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001605#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001606static int fd_in_FILEs(int fd)
1607{
1608 struct FILE_list *fl = G.FILE_list;
1609 while (fl) {
1610 if (fl->fd == fd)
1611 return 1;
1612 fl = fl->next;
1613 }
1614 return 0;
1615}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001616
1617
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001618/* Helpers for setting new $n and restoring them back
1619 */
1620typedef struct save_arg_t {
1621 char *sv_argv0;
1622 char **sv_g_argv;
1623 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001624 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001625} save_arg_t;
1626
1627static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1628{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001629 sv->sv_argv0 = argv[0];
1630 sv->sv_g_argv = G.global_argv;
1631 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001632 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001633
1634 argv[0] = G.global_argv[0]; /* retain $0 */
1635 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001636 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001637
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001638 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001639}
1640
1641static void restore_G_args(save_arg_t *sv, char **argv)
1642{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001643#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001644 if (G.global_args_malloced) {
1645 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001646 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001647 while (*++pp) /* note: does not free $0 */
1648 free(*pp);
1649 free(G.global_argv);
1650 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001651#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001652 argv[0] = sv->sv_argv0;
1653 G.global_argv = sv->sv_g_argv;
1654 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001655 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001656}
1657
1658
Denis Vlasenkod5762932009-03-31 11:22:57 +00001659/* Basic theory of signal handling in shell
1660 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001661 * This does not describe what hush does, rather, it is current understanding
1662 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001663 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1664 *
1665 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1666 * is finished or backgrounded. It is the same in interactive and
1667 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001668 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001669 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001670 * backgrounds (i.e. stops) or kills all members of currently running
1671 * pipe.
1672 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001673 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001674 * or by SIGINT in interactive shell.
1675 *
1676 * Trap handlers will execute even within trap handlers. (right?)
1677 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001678 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1679 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001680 *
1681 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001682 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001683 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001684 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001685 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001686 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001687 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001688 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001689 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001690 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001691 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001692 *
1693 * SIGQUIT: ignore
1694 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001695 * SIGHUP (interactive):
1696 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001697 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001698 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1699 * that all pipe members are stopped. Try this in bash:
1700 * while :; do :; done - ^Z does not background it
1701 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001702 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001703 * of the command line, show prompt. NB: ^C does not send SIGINT
1704 * to interactive shell while shell is waiting for a pipe,
1705 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001706 * Example 1: this waits 5 sec, but does not execute ls:
1707 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1708 * Example 2: this does not wait and does not execute ls:
1709 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1710 * Example 3: this does not wait 5 sec, but executes ls:
1711 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001712 * Example 4: this does not wait and does not execute ls:
1713 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001714 *
1715 * (What happens to signals which are IGN on shell start?)
1716 * (What happens with signal mask on shell start?)
1717 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001718 * Old implementation
1719 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001720 * We use in-kernel pending signal mask to determine which signals were sent.
1721 * We block all signals which we don't want to take action immediately,
1722 * i.e. we block all signals which need to have special handling as described
1723 * above, and all signals which have traps set.
1724 * After each pipe execution, we extract any pending signals via sigtimedwait()
1725 * and act on them.
1726 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001727 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001728 * sigset_t blocked_set: current blocked signal set
1729 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001730 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001731 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001732 * "trap 'cmd' SIGxxx":
1733 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001734 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001735 * unblock signals with special interactive handling
1736 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001737 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001738 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001739 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001740 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001741 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001742 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001743 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001744 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001745 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001746 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001747 * Standard says "When a subshell is entered, traps that are not being ignored
1748 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001749 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001750 *
1751 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001752 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001753 * masked signals are not visible!
1754 *
1755 * New implementation
1756 * ==================
1757 * We record each signal we are interested in by installing signal handler
1758 * for them - a bit like emulating kernel pending signal mask in userspace.
1759 * We are interested in: signals which need to have special handling
1760 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001761 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001762 * After each pipe execution, we extract any pending signals
1763 * and act on them.
1764 *
1765 * unsigned special_sig_mask: a mask of shell-special signals.
1766 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1767 * char *traps[sig] if trap for sig is set (even if it's '').
1768 * sigset_t pending_set: set of sigs we received.
1769 *
1770 * "trap - SIGxxx":
1771 * if sig is in special_sig_mask, set handler back to:
1772 * record_pending_signo, or to IGN if it's a tty stop signal
1773 * if sig is in fatal_sig_mask, set handler back to sigexit.
1774 * else: set handler back to SIG_DFL
1775 * "trap 'cmd' SIGxxx":
1776 * set handler to record_pending_signo.
1777 * "trap '' SIGxxx":
1778 * set handler to SIG_IGN.
1779 * after [v]fork, if we plan to be a shell:
1780 * set signals with special interactive handling to SIG_DFL
1781 * (because child shell is not interactive),
1782 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1783 * after [v]fork, if we plan to exec:
1784 * POSIX says fork clears pending signal mask in child - no need to clear it.
1785 *
1786 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1787 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1788 *
1789 * Note (compat):
1790 * Standard says "When a subshell is entered, traps that are not being ignored
1791 * are set to the default actions". bash interprets it so that traps which
1792 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001793 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001794enum {
1795 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001796 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001797 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001798 | (1 << SIGHUP)
1799 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001800 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001801#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001802 | (1 << SIGTTIN)
1803 | (1 << SIGTTOU)
1804 | (1 << SIGTSTP)
1805#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001806 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001807};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001808
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001809static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001810{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001811 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001812#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001813 if (sig == SIGCHLD) {
1814 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001815//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 +02001816 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001817#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001818}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001819
Denys Vlasenko0806e402011-05-12 23:06:20 +02001820static sighandler_t install_sighandler(int sig, sighandler_t handler)
1821{
1822 struct sigaction old_sa;
1823
1824 /* We could use signal() to install handlers... almost:
1825 * except that we need to mask ALL signals while handlers run.
1826 * I saw signal nesting in strace, race window isn't small.
1827 * SA_RESTART is also needed, but in Linux, signal()
1828 * sets SA_RESTART too.
1829 */
1830 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1831 /* sigfillset(&G.sa.sa_mask); - already done */
1832 /* G.sa.sa_flags = SA_RESTART; - already done */
1833 G.sa.sa_handler = handler;
1834 sigaction(sig, &G.sa, &old_sa);
1835 return old_sa.sa_handler;
1836}
1837
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001838static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001839
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001840static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001841static void restore_ttypgrp_and__exit(void)
1842{
1843 /* xfunc has failed! die die die */
1844 /* no EXIT traps, this is an escape hatch! */
1845 G.exiting = 1;
1846 hush_exit(xfunc_error_retval);
1847}
1848
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001849#if ENABLE_HUSH_JOB
1850
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001851/* Needed only on some libc:
1852 * It was observed that on exit(), fgetc'ed buffered data
1853 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1854 * With the net effect that even after fork(), not vfork(),
1855 * exit() in NOEXECed applet in "sh SCRIPT":
1856 * noexec_applet_here
1857 * echo END_OF_SCRIPT
1858 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1859 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001860 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001861 * and in `cmd` handling.
1862 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1863 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001864static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001865static void fflush_and__exit(void)
1866{
1867 fflush_all();
1868 _exit(xfunc_error_retval);
1869}
1870
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001871/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001872# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001873/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001874# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001875
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001876/* Restores tty foreground process group, and exits.
1877 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001878 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001879 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001880 * We also call it if xfunc is exiting.
1881 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001882static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001883static void sigexit(int sig)
1884{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001885 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001886 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001887 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1888 /* Disable all signals: job control, SIGPIPE, etc.
1889 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1890 */
1891 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001892 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001893 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001894
1895 /* Not a signal, just exit */
1896 if (sig <= 0)
1897 _exit(- sig);
1898
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001899 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001900}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001901#else
1902
Denys Vlasenko8391c482010-05-22 17:50:43 +02001903# define disable_restore_tty_pgrp_on_exit() ((void)0)
1904# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001905
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001906#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001907
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001908static sighandler_t pick_sighandler(unsigned sig)
1909{
1910 sighandler_t handler = SIG_DFL;
1911 if (sig < sizeof(unsigned)*8) {
1912 unsigned sigmask = (1 << sig);
1913
1914#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001915 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001916 if (G_fatal_sig_mask & sigmask)
1917 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001918 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001919#endif
1920 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001921 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001922 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001923 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001924 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001925 * in an endless loop when we try to do some
1926 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001927 */
1928 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1929 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001930 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001931 }
1932 return handler;
1933}
1934
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001935/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001936static void hush_exit(int exitcode)
1937{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001938#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1939 save_history(G.line_input_state);
1940#endif
1941
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001942 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001943 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001944 char *argv[3];
1945 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001946 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001947 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001948 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001949 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001950 * "trap" will still show it, if executed
1951 * in the handler */
1952 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001953 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001954
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001955#if ENABLE_FEATURE_CLEAN_UP
1956 {
1957 struct variable *cur_var;
1958 if (G.cwd != bb_msg_unknown)
1959 free((char*)G.cwd);
1960 cur_var = G.top_var;
1961 while (cur_var) {
1962 struct variable *tmp = cur_var;
1963 if (!cur_var->max_len)
1964 free(cur_var->varstr);
1965 cur_var = cur_var->next;
1966 free(tmp);
1967 }
1968 }
1969#endif
1970
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001971 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001972#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001973 sigexit(- (exitcode & 0xff));
1974#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001975 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001976#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001977}
1978
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001979
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001980//TODO: return a mask of ALL handled sigs?
1981static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001982{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001983 int last_sig = 0;
1984
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001985 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001986 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001987
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001988 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001989 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001990 sig = 0;
1991 do {
1992 sig++;
1993 if (sigismember(&G.pending_set, sig)) {
1994 sigdelset(&G.pending_set, sig);
1995 goto got_sig;
1996 }
1997 } while (sig < NSIG);
1998 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001999 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002000 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002001 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002002 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002003 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002004 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002005 char *argv[3];
2006 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002007 argv[1] = xstrdup(G_traps[sig]);
2008 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002009 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002010 save_rcode = G.last_exitcode;
2011 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002012 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002013//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002014 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002015 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002016 } /* else: "" trap, ignoring signal */
2017 continue;
2018 }
2019 /* not a trap: special action */
2020 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002021 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002022 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002023 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002024 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002025 break;
2026#if ENABLE_HUSH_JOB
2027 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002028//TODO: why are we doing this? ash and dash don't do this,
2029//they have no handler for SIGHUP at all,
2030//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002031 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002032 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002033 /* bash is observed to signal whole process groups,
2034 * not individual processes */
2035 for (job = G.job_list; job; job = job->next) {
2036 if (job->pgrp <= 0)
2037 continue;
2038 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2039 if (kill(- job->pgrp, SIGHUP) == 0)
2040 kill(- job->pgrp, SIGCONT);
2041 }
2042 sigexit(SIGHUP);
2043 }
2044#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002045#if ENABLE_HUSH_FAST
2046 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002047 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002048 G.count_SIGCHLD++;
2049//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2050 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002051 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002052 * This simplifies wait builtin a bit.
2053 */
2054 break;
2055#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002056 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002057 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002059 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002060 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002061 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002062 * in interactive shell, because TERM is ignored.
2063 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002064 break;
2065 }
2066 }
2067 return last_sig;
2068}
2069
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002070
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002071static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002072{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002073 if (force || G.cwd == NULL) {
2074 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2075 * we must not try to free(bb_msg_unknown) */
2076 if (G.cwd == bb_msg_unknown)
2077 G.cwd = NULL;
2078 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2079 if (!G.cwd)
2080 G.cwd = bb_msg_unknown;
2081 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002082 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002083}
2084
Denis Vlasenko83506862007-11-23 13:11:42 +00002085
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002086/*
2087 * Shell and environment variable support
2088 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002089static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002090{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002091 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002092 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002093
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002094 pp = &G.top_var;
2095 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002096 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002097 return pp;
2098 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002099 }
2100 return NULL;
2101}
2102
Denys Vlasenko03dad222010-01-12 23:29:57 +01002103static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002104{
Denys Vlasenko29082232010-07-16 13:52:32 +02002105 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002106 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002107
2108 if (G.expanded_assignments) {
2109 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002110 while (*cpp) {
2111 char *cp = *cpp;
2112 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2113 return cp + len + 1;
2114 cpp++;
2115 }
2116 }
2117
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002118 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002119 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002120 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002121
Denys Vlasenkodea47882009-10-09 15:40:49 +02002122 if (strcmp(name, "PPID") == 0)
2123 return utoa(G.root_ppid);
2124 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002125#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002126 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002127 return utoa(next_random(&G.random_gen));
2128#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 return NULL;
2130}
2131
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002132static void handle_changed_special_names(const char *name, unsigned name_len)
2133{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002134 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2135 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2136 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002137 cmdedit_update_prompt();
2138 return;
2139 }
2140
2141 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2142 && name_len == 6
2143 ) {
2144#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002145 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002146 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002147 return;
2148 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002149#endif
2150#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002151 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002152 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002153 return;
2154 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002155#endif
2156 }
2157}
2158
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002160 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002161 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002162#define SETFLAG_EXPORT (1 << 0)
2163#define SETFLAG_UNEXPORT (1 << 1)
2164#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002165#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002166static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002167{
Denys Vlasenko61407802018-04-04 21:14:28 +02002168 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002169 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002170 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002171 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002172 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002173 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002174
Denis Vlasenko950bd722009-04-21 11:23:56 +00002175 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002176 if (HUSH_DEBUG && !eq_sign)
2177 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002178
Denis Vlasenko950bd722009-04-21 11:23:56 +00002179 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002180 cur_pp = &G.top_var;
2181 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002182 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002183 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002184 continue;
2185 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002186
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002187 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002188 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002189 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002190 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002191//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2192//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002193 return -1;
2194 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002195 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002196 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2197 *eq_sign = '\0';
2198 unsetenv(str);
2199 *eq_sign = '=';
2200 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002201 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002202 /* bash 3.2.33(1) and exported vars:
2203 * # export z=z
2204 * # f() { local z=a; env | grep ^z; }
2205 * # f
2206 * z=a
2207 * # env | grep ^z
2208 * z=z
2209 */
2210 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002211 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002212 /* New variable is local ("local VAR=VAL" or
2213 * "VAR=VAL cmd")
2214 * and existing one is global, or local
2215 * on a lower level that new one.
2216 * Remove it from global variable list:
2217 */
2218 *cur_pp = cur->next;
2219 if (G.shadowed_vars_pp) {
2220 /* Save in "shadowed" list */
2221 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2222 cur->flg_export ? "exported " : "",
2223 cur->varstr, cur->var_nest_level, str, local_lvl
2224 );
2225 cur->next = *G.shadowed_vars_pp;
2226 *G.shadowed_vars_pp = cur;
2227 } else {
2228 /* Came from pseudo_exec_argv(), no need to save: delete it */
2229 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2230 cur->flg_export ? "exported " : "",
2231 cur->varstr, cur->var_nest_level, str, local_lvl
2232 );
2233 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2234 free_me = cur->varstr; /* then free it later */
2235 free(cur);
2236 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002237 break;
2238 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002239
Denis Vlasenko950bd722009-04-21 11:23:56 +00002240 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002241 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242 free_and_exp:
2243 free(str);
2244 goto exp;
2245 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002246
2247 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002248 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002249 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002250 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002251 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002252 strcpy(cur->varstr, str);
2253 goto free_and_exp;
2254 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002255 /* Can't reuse */
2256 cur->max_len = 0;
2257 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002258 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002259 /* max_len == 0 signifies "malloced" var, which we can
2260 * (and have to) free. But we can't free(cur->varstr) here:
2261 * if cur->flg_export is 1, it is in the environment.
2262 * We should either unsetenv+free, or wait until putenv,
2263 * then putenv(new)+free(old).
2264 */
2265 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 goto set_str_and_exp;
2267 }
2268
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002269 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002270 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002271 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002272 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002273 cur->next = *cur_pp;
2274 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002275
2276 set_str_and_exp:
2277 cur->varstr = str;
2278 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002279#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002280 if (flags & SETFLAG_MAKE_RO) {
2281 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002282 }
2283#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002284 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002285 cur->flg_export = 1;
2286 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002287 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002288 cur->flg_export = 0;
2289 /* unsetenv was already done */
2290 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002291 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002292 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002293 i = putenv(cur->varstr);
2294 /* only now we can free old exported malloced string */
2295 free(free_me);
2296 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002297 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002298 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002299 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002300
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002301 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002302
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002303 return 0;
2304}
2305
Denys Vlasenko6db47842009-09-05 20:15:17 +02002306/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002307static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002308{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002309 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002310}
2311
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002312static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002313{
2314 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002315 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002316
Denys Vlasenko61407802018-04-04 21:14:28 +02002317 cur_pp = &G.top_var;
2318 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002319 if (strncmp(cur->varstr, name, name_len) == 0
2320 && cur->varstr[name_len] == '='
2321 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322 if (cur->flg_read_only) {
2323 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002324 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002325 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002326
Denys Vlasenko61407802018-04-04 21:14:28 +02002327 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2329 bb_unsetenv(cur->varstr);
2330 if (!cur->max_len)
2331 free(cur->varstr);
2332 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002333
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002334 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002335 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002336 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002337 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002338
2339 /* Handle "unset PS1" et al even if did not find the variable to unset */
2340 handle_changed_special_names(name, name_len);
2341
Mike Frysingerd690f682009-03-30 06:50:54 +00002342 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002343}
2344
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002345#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002346static int unset_local_var(const char *name)
2347{
2348 return unset_local_var_len(name, strlen(name));
2349}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002350#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002351
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002352#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002353static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002354{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002355 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002356 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002357}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002358#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002359
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002360
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002361/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002362 * Helpers for "var1=val1 var2=val2 cmd" feature
2363 */
2364static void add_vars(struct variable *var)
2365{
2366 struct variable *next;
2367
2368 while (var) {
2369 next = var->next;
2370 var->next = G.top_var;
2371 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002372 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002373 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002374 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002375 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002376 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002377 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002378 var = next;
2379 }
2380}
2381
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002382/* We put strings[i] into variable table and possibly putenv them.
2383 * If variable is read only, we can free the strings[i]
2384 * which attempts to overwrite it.
2385 * The strings[] vector itself is freed.
2386 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002387static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002388{
2389 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002390
2391 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002392 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002393
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002394 s = strings;
2395 while (*s) {
2396 struct variable *var_p;
2397 struct variable **var_pp;
2398 char *eq;
2399
2400 eq = strchr(*s, '=');
2401 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002402 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002403 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002404 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002405 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002406 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002407 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002408 /*
2409 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2410 * If VAR is readonly, leaving it in the list
2411 * after asssignment error (msg above)
2412 * causes doubled error message later, on unset.
2413 */
2414 debug_printf_env("removing/freeing '%s' element\n", *s);
2415 free(*s);
2416 p = s;
2417 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002418 goto next;
2419 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002420 /* below, set_local_var() with nest level will
2421 * "shadow" (remove) this variable from
2422 * global linked list.
2423 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002424 }
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002425 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002426 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2427 } else if (HUSH_DEBUG) {
2428 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002429 }
2430 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002431 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002432 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002433 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002434}
2435
2436
2437/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002438 * Unicode helper
2439 */
2440static void reinit_unicode_for_hush(void)
2441{
2442 /* Unicode support should be activated even if LANG is set
2443 * _during_ shell execution, not only if it was set when
2444 * shell was started. Therefore, re-check LANG every time:
2445 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002446 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2447 || ENABLE_UNICODE_USING_LOCALE
2448 ) {
2449 const char *s = get_local_var_value("LC_ALL");
2450 if (!s) s = get_local_var_value("LC_CTYPE");
2451 if (!s) s = get_local_var_value("LANG");
2452 reinit_unicode(s);
2453 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002454}
2455
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002456/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002457 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002458 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002459
2460#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002461/* To test correct lineedit/interactive behavior, type from command line:
2462 * echo $P\
2463 * \
2464 * AT\
2465 * H\
2466 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002467 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002468 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002469# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002470static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002471{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002472 G.PS1 = get_local_var_value("PS1");
2473 if (G.PS1 == NULL)
2474 G.PS1 = "";
2475 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002476 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002477 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002478}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002479# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002480static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002481{
2482 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002483
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002484 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002485
2486 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2487 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002488 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002489 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2490 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002491 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002492 /* bash uses $PWD value, even if it is set by user.
2493 * It uses current dir only if PWD is unset.
2494 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002495 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002496 }
2497 prompt_str = G.PS1;
2498 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002499 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002500 return prompt_str;
2501}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002502static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503{
2504 int r;
2505 const char *prompt_str;
2506
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002507 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002508# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002509 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002510 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002511 if (G.flag_SIGINT) {
2512 /* There was ^C'ed, make it look prettier: */
2513 bb_putchar('\n');
2514 G.flag_SIGINT = 0;
2515 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002516 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002517 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002518 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002519 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002520 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002521 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002522 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002523 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002524 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002525 if (r != 0 && !G.flag_SIGINT)
2526 break;
2527 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002528 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2529 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002530 G.last_exitcode = 128 + SIGINT;
2531 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002532 if (r < 0) {
2533 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002534 i->p = NULL;
2535 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002536 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002537 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002538 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002539 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002540# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002541 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002542 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002543 if (i->last_char == '\0' || i->last_char == '\n') {
2544 /* Why check_and_run_traps here? Try this interactively:
2545 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2546 * $ <[enter], repeatedly...>
2547 * Without check_and_run_traps, handler never runs.
2548 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002549 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002550 fputs(prompt_str, stdout);
2551 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002552 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002553//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002554 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002555 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2556 * no ^C masking happens during fgetc, no special code for ^C:
2557 * it generates SIGINT as usual.
2558 */
2559 check_and_run_traps();
2560 if (G.flag_SIGINT)
2561 G.last_exitcode = 128 + SIGINT;
2562 if (r != '\0')
2563 break;
2564 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002565 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002566# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002567}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002568/* This is the magic location that prints prompts
2569 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002570static int fgetc_interactive(struct in_str *i)
2571{
2572 int ch;
2573 /* If it's interactive stdin, get new line. */
2574 if (G_interactive_fd && i->file == stdin) {
2575 /* Returns first char (or EOF), the rest is in i->p[] */
2576 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002577 G.promptmode = 1; /* PS2 */
2578 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002579 } else {
2580 /* Not stdin: script file, sourced file, etc */
2581 do ch = fgetc(i->file); while (ch == '\0');
2582 }
2583 return ch;
2584}
2585#else
2586static inline int fgetc_interactive(struct in_str *i)
2587{
2588 int ch;
2589 do ch = fgetc(i->file); while (ch == '\0');
2590 return ch;
2591}
2592#endif /* INTERACTIVE */
2593
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002594static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002595{
2596 int ch;
2597
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002598 if (!i->file) {
2599 /* string-based in_str */
2600 ch = (unsigned char)*i->p;
2601 if (ch != '\0') {
2602 i->p++;
2603 i->last_char = ch;
2604 return ch;
2605 }
2606 return EOF;
2607 }
2608
2609 /* FILE-based in_str */
2610
Denys Vlasenko4074d492016-09-30 01:49:53 +02002611#if ENABLE_FEATURE_EDITING
2612 /* This can be stdin, check line editing char[] buffer */
2613 if (i->p && *i->p != '\0') {
2614 ch = (unsigned char)*i->p++;
2615 goto out;
2616 }
2617#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002618 /* peek_buf[] is an int array, not char. Can contain EOF. */
2619 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002620 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002621 int ch2 = i->peek_buf[1];
2622 i->peek_buf[0] = ch2;
2623 if (ch2 == 0) /* very likely, avoid redundant write */
2624 goto out;
2625 i->peek_buf[1] = 0;
2626 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002627 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002628
Denys Vlasenko4074d492016-09-30 01:49:53 +02002629 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002630 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002631 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002632 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002633#if ENABLE_HUSH_LINENO_VAR
2634 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002635 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002636 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2637 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002638#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639 return ch;
2640}
2641
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002642static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643{
2644 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002645
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002646 if (!i->file) {
2647 /* string-based in_str */
2648 /* Doesn't report EOF on NUL. None of the callers care. */
2649 return (unsigned char)*i->p;
2650 }
2651
2652 /* FILE-based in_str */
2653
Denys Vlasenko4074d492016-09-30 01:49:53 +02002654#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002655 /* This can be stdin, check line editing char[] buffer */
2656 if (i->p && *i->p != '\0')
2657 return (unsigned char)*i->p;
2658#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002659 /* peek_buf[] is an int array, not char. Can contain EOF. */
2660 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002661 if (ch != 0)
2662 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002663
Denys Vlasenko4074d492016-09-30 01:49:53 +02002664 /* Need to get a new char */
2665 ch = fgetc_interactive(i);
2666 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2667
2668 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2669#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2670 if (i->p) {
2671 i->p -= 1;
2672 return ch;
2673 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002674#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002675 i->peek_buf[0] = ch;
2676 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002677 return ch;
2678}
2679
Denys Vlasenko4074d492016-09-30 01:49:53 +02002680/* Only ever called if i_peek() was called, and did not return EOF.
2681 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2682 * not end-of-line. Therefore we never need to read a new editing line here.
2683 */
2684static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002685{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002686 int ch;
2687
2688 /* There are two cases when i->p[] buffer exists.
2689 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002690 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002691 * In both cases, we know that i->p[0] exists and not NUL, and
2692 * the peek2 result is in i->p[1].
2693 */
2694 if (i->p)
2695 return (unsigned char)i->p[1];
2696
2697 /* Now we know it is a file-based in_str. */
2698
2699 /* peek_buf[] is an int array, not char. Can contain EOF. */
2700 /* Is there 2nd char? */
2701 ch = i->peek_buf[1];
2702 if (ch == 0) {
2703 /* We did not read it yet, get it now */
2704 do ch = fgetc(i->file); while (ch == '\0');
2705 i->peek_buf[1] = ch;
2706 }
2707
2708 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2709 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002710}
2711
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002712static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2713{
2714 for (;;) {
2715 int ch, ch2;
2716
2717 ch = i_getch(input);
2718 if (ch != '\\')
2719 return ch;
2720 ch2 = i_peek(input);
2721 if (ch2 != '\n')
2722 return ch;
2723 /* backslash+newline, skip it */
2724 i_getch(input);
2725 }
2726}
2727
2728/* Note: this function _eats_ \<newline> pairs, safe to use plain
2729 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2730 */
2731static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2732{
2733 for (;;) {
2734 int ch, ch2;
2735
2736 ch = i_peek(input);
2737 if (ch != '\\')
2738 return ch;
2739 ch2 = i_peek2(input);
2740 if (ch2 != '\n')
2741 return ch;
2742 /* backslash+newline, skip it */
2743 i_getch(input);
2744 i_getch(input);
2745 }
2746}
2747
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002748static void setup_file_in_str(struct in_str *i, FILE *f)
2749{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002750 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002751 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002752 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002753}
2754
2755static void setup_string_in_str(struct in_str *i, const char *s)
2756{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002757 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002758 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002759 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002760}
2761
2762
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002763/*
2764 * o_string support
2765 */
2766#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002767
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002768static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002769{
2770 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002771 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002772 if (o->data)
2773 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002774}
2775
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002776static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002777{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002778 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002779 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002780}
2781
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002782static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2783{
2784 free(o->data);
2785}
2786
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002787static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002788{
2789 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002790 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002791 o->data = xrealloc(o->data, 1 + o->maxlen);
2792 }
2793}
2794
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002795static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002796{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002797 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002798 if (o->length < o->maxlen) {
2799 /* likely. avoid o_grow_by() call */
2800 add:
2801 o->data[o->length] = ch;
2802 o->length++;
2803 o->data[o->length] = '\0';
2804 return;
2805 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002806 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002807 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002808}
2809
Denys Vlasenko657086a2016-09-29 18:07:42 +02002810#if 0
2811/* Valid only if we know o_string is not empty */
2812static void o_delchr(o_string *o)
2813{
2814 o->length--;
2815 o->data[o->length] = '\0';
2816}
2817#endif
2818
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002819static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002820{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002821 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002822 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002823 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002824}
2825
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002826static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002827{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002828 o_addblock(o, str, strlen(str));
2829}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002830
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002831#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002832static void nommu_addchr(o_string *o, int ch)
2833{
2834 if (o)
2835 o_addchr(o, ch);
2836}
2837#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002838# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002839#endif
2840
2841static void o_addstr_with_NUL(o_string *o, const char *str)
2842{
2843 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002844}
2845
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002846/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002847 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002848 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2849 * Apparently, on unquoted $v bash still does globbing
2850 * ("v='*.txt'; echo $v" prints all .txt files),
2851 * but NOT brace expansion! Thus, there should be TWO independent
2852 * quoting mechanisms on $v expansion side: one protects
2853 * $v from brace expansion, and other additionally protects "$v" against globbing.
2854 * We have only second one.
2855 */
2856
Denys Vlasenko9e800222010-10-03 14:28:04 +02002857#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002858# define MAYBE_BRACES "{}"
2859#else
2860# define MAYBE_BRACES ""
2861#endif
2862
Eric Andersen25f27032001-04-26 23:22:31 +00002863/* My analysis of quoting semantics tells me that state information
2864 * is associated with a destination, not a source.
2865 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002866static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002867{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002868 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002869 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002870 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002871 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002872 o_grow_by(o, sz);
2873 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002874 o->data[o->length] = '\\';
2875 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002876 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002877 o->data[o->length] = ch;
2878 o->length++;
2879 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002880}
2881
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002882static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002883{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002884 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002885 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2886 && strchr("*?[\\" MAYBE_BRACES, ch)
2887 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002888 sz++;
2889 o->data[o->length] = '\\';
2890 o->length++;
2891 }
2892 o_grow_by(o, sz);
2893 o->data[o->length] = ch;
2894 o->length++;
2895 o->data[o->length] = '\0';
2896}
2897
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002898static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002899{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002900 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002901 char ch;
2902 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002903 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002904 if (ordinary_cnt > len) /* paranoia */
2905 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002906 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002907 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002908 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002909 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002910 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002911
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002912 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002914 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002915 sz++;
2916 o->data[o->length] = '\\';
2917 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002918 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002919 o_grow_by(o, sz);
2920 o->data[o->length] = ch;
2921 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002922 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002923 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002924}
2925
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002926static void o_addQblock(o_string *o, const char *str, int len)
2927{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002928 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002929 o_addblock(o, str, len);
2930 return;
2931 }
2932 o_addqblock(o, str, len);
2933}
2934
Denys Vlasenko38292b62010-09-05 14:49:40 +02002935static void o_addQstr(o_string *o, const char *str)
2936{
2937 o_addQblock(o, str, strlen(str));
2938}
2939
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002940/* A special kind of o_string for $VAR and `cmd` expansion.
2941 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002942 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002943 * list[i] contains an INDEX (int!) into this string data.
2944 * It means that if list[] needs to grow, data needs to be moved higher up
2945 * but list[i]'s need not be modified.
2946 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002947 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002948 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2949 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002950#if DEBUG_EXPAND || DEBUG_GLOB
2951static void debug_print_list(const char *prefix, o_string *o, int n)
2952{
2953 char **list = (char**)o->data;
2954 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2955 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002956
2957 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002958 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 +02002959 prefix, list, n, string_start, o->length, o->maxlen,
2960 !!(o->o_expflags & EXP_FLAG_GLOB),
2961 o->has_quoted_part,
2962 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002963 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002964 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002965 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2966 o->data + (int)(uintptr_t)list[i] + string_start,
2967 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002968 i++;
2969 }
2970 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002971 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002972 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002973 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002974 }
2975}
2976#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002977# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002978#endif
2979
2980/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2981 * in list[n] so that it points past last stored byte so far.
2982 * It returns n+1. */
2983static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002984{
2985 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002986 int string_start;
2987 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002988
2989 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002990 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2991 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002992 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002993 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002994 /* list[n] points to string_start, make space for 16 more pointers */
2995 o->maxlen += 0x10 * sizeof(list[0]);
2996 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002997 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002998 memmove(list + n + 0x10, list + n, string_len);
2999 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003000 } else {
3001 debug_printf_list("list[%d]=%d string_start=%d\n",
3002 n, string_len, string_start);
3003 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003004 } else {
3005 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003006 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3007 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003008 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3009 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003010 o->has_empty_slot = 0;
3011 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003012 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003013 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003014 return n + 1;
3015}
3016
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003017/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003018static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003019{
3020 char **list = (char**)o->data;
3021 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3022
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003023 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003024}
3025
Denys Vlasenko9e800222010-10-03 14:28:04 +02003026#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003027/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3028 * first, it processes even {a} (no commas), second,
3029 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003030 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003031 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003032
3033/* Helper */
3034static int glob_needed(const char *s)
3035{
3036 while (*s) {
3037 if (*s == '\\') {
3038 if (!s[1])
3039 return 0;
3040 s += 2;
3041 continue;
3042 }
3043 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3044 return 1;
3045 s++;
3046 }
3047 return 0;
3048}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003049/* Return pointer to next closing brace or to comma */
3050static const char *next_brace_sub(const char *cp)
3051{
3052 unsigned depth = 0;
3053 cp++;
3054 while (*cp != '\0') {
3055 if (*cp == '\\') {
3056 if (*++cp == '\0')
3057 break;
3058 cp++;
3059 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003060 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003061 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003062 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003063 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003064 depth++;
3065 }
3066
3067 return *cp != '\0' ? cp : NULL;
3068}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003069/* Recursive brace globber. Note: may garble pattern[]. */
3070static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003071{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003072 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003073 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003074 const char *next;
3075 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003076 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003077 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003078
3079 debug_printf_glob("glob_brace('%s')\n", pattern);
3080
3081 begin = pattern;
3082 while (1) {
3083 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003084 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003085 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003086 /* Find the first sub-pattern and at the same time
3087 * find the rest after the closing brace */
3088 next = next_brace_sub(begin);
3089 if (next == NULL) {
3090 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003091 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003092 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003093 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003094 /* "{abc}" with no commas - illegal
3095 * brace expr, disregard and skip it */
3096 begin = next + 1;
3097 continue;
3098 }
3099 break;
3100 }
3101 if (*begin == '\\' && begin[1] != '\0')
3102 begin++;
3103 begin++;
3104 }
3105 debug_printf_glob("begin:%s\n", begin);
3106 debug_printf_glob("next:%s\n", next);
3107
3108 /* Now find the end of the whole brace expression */
3109 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003110 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003111 rest = next_brace_sub(rest);
3112 if (rest == NULL) {
3113 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003114 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003115 }
3116 debug_printf_glob("rest:%s\n", rest);
3117 }
3118 rest_len = strlen(++rest) + 1;
3119
3120 /* We are sure the brace expression is well-formed */
3121
3122 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003123 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003124
3125 /* We have a brace expression. BEGIN points to the opening {,
3126 * NEXT points past the terminator of the first element, and REST
3127 * points past the final }. We will accumulate result names from
3128 * recursive runs for each brace alternative in the buffer using
3129 * GLOB_APPEND. */
3130
3131 p = begin + 1;
3132 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003133 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003134 memcpy(
3135 mempcpy(
3136 mempcpy(new_pattern_buf,
3137 /* We know the prefix for all sub-patterns */
3138 pattern, begin - pattern),
3139 p, next - p),
3140 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003141
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003142 /* Note: glob_brace() may garble new_pattern_buf[].
3143 * That's why we re-copy prefix every time (1st memcpy above).
3144 */
3145 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003146 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003147 /* We saw the last entry */
3148 break;
3149 }
3150 p = next + 1;
3151 next = next_brace_sub(next);
3152 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003153 free(new_pattern_buf);
3154 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003155
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003156 simple_glob:
3157 {
3158 int gr;
3159 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003160
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003161 memset(&globdata, 0, sizeof(globdata));
3162 gr = glob(pattern, 0, NULL, &globdata);
3163 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3164 if (gr != 0) {
3165 if (gr == GLOB_NOMATCH) {
3166 globfree(&globdata);
3167 /* NB: garbles parameter */
3168 unbackslash(pattern);
3169 o_addstr_with_NUL(o, pattern);
3170 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3171 return o_save_ptr_helper(o, n);
3172 }
3173 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003174 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003175 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3176 * but we didn't specify it. Paranoia again. */
3177 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3178 }
3179 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3180 char **argv = globdata.gl_pathv;
3181 while (1) {
3182 o_addstr_with_NUL(o, *argv);
3183 n = o_save_ptr_helper(o, n);
3184 argv++;
3185 if (!*argv)
3186 break;
3187 }
3188 }
3189 globfree(&globdata);
3190 }
3191 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003192}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003193/* Performs globbing on last list[],
3194 * saving each result as a new list[].
3195 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003196static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003197{
3198 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003199
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003200 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003201 if (!o->data)
3202 return o_save_ptr_helper(o, n);
3203 pattern = o->data + o_get_last_ptr(o, n);
3204 debug_printf_glob("glob pattern '%s'\n", pattern);
3205 if (!glob_needed(pattern)) {
3206 /* unbackslash last string in o in place, fix length */
3207 o->length = unbackslash(pattern) - o->data;
3208 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3209 return o_save_ptr_helper(o, n);
3210 }
3211
3212 copy = xstrdup(pattern);
3213 /* "forget" pattern in o */
3214 o->length = pattern - o->data;
3215 n = glob_brace(copy, o, n);
3216 free(copy);
3217 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003218 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003219 return n;
3220}
3221
Denys Vlasenko238081f2010-10-03 14:26:26 +02003222#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003223
3224/* Helper */
3225static int glob_needed(const char *s)
3226{
3227 while (*s) {
3228 if (*s == '\\') {
3229 if (!s[1])
3230 return 0;
3231 s += 2;
3232 continue;
3233 }
3234 if (*s == '*' || *s == '[' || *s == '?')
3235 return 1;
3236 s++;
3237 }
3238 return 0;
3239}
3240/* Performs globbing on last list[],
3241 * saving each result as a new list[].
3242 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003243static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003244{
3245 glob_t globdata;
3246 int gr;
3247 char *pattern;
3248
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003249 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003250 if (!o->data)
3251 return o_save_ptr_helper(o, n);
3252 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003253 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003254 if (!glob_needed(pattern)) {
3255 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003256 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003257 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003258 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003259 return o_save_ptr_helper(o, n);
3260 }
3261
3262 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003263 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3264 * If we glob "*.\*" and don't find anything, we need
3265 * to fall back to using literal "*.*", but GLOB_NOCHECK
3266 * will return "*.\*"!
3267 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003268 gr = glob(pattern, 0, NULL, &globdata);
3269 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003270 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003271 if (gr == GLOB_NOMATCH) {
3272 globfree(&globdata);
3273 goto literal;
3274 }
3275 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003276 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003277 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3278 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003279 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003280 }
3281 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3282 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003283 /* "forget" pattern in o */
3284 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003285 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003286 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003287 n = o_save_ptr_helper(o, n);
3288 argv++;
3289 if (!*argv)
3290 break;
3291 }
3292 }
3293 globfree(&globdata);
3294 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003295 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003296 return n;
3297}
3298
Denys Vlasenko238081f2010-10-03 14:26:26 +02003299#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003300
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003301/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003302 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003303static int o_save_ptr(o_string *o, int n)
3304{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003305 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003306 /* If o->has_empty_slot, list[n] was already globbed
3307 * (if it was requested back then when it was filled)
3308 * so don't do that again! */
3309 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003310 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003311 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003312 return o_save_ptr_helper(o, n);
3313}
3314
3315/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003316static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003317{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003318 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003319 int string_start;
3320
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003321 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3322 if (DEBUG_EXPAND)
3323 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003324 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003325 list = (char**)o->data;
3326 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3327 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003328 while (n) {
3329 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003330 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003331 }
3332 return list;
3333}
3334
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003335static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003336
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003337/* Returns pi->next - next pipe in the list */
3338static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003339{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003340 struct pipe *next;
3341 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003342
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003343 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003344 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003345 struct command *command;
3346 struct redir_struct *r, *rnext;
3347
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003348 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003349 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003350 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003351 if (DEBUG_CLEAN) {
3352 int a;
3353 char **p;
3354 for (a = 0, p = command->argv; *p; a++, p++) {
3355 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3356 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003357 }
3358 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003359 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003360 }
3361 /* not "else if": on syntax error, we may have both! */
3362 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003363 debug_printf_clean(" begin group (cmd_type:%d)\n",
3364 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003365 free_pipe_list(command->group);
3366 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003367 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003368 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003369 /* else is crucial here.
3370 * If group != NULL, child_func is meaningless */
3371#if ENABLE_HUSH_FUNCTIONS
3372 else if (command->child_func) {
3373 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3374 command->child_func->parent_cmd = NULL;
3375 }
3376#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003377#if !BB_MMU
3378 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003379 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003380#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003381 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003382 debug_printf_clean(" redirect %d%s",
3383 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003384 /* guard against the case >$FOO, where foo is unset or blank */
3385 if (r->rd_filename) {
3386 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3387 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003388 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003389 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003390 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003391 rnext = r->next;
3392 free(r);
3393 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003394 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003395 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003396 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003397 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003398#if ENABLE_HUSH_JOB
3399 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003400 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003401#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003402
3403 next = pi->next;
3404 free(pi);
3405 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003406}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003407
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003408static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003409{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003410 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003411#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003412 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003413#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003414 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003415 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003416 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003417}
3418
3419
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003420/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003421
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003422#ifndef debug_print_tree
3423static void debug_print_tree(struct pipe *pi, int lvl)
3424{
3425 static const char *const PIPE[] = {
3426 [PIPE_SEQ] = "SEQ",
3427 [PIPE_AND] = "AND",
3428 [PIPE_OR ] = "OR" ,
3429 [PIPE_BG ] = "BG" ,
3430 };
3431 static const char *RES[] = {
3432 [RES_NONE ] = "NONE" ,
3433# if ENABLE_HUSH_IF
3434 [RES_IF ] = "IF" ,
3435 [RES_THEN ] = "THEN" ,
3436 [RES_ELIF ] = "ELIF" ,
3437 [RES_ELSE ] = "ELSE" ,
3438 [RES_FI ] = "FI" ,
3439# endif
3440# if ENABLE_HUSH_LOOPS
3441 [RES_FOR ] = "FOR" ,
3442 [RES_WHILE] = "WHILE",
3443 [RES_UNTIL] = "UNTIL",
3444 [RES_DO ] = "DO" ,
3445 [RES_DONE ] = "DONE" ,
3446# endif
3447# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3448 [RES_IN ] = "IN" ,
3449# endif
3450# if ENABLE_HUSH_CASE
3451 [RES_CASE ] = "CASE" ,
3452 [RES_CASE_IN ] = "CASE_IN" ,
3453 [RES_MATCH] = "MATCH",
3454 [RES_CASE_BODY] = "CASE_BODY",
3455 [RES_ESAC ] = "ESAC" ,
3456# endif
3457 [RES_XXXX ] = "XXXX" ,
3458 [RES_SNTX ] = "SNTX" ,
3459 };
3460 static const char *const CMDTYPE[] = {
3461 "{}",
3462 "()",
3463 "[noglob]",
3464# if ENABLE_HUSH_FUNCTIONS
3465 "func()",
3466# endif
3467 };
3468
3469 int pin, prn;
3470
3471 pin = 0;
3472 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003473 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3474 lvl*2, "",
3475 pin,
3476 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3477 RES[pi->res_word],
3478 pi->followup, PIPE[pi->followup]
3479 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003480 prn = 0;
3481 while (prn < pi->num_cmds) {
3482 struct command *command = &pi->cmds[prn];
3483 char **argv = command->argv;
3484
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003485 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003486 lvl*2, "", prn,
3487 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003488#if ENABLE_HUSH_LINENO_VAR
3489 fdprintf(2, " LINENO:%u", command->lineno);
3490#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003491 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003492 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003493 CMDTYPE[command->cmd_type],
3494 argv
3495# if !BB_MMU
3496 , " group_as_string:", command->group_as_string
3497# else
3498 , "", ""
3499# endif
3500 );
3501 debug_print_tree(command->group, lvl+1);
3502 prn++;
3503 continue;
3504 }
3505 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003506 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003507 argv++;
3508 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003509 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003510 prn++;
3511 }
3512 pi = pi->next;
3513 pin++;
3514 }
3515}
3516#endif /* debug_print_tree */
3517
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003518static struct pipe *new_pipe(void)
3519{
Eric Andersen25f27032001-04-26 23:22:31 +00003520 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003521 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003522 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003523 return pi;
3524}
3525
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003526/* Command (member of a pipe) is complete, or we start a new pipe
3527 * if ctx->command is NULL.
3528 * No errors possible here.
3529 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003530static int done_command(struct parse_context *ctx)
3531{
3532 /* The command is really already in the pipe structure, so
3533 * advance the pipe counter and make a new, null command. */
3534 struct pipe *pi = ctx->pipe;
3535 struct command *command = ctx->command;
3536
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003537#if 0 /* Instead we emit error message at run time */
3538 if (ctx->pending_redirect) {
3539 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003540 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003541 ctx->pending_redirect = NULL;
3542 }
3543#endif
3544
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003545 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003546 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003547 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003548 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003549 }
3550 pi->num_cmds++;
3551 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003552 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553 } else {
3554 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3555 }
3556
3557 /* Only real trickiness here is that the uncommitted
3558 * command structure is not counted in pi->num_cmds. */
3559 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003560 ctx->command = command = &pi->cmds[pi->num_cmds];
3561 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003562 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003563#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003564 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003565 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003566#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003567 return pi->num_cmds; /* used only for 0/nonzero check */
3568}
3569
3570static void done_pipe(struct parse_context *ctx, pipe_style type)
3571{
3572 int not_null;
3573
3574 debug_printf_parse("done_pipe entered, followup %d\n", type);
3575 /* Close previous command */
3576 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003577#if HAS_KEYWORDS
3578 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3579 ctx->ctx_inverted = 0;
3580 ctx->pipe->res_word = ctx->ctx_res_w;
3581#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003582 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3583 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003584 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3585 * in a backgrounded subshell.
3586 */
3587 struct pipe *pi;
3588 struct command *command;
3589
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003590 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003591 pi = ctx->list_head;
3592 while (pi != ctx->pipe) {
3593 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3594 goto no_conv;
3595 pi = pi->next;
3596 }
3597
3598 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3599 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3600 pi = xzalloc(sizeof(*pi));
3601 pi->followup = PIPE_BG;
3602 pi->num_cmds = 1;
3603 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3604 command = &pi->cmds[0];
3605 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3606 command->cmd_type = CMD_NORMAL;
3607 command->group = ctx->list_head;
3608#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003609 command->group_as_string = xstrndup(
3610 ctx->as_string.data,
3611 ctx->as_string.length - 1 /* do not copy last char, "&" */
3612 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003613#endif
3614 /* Replace all pipes in ctx with one newly created */
3615 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003616 } else {
3617 no_conv:
3618 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003619 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003620
3621 /* Without this check, even just <enter> on command line generates
3622 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003623 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003624 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003625#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003626 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003627#endif
3628#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003629 || ctx->ctx_res_w == RES_DONE
3630 || ctx->ctx_res_w == RES_FOR
3631 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003632#endif
3633#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003634 || ctx->ctx_res_w == RES_ESAC
3635#endif
3636 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003637 struct pipe *new_p;
3638 debug_printf_parse("done_pipe: adding new pipe: "
3639 "not_null:%d ctx->ctx_res_w:%d\n",
3640 not_null, ctx->ctx_res_w);
3641 new_p = new_pipe();
3642 ctx->pipe->next = new_p;
3643 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003644 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003645 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003646 * This is used to control execution.
3647 * RES_FOR and RES_IN are NOT sticky (needed to support
3648 * cases where variable or value happens to match a keyword):
3649 */
3650#if ENABLE_HUSH_LOOPS
3651 if (ctx->ctx_res_w == RES_FOR
3652 || ctx->ctx_res_w == RES_IN)
3653 ctx->ctx_res_w = RES_NONE;
3654#endif
3655#if ENABLE_HUSH_CASE
3656 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003657 ctx->ctx_res_w = RES_CASE_BODY;
3658 if (ctx->ctx_res_w == RES_CASE)
3659 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003660#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003661 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003662 /* Create the memory for command, roughly:
3663 * ctx->pipe->cmds = new struct command;
3664 * ctx->command = &ctx->pipe->cmds[0];
3665 */
3666 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003667 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003668 }
3669 debug_printf_parse("done_pipe return\n");
3670}
3671
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003672static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003673{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003674 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003675 if (MAYBE_ASSIGNMENT != 0)
3676 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003677 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003678 /* Create the memory for command, roughly:
3679 * ctx->pipe->cmds = new struct command;
3680 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003681 */
3682 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003683}
3684
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003685/* If a reserved word is found and processed, parse context is modified
3686 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003687 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003688#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003689struct reserved_combo {
3690 char literal[6];
3691 unsigned char res;
3692 unsigned char assignment_flag;
3693 int flag;
3694};
3695enum {
3696 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003697# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003698 FLAG_IF = (1 << RES_IF ),
3699 FLAG_THEN = (1 << RES_THEN ),
3700 FLAG_ELIF = (1 << RES_ELIF ),
3701 FLAG_ELSE = (1 << RES_ELSE ),
3702 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003703# endif
3704# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003705 FLAG_FOR = (1 << RES_FOR ),
3706 FLAG_WHILE = (1 << RES_WHILE),
3707 FLAG_UNTIL = (1 << RES_UNTIL),
3708 FLAG_DO = (1 << RES_DO ),
3709 FLAG_DONE = (1 << RES_DONE ),
3710 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003711# endif
3712# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003713 FLAG_MATCH = (1 << RES_MATCH),
3714 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003715# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003716 FLAG_START = (1 << RES_XXXX ),
3717};
3718
3719static const struct reserved_combo* match_reserved_word(o_string *word)
3720{
Eric Andersen25f27032001-04-26 23:22:31 +00003721 /* Mostly a list of accepted follow-up reserved words.
3722 * FLAG_END means we are done with the sequence, and are ready
3723 * to turn the compound list into a command.
3724 * FLAG_START means the word must start a new compound list.
3725 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003726 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003727# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003728 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3729 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3730 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3731 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3732 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3733 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003734# endif
3735# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003736 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3737 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3738 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3739 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3740 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3741 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003742# endif
3743# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003744 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3745 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003746# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003747 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003748 const struct reserved_combo *r;
3749
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003750 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003751 if (strcmp(word->data, r->literal) == 0)
3752 return r;
3753 }
3754 return NULL;
3755}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003756/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003757 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003758static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003759{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003760# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003761 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003762 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003763 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003764# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003765 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003766
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003767 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003768 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003769 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003770 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003771 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003772
3773 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003774# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003775 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3776 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003777 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003778 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003779# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003780 if (r->flag == 0) { /* '!' */
3781 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003782 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003783 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003784 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003785 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003786 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003787 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003788 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003789 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003790
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003791 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003792 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003793 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003794 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003795 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003796 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003797 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003798 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003799 } else {
3800 /* "{...} fi" is ok. "{...} if" is not
3801 * Example:
3802 * if { echo foo; } then { echo bar; } fi */
3803 if (ctx->command->group)
3804 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003805 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003806
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003807 ctx->ctx_res_w = r->res;
3808 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003809 ctx->is_assignment = r->assignment_flag;
3810 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003811
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003812 if (ctx->old_flag & FLAG_END) {
3813 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003814
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003815 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003816 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003817 old = ctx->stack;
3818 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003819 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003820# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003821 /* At this point, the compound command's string is in
3822 * ctx->as_string... except for the leading keyword!
3823 * Consider this example: "echo a | if true; then echo a; fi"
3824 * ctx->as_string will contain "true; then echo a; fi",
3825 * with "if " remaining in old->as_string!
3826 */
3827 {
3828 char *str;
3829 int len = old->as_string.length;
3830 /* Concatenate halves */
3831 o_addstr(&old->as_string, ctx->as_string.data);
3832 o_free_unsafe(&ctx->as_string);
3833 /* Find where leading keyword starts in first half */
3834 str = old->as_string.data + len;
3835 if (str > old->as_string.data)
3836 str--; /* skip whitespace after keyword */
3837 while (str > old->as_string.data && isalpha(str[-1]))
3838 str--;
3839 /* Ugh, we're done with this horrid hack */
3840 old->command->group_as_string = xstrdup(str);
3841 debug_printf_parse("pop, remembering as:'%s'\n",
3842 old->command->group_as_string);
3843 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003844# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003845 *ctx = *old; /* physical copy */
3846 free(old);
3847 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003848 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003849}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003850#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003851
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003852/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003853 * Normal return is 0. Syntax errors return 1.
3854 * Note: on return, word is reset, but not o_free'd!
3855 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003856static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003857{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003858 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003859
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003860 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3861 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003862 debug_printf_parse("done_word return 0: true null, ignored\n");
3863 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003864 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003865
Eric Andersen25f27032001-04-26 23:22:31 +00003866 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003867 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3868 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003869 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003870 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003871 * If the redirection operator is "<<" or "<<-", the word
3872 * that follows the redirection operator shall be
3873 * subjected to quote removal; it is unspecified whether
3874 * any of the other expansions occur. For the other
3875 * redirection operators, the word that follows the
3876 * redirection operator shall be subjected to tilde
3877 * expansion, parameter expansion, command substitution,
3878 * arithmetic expansion, and quote removal.
3879 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003880 * on the word by a non-interactive shell; an interactive
3881 * shell may perform it, but shall do so only when
3882 * the expansion would result in one word."
3883 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003884//bash does not do parameter/command substitution or arithmetic expansion
3885//for _heredoc_ redirection word: these constructs look for exact eof marker
3886// as written:
3887// <<EOF$t
3888// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003889// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3890
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003891 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003892 /* Cater for >\file case:
3893 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3894 * Same with heredocs:
3895 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3896 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003897 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3898 unbackslash(ctx->pending_redirect->rd_filename);
3899 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003900 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003901 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3902 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003903 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003904 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003905 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003906 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003907#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003908# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003909 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003910 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003911 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003912 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003913 /* ctx->ctx_res_w = RES_MATCH; */
3914 ctx->ctx_dsemicolon = 0;
3915 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003916# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003917 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003918# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003919 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3920 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003921# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003922# if ENABLE_HUSH_CASE
3923 && ctx->ctx_res_w != RES_CASE
3924# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003925 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003926 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003927 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003928 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003929 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003930# if ENABLE_HUSH_LINENO_VAR
3931/* Case:
3932 * "while ...; do
3933 * cmd ..."
3934 * If we don't close the pipe _now_, immediately after "do", lineno logic
3935 * sees "cmd" as starting at "do" - i.e., at the previous line.
3936 */
3937 if (0
3938 IF_HUSH_IF(|| reserved->res == RES_THEN)
3939 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3940 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3941 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3942 ) {
3943 done_pipe(ctx, PIPE_SEQ);
3944 }
3945# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003946 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003947 debug_printf_parse("done_word return %d\n",
3948 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003949 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003950 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003951# if defined(CMD_SINGLEWORD_NOGLOB)
3952 if (0
3953# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003954 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003955# endif
3956 /* In bash, local/export/readonly are special, args
3957 * are assignments and therefore expansion of them
3958 * should be "one-word" expansion:
3959 * $ export i=`echo 'a b'` # one arg: "i=a b"
3960 * compare with:
3961 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3962 * ls: cannot access i=a: No such file or directory
3963 * ls: cannot access b: No such file or directory
3964 * Note: bash 3.2.33(1) does this only if export word
3965 * itself is not quoted:
3966 * $ export i=`echo 'aaa bbb'`; echo "$i"
3967 * aaa bbb
3968 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3969 * aaa
3970 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003971 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3972 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3973 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003974 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003975 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3976 }
3977 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003978# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003979 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003980#endif /* HAS_KEYWORDS */
3981
Denis Vlasenkobb929512009-04-16 10:59:40 +00003982 if (command->group) {
3983 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003984 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003985 debug_printf_parse("done_word return 1: syntax error, "
3986 "groups and arglists don't mix\n");
3987 return 1;
3988 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003989
3990 /* If this word wasn't an assignment, next ones definitely
3991 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003992 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
3993 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003994 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003995 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003996 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003997 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003998 command->assignment_cnt++;
3999 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4000 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004001 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4002 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004003 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004004 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4005 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004006 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004007 }
Eric Andersen25f27032001-04-26 23:22:31 +00004008
Denis Vlasenko06810332007-05-21 23:30:54 +00004009#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004010 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004011 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004012 || !is_well_formed_var_name(command->argv[0], '\0')
4013 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004014 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004015 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004016 return 1;
4017 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004018 /* Force FOR to have just one word (variable name) */
4019 /* NB: basically, this makes hush see "for v in ..."
4020 * syntax as if it is "for v; in ...". FOR and IN become
4021 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004022 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004023 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004024#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004025#if ENABLE_HUSH_CASE
4026 /* Force CASE to have just one word */
4027 if (ctx->ctx_res_w == RES_CASE) {
4028 done_pipe(ctx, PIPE_SEQ);
4029 }
4030#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004031
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004032 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004033
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004034 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004035 return 0;
4036}
4037
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004038
4039/* Peek ahead in the input to find out if we have a "&n" construct,
4040 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004041 * Return:
4042 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4043 * REDIRFD_SYNTAX_ERR if syntax error,
4044 * REDIRFD_TO_FILE if no & was seen,
4045 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004046 */
4047#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004048#define parse_redir_right_fd(as_string, input) \
4049 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004050#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004051static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004052{
4053 int ch, d, ok;
4054
4055 ch = i_peek(input);
4056 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004057 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004058
4059 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004060 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004061 ch = i_peek(input);
4062 if (ch == '-') {
4063 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004064 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004065 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004066 }
4067 d = 0;
4068 ok = 0;
4069 while (ch != EOF && isdigit(ch)) {
4070 d = d*10 + (ch-'0');
4071 ok = 1;
4072 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004073 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004074 ch = i_peek(input);
4075 }
4076 if (ok) return d;
4077
4078//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4079
4080 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004081 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004082}
4083
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004084/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004085 */
4086static int parse_redirect(struct parse_context *ctx,
4087 int fd,
4088 redir_type style,
4089 struct in_str *input)
4090{
4091 struct command *command = ctx->command;
4092 struct redir_struct *redir;
4093 struct redir_struct **redirp;
4094 int dup_num;
4095
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004096 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004098 /* Check for a '>&1' type redirect */
4099 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4100 if (dup_num == REDIRFD_SYNTAX_ERR)
4101 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004102 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004103 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004104 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004105 if (dup_num) { /* <<-... */
4106 ch = i_getch(input);
4107 nommu_addchr(&ctx->as_string, ch);
4108 ch = i_peek(input);
4109 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004110 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004111
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004112 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004113 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004114 if (ch == '|') {
4115 /* >|FILE redirect ("clobbering" >).
4116 * Since we do not support "set -o noclobber" yet,
4117 * >| and > are the same for now. Just eat |.
4118 */
4119 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004120 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004121 }
4122 }
4123
4124 /* Create a new redir_struct and append it to the linked list */
4125 redirp = &command->redirects;
4126 while ((redir = *redirp) != NULL) {
4127 redirp = &(redir->next);
4128 }
4129 *redirp = redir = xzalloc(sizeof(*redir));
4130 /* redir->next = NULL; */
4131 /* redir->rd_filename = NULL; */
4132 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004133 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004135 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4136 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004137
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004138 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004139 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004140 /* Erik had a check here that the file descriptor in question
4141 * is legit; I postpone that to "run time"
4142 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004143 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4144 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004145 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004146#if 0 /* Instead we emit error message at run time */
4147 if (ctx->pending_redirect) {
4148 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004149 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004150 }
4151#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004152 /* Set ctx->pending_redirect, so we know what to do at the
4153 * end of the next parsed word. */
4154 ctx->pending_redirect = redir;
4155 }
4156 return 0;
4157}
4158
Eric Andersen25f27032001-04-26 23:22:31 +00004159/* If a redirect is immediately preceded by a number, that number is
4160 * supposed to tell which file descriptor to redirect. This routine
4161 * looks for such preceding numbers. In an ideal world this routine
4162 * needs to handle all the following classes of redirects...
4163 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4164 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4165 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4166 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167 *
4168 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4169 * "2.7 Redirection
4170 * ... If n is quoted, the number shall not be recognized as part of
4171 * the redirection expression. For example:
4172 * echo \2>a
4173 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004174 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 *
4176 * A -1 return means no valid number was found,
4177 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004178 */
4179static int redirect_opt_num(o_string *o)
4180{
4181 int num;
4182
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004183 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004184 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004185 num = bb_strtou(o->data, NULL, 10);
4186 if (errno || num < 0)
4187 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004188 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004189 return num;
4190}
4191
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004192#if BB_MMU
4193#define fetch_till_str(as_string, input, word, skip_tabs) \
4194 fetch_till_str(input, word, skip_tabs)
4195#endif
4196static char *fetch_till_str(o_string *as_string,
4197 struct in_str *input,
4198 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004199 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200{
4201 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004202 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004203 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004204 int ch;
4205
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004206 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004207
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004208 while (1) {
4209 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004210 if (ch != EOF)
4211 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004212 if (ch == '\n' || ch == EOF) {
4213 check_heredoc_end:
4214 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4215 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4216 heredoc.data[past_EOL] = '\0';
4217 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4218 return heredoc.data;
4219 }
4220 if (ch == '\n') {
4221 /* This is a new line.
4222 * Remember position and backslash-escaping status.
4223 */
4224 o_addchr(&heredoc, ch);
4225 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004226 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004227 past_EOL = heredoc.length;
4228 /* Get 1st char of next line, possibly skipping leading tabs */
4229 do {
4230 ch = i_getch(input);
4231 if (ch != EOF)
4232 nommu_addchr(as_string, ch);
4233 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4234 /* If this immediately ended the line,
4235 * go back to end-of-line checks.
4236 */
4237 if (ch == '\n')
4238 goto check_heredoc_end;
4239 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004240 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004241 }
4242 if (ch == EOF) {
4243 o_free_unsafe(&heredoc);
4244 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004245 }
4246 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004247 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004248 if (prev == '\\' && ch == '\\')
4249 /* Correctly handle foo\\<eol> (not a line cont.) */
4250 prev = 0; /* not \ */
4251 else
4252 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004253 }
4254}
4255
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004256/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4257 * and load them all. There should be exactly heredoc_cnt of them.
4258 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004259static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4260{
4261 struct pipe *pi = ctx->list_head;
4262
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004263 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004264 int i;
4265 struct command *cmd = pi->cmds;
4266
4267 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4268 pi->num_cmds,
4269 cmd->argv ? cmd->argv[0] : "NONE");
4270 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004271 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004272
4273 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4274 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004275 while (redir) {
4276 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004277 char *p;
4278
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004279 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004280 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004281 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004282 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004283 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004284 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004285 return 1;
4286 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004287 free(redir->rd_filename);
4288 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 heredoc_cnt--;
4290 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004291 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004292 }
4293 cmd++;
4294 }
4295 pi = pi->next;
4296 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004297#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004298 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004299 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004300 bb_error_msg_and_die("heredoc BUG 2");
4301#endif
4302 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303}
4304
4305
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004306static int run_list(struct pipe *pi);
4307#if BB_MMU
4308#define parse_stream(pstring, input, end_trigger) \
4309 parse_stream(input, end_trigger)
4310#endif
4311static struct pipe *parse_stream(char **pstring,
4312 struct in_str *input,
4313 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004314
Eric Andersen25f27032001-04-26 23:22:31 +00004315
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004316static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004317 struct in_str *input, int ch)
4318{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004319 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004320 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004321 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004322#if BB_MMU
4323# define as_string NULL
4324#else
4325 char *as_string = NULL;
4326#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004327 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004328 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004329 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004330
4331 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004332#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004333 if (ch == '(' && !ctx->word.has_quoted_part) {
4334 if (ctx->word.length)
4335 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004336 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004337 if (!command->argv)
4338 goto skip; /* (... */
4339 if (command->argv[1]) { /* word word ... (... */
4340 syntax_error_unexpected_ch('(');
4341 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004342 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004343 /* it is "word(..." or "word (..." */
4344 do
4345 ch = i_getch(input);
4346 while (ch == ' ' || ch == '\t');
4347 if (ch != ')') {
4348 syntax_error_unexpected_ch(ch);
4349 return 1;
4350 }
4351 nommu_addchr(&ctx->as_string, ch);
4352 do
4353 ch = i_getch(input);
4354 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004355 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004356 syntax_error_unexpected_ch(ch);
4357 return 1;
4358 }
4359 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004360 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004361 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004362 }
4363#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004364
4365#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004366 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004367 || ctx->word.length /* word{... */
4368 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004369 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004370 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004371 debug_printf_parse("parse_group return 1: "
4372 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004373 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004374 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004375#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004376
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004377 IF_HUSH_FUNCTIONS(skip:)
4378
Denis Vlasenko240c2552009-04-03 03:45:05 +00004379 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004380 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004381 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004382 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4383 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004384 } else {
4385 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004386 ch = i_peek(input);
4387 if (ch != ' ' && ch != '\t' && ch != '\n'
4388 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4389 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004390 syntax_error_unexpected_ch(ch);
4391 return 1;
4392 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004393 if (ch != '(') {
4394 ch = i_getch(input);
4395 nommu_addchr(&ctx->as_string, ch);
4396 }
Eric Andersen25f27032001-04-26 23:22:31 +00004397 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004398
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004399 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004400#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004401 if (as_string)
4402 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004403#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004404
4405 /* empty ()/{} or parse error? */
4406 if (!pipe_list || pipe_list == ERR_PTR) {
4407 /* parse_stream already emitted error msg */
4408 if (!BB_MMU)
4409 free(as_string);
4410 debug_printf_parse("parse_group return 1: "
4411 "parse_stream returned %p\n", pipe_list);
4412 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004413 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004414#if !BB_MMU
4415 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4416 command->group_as_string = as_string;
4417 debug_printf_parse("end of group, remembering as:'%s'\n",
4418 command->group_as_string);
4419#endif
4420
4421#if ENABLE_HUSH_FUNCTIONS
4422 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4423 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4424 struct command *cmd2;
4425
4426 cmd2 = xzalloc(sizeof(*cmd2));
4427 cmd2->cmd_type = CMD_SUBSHELL;
4428 cmd2->group = pipe_list;
4429# if !BB_MMU
4430//UNTESTED!
4431 cmd2->group_as_string = command->group_as_string;
4432 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4433# endif
4434
4435 pipe_list = new_pipe();
4436 pipe_list->cmds = cmd2;
4437 pipe_list->num_cmds = 1;
4438 }
4439#endif
4440
4441 command->group = pipe_list;
4442
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004443 debug_printf_parse("parse_group return 0\n");
4444 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004445 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004446#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004447}
4448
Denys Vlasenko0b883582016-12-23 16:49:07 +01004449#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004450/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004451static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004452/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004453static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004454{
4455 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004456 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004457 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004458 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004459 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004460 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004461 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004462 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004463 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004464 }
4465}
4466/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004467static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004468{
4469 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004470 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004471 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004472 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004473 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004474 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004476 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004478 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004479 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004480 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004481 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004482 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004483 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4484 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004485 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004486 continue;
4487 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004488 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004489 }
4490}
4491/* Process `cmd` - copy contents until "`" is seen. Complicated by
4492 * \` quoting.
4493 * "Within the backquoted style of command substitution, backslash
4494 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4495 * The search for the matching backquote shall be satisfied by the first
4496 * backquote found without a preceding backslash; during this search,
4497 * if a non-escaped backquote is encountered within a shell comment,
4498 * a here-document, an embedded command substitution of the $(command)
4499 * form, or a quoted string, undefined results occur. A single-quoted
4500 * or double-quoted string that begins, but does not end, within the
4501 * "`...`" sequence produces undefined results."
4502 * Example Output
4503 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4504 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004505static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004506{
4507 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004508 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004509 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004510 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004511 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004512 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4513 ch = i_getch(input);
4514 if (ch != '`'
4515 && ch != '$'
4516 && ch != '\\'
4517 && (!in_dquote || ch != '"')
4518 ) {
4519 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004520 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004521 }
4522 if (ch == EOF) {
4523 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004524 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004525 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004526 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004527 }
4528}
4529/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4530 * quoting and nested ()s.
4531 * "With the $(command) style of command substitution, all characters
4532 * following the open parenthesis to the matching closing parenthesis
4533 * constitute the command. Any valid shell script can be used for command,
4534 * except a script consisting solely of redirections which produces
4535 * unspecified results."
4536 * Example Output
4537 * echo $(echo '(TEST)' BEST) (TEST) BEST
4538 * echo $(echo 'TEST)' BEST) TEST) BEST
4539 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004540 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004541 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004542 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004543 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4544 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004545 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004546#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004547static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004548{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004549 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004550 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004551# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004552 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004553# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004554 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4555
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004556 G.promptmode = 1; /* PS2 */
4557 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4558
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004559 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004560 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004561 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004562 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004563 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004564 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004565 if (ch == end_ch
4566# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004567 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004568# endif
4569 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004570 if (!dbl)
4571 break;
4572 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004573 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004574 i_getch(input); /* eat second ')' */
4575 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004576 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004577 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004578 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004579 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004580 if (ch == '(' || ch == '{') {
4581 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004582 if (!add_till_closing_bracket(dest, input, ch))
4583 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004584 o_addchr(dest, ch);
4585 continue;
4586 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004587 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588 if (!add_till_single_quote(dest, input))
4589 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004590 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004591 continue;
4592 }
4593 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004594 if (!add_till_double_quote(dest, input))
4595 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004596 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004597 continue;
4598 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004599 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004600 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4601 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004602 o_addchr(dest, ch);
4603 continue;
4604 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004605 if (ch == '\\') {
4606 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004607 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004608 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004609 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004610 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004611 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004612#if 0
4613 if (ch == '\n') {
4614 /* "backslash+newline", ignore both */
4615 o_delchr(dest); /* undo insertion of '\' */
4616 continue;
4617 }
4618#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004619 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004620 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004621 continue;
4622 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004623 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004624 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004625 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004626}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004627#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004628
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004629/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004630#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004631#define parse_dollar(as_string, dest, input, quote_mask) \
4632 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004633#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004634#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004635static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004636 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004637 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004638{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004639 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004640
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004641 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004642 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004643 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004644 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004645 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004646 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004647 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004648 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004649 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004650 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004651 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004652 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004653 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004654 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004655 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004656 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004657 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004658 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004659 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004660 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004661 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004662 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004663 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004664 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004665 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004666 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004667 o_addchr(dest, ch | quote_mask);
4668 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004669 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004670 case '$': /* pid */
4671 case '!': /* last bg pid */
4672 case '?': /* last exit code */
4673 case '#': /* number of args */
4674 case '*': /* args */
4675 case '@': /* args */
4676 goto make_one_char_var;
4677 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004678 char len_single_ch;
4679
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004680 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4681
Denys Vlasenko74369502010-05-21 19:52:01 +02004682 ch = i_getch(input); /* eat '{' */
4683 nommu_addchr(as_string, ch);
4684
Denys Vlasenko46e64982016-09-29 19:50:55 +02004685 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004686 /* It should be ${?}, or ${#var},
4687 * or even ${?+subst} - operator acting on a special variable,
4688 * or the beginning of variable name.
4689 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004690 if (ch == EOF
4691 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4692 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004693 bad_dollar_syntax:
4694 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004695 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4696 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004697 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004698 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004699 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004700 ch |= quote_mask;
4701
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004702 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004703 * However, this regresses some of our testsuite cases
4704 * which check invalid constructs like ${%}.
4705 * Oh well... let's check that the var name part is fine... */
4706
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004707 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004708 unsigned pos;
4709
Denys Vlasenko74369502010-05-21 19:52:01 +02004710 o_addchr(dest, ch);
4711 debug_printf_parse(": '%c'\n", ch);
4712
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004713 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004714 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004715 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004716 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004717
Denys Vlasenko74369502010-05-21 19:52:01 +02004718 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004719 unsigned end_ch;
4720 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004721 /* handle parameter expansions
4722 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4723 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004724 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4725 if (len_single_ch != '#'
4726 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4727 || i_peek(input) != '}'
4728 ) {
4729 goto bad_dollar_syntax;
4730 }
4731 /* else: it's "length of C" ${#C} op,
4732 * where C is a single char
4733 * special var name, e.g. ${#!}.
4734 */
4735 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004736 /* Eat everything until closing '}' (or ':') */
4737 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004738 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004739 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004740 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004741 ) {
4742 /* It's ${var:N[:M]} thing */
4743 end_ch = '}' * 0x100 + ':';
4744 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004745 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004746 && ch == '/'
4747 ) {
4748 /* It's ${var/[/]pattern[/repl]} thing */
4749 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4750 i_getch(input);
4751 nommu_addchr(as_string, '/');
4752 ch = '\\';
4753 }
4754 end_ch = '}' * 0x100 + '/';
4755 }
4756 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004757 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004758 if (!BB_MMU)
4759 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004760#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004761 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004762 if (last_ch == 0) /* error? */
4763 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004764#else
4765#error Simple code to only allow ${var} is not implemented
4766#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004767 if (as_string) {
4768 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004769 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004770 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004771
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004772 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4773 && (end_ch & 0xff00)
4774 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004775 /* close the first block: */
4776 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004777 /* while parsing N from ${var:N[:M]}
4778 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004779 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004780 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004781 end_ch = '}';
4782 goto again;
4783 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004784 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004785 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004786 /* it's ${var:N} - emulate :999999999 */
4787 o_addstr(dest, "999999999");
4788 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004789 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004790 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004791 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004792 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004793 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004794 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4795 break;
4796 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004797#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004798 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004799 unsigned pos;
4800
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004801 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004802 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004803# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004804 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004805 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004806 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004807 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4808 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004809 if (!BB_MMU)
4810 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004811 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4812 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004813 if (as_string) {
4814 o_addstr(as_string, dest->data + pos);
4815 o_addchr(as_string, ')');
4816 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004817 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004818 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004819 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004820 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004821# endif
4822# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004823 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4824 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004825 if (!BB_MMU)
4826 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004827 if (!add_till_closing_bracket(dest, input, ')'))
4828 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004829 if (as_string) {
4830 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004831 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004832 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004833 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004834# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004835 break;
4836 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004837#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004838 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004839 goto make_var;
4840#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004841 /* TODO: $_ and $-: */
4842 /* $_ Shell or shell script name; or last argument of last command
4843 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4844 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004845 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004846 ch = i_getch(input);
4847 nommu_addchr(as_string, ch);
4848 ch = i_peek_and_eat_bkslash_nl(input);
4849 if (isalnum(ch)) { /* it's $_name or $_123 */
4850 ch = '_';
4851 goto make_var1;
4852 }
4853 /* else: it's $_ */
4854#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004855 default:
4856 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004857 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004858 debug_printf_parse("parse_dollar return 1 (ok)\n");
4859 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004860#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004861}
4862
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004863#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004864# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004865#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4866 encode_string(dest, input, dquote_end, process_bkslash)
4867# else
4868/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4869#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4870 encode_string(dest, input, dquote_end)
4871# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004872#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004873
4874#else /* !MMU */
4875
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004876# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004877/* all parameters are needed, no macro tricks */
4878# else
4879#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4880 encode_string(as_string, dest, input, dquote_end)
4881# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004882#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004883static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004884 o_string *dest,
4885 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004886 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004887 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004888{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004889#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004890 const int process_bkslash = 1;
4891#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004892 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004893 int next;
4894
4895 again:
4896 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004897 if (ch != EOF)
4898 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004899 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004900 debug_printf_parse("encode_string return 1 (ok)\n");
4901 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004902 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004903 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004904 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004905 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004906 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004907 }
4908 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004909 if (ch != '\n') {
4910 next = i_peek(input);
4911 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004912 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004913 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004914 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004915 if (next == EOF) {
Denys Vlasenko1c572692018-04-10 13:09:26 +02004916// TODO: what if in interactive shell a file with
4917// echo "unterminated string\<eof>
4918// is sourced?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004919 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004920 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004921 }
4922 /* bash:
4923 * "The backslash retains its special meaning [in "..."]
4924 * only when followed by one of the following characters:
4925 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004926 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004927 * NB: in (unquoted) heredoc, above does not apply to ",
4928 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004929 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004930 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004931 ch = i_getch(input); /* eat next */
4932 if (ch == '\n')
4933 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004934 } /* else: ch remains == '\\', and we double it below: */
4935 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004936 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004937 goto again;
4938 }
4939 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004940 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4941 debug_printf_parse("encode_string return 0: "
4942 "parse_dollar returned 0 (error)\n");
4943 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004944 }
4945 goto again;
4946 }
4947#if ENABLE_HUSH_TICK
4948 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004949 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004950 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4951 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004952 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4953 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004954 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4955 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004956 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004957 }
4958#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004959 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004960 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004961#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004962}
4963
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004964/*
4965 * Scan input until EOF or end_trigger char.
4966 * Return a list of pipes to execute, or NULL on EOF
4967 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004968 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004969 * reset parsing machinery and start parsing anew,
4970 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004971 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004972static struct pipe *parse_stream(char **pstring,
4973 struct in_str *input,
4974 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004975{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004976 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004977 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004978
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004979 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004980 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004981 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004982 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004983 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004984 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004985
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004986 initialize_context(&ctx);
4987
4988 /* If very first arg is "" or '', ctx.word.data may end up NULL.
4989 * Preventing this:
4990 */
4991 o_addchr(&ctx.word, '\0');
4992 ctx.word.length = 0;
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004993
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004994 /* We used to separate words on $IFS here. This was wrong.
4995 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004996 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004997 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004998
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004999 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005000 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005001 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005002 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005003 int ch;
5004 int next;
5005 int redir_fd;
5006 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005007
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005008 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005009 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005010 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005011 if (ch == EOF) {
5012 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005013
5014 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005015 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005016 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005017 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005018 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005019 syntax_error_unterm_ch('(');
5020 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005021 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005022 if (end_trigger == '}') {
5023 syntax_error_unterm_ch('{');
5024 goto parse_error;
5025 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005026
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005027 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005028 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005029 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005030 o_free(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005031 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005032 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005033 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005034 /* (this makes bare "&" cmd a no-op.
5035 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005036 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005037 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005038 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005039 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005040 pi = NULL;
5041 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005042#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005043 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005044 if (pstring)
5045 *pstring = ctx.as_string.data;
5046 else
5047 o_free_unsafe(&ctx.as_string);
5048#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005049 debug_leave();
5050 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005051 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005052 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005053 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005054
5055 next = '\0';
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005056 if (ch != '\n') {
Denys Vlasenko1c572692018-04-10 13:09:26 +02005057 /* Do not break this case:
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005058 * echo '\
5059 * '
Denys Vlasenko1c572692018-04-10 13:09:26 +02005060 * and
5061 * echo z\\
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005062 */
Denys Vlasenko1c572692018-04-10 13:09:26 +02005063 next = (ch == '\'' || ch == '\\') ? i_peek(input) : i_peek_and_eat_bkslash_nl(input);
5064///
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005065 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005066
5067 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005068 "\\$\"" IF_HUSH_TICK("`") /* always special */
5069 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005070 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005071 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005072 || ctx.word.length /* word{... - non-special */
5073 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005074 || (next != ';' /* }; - special */
5075 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005076 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005077 && next != '&' /* }& and }&& ... - special */
5078 && next != '|' /* }|| ... - special */
5079 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005080 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005081 ) {
5082 /* They are not special, skip "{}" */
5083 is_special += 2;
5084 }
5085 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005086 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005087
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005088 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005089 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005090 o_addQchr(&ctx.word, ch);
5091 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5092 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005093 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005094 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005095 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005096 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5097 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005098 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005099 continue;
5100 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005101
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005102 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005103#if ENABLE_HUSH_LINENO_VAR
5104/* Case:
5105 * "while ...; do<whitespace><newline>
5106 * cmd ..."
5107 * would think that "cmd" starts in <whitespace> -
5108 * i.e., at the previous line.
5109 * We need to skip all whitespace before newlines.
5110 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005111 while (ch != '\n') {
5112 next = i_peek(input);
5113 if (next != ' ' && next != '\t' && next != '\n')
5114 break; /* next char is not ws */
5115 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005116 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005117 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005118#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005119 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005120 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005121 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005122 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005123 /* Is this a case when newline is simply ignored?
5124 * Some examples:
5125 * "cmd | <newline> cmd ..."
5126 * "case ... in <newline> word) ..."
5127 */
5128 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005129 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005130 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005131 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005132 * Without check #1, interactive shell
5133 * ignores even bare <newline>,
5134 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005135 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005136 * ps2> _ <=== wrong, should be ps1
5137 * Without check #2, "cmd & <newline>"
5138 * is similarly mistreated.
5139 * (BTW, this makes "cmd & cmd"
5140 * and "cmd && cmd" non-orthogonal.
5141 * Really, ask yourself, why
5142 * "cmd && <newline>" doesn't start
5143 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005144 * The only reason is that it might be
5145 * a "cmd1 && <nl> cmd2 &" construct,
5146 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005147 */
5148 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005149 if (pi->num_cmds != 0 /* check #1 */
5150 && pi->followup != PIPE_BG /* check #2 */
5151 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005152 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005153 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005154 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005155 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005156 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005157 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5158 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005159 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005160 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005161 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005162 heredoc_cnt = 0;
5163 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005164 ctx.is_assignment = MAYBE_ASSIGNMENT;
5165 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005166 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005167 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005168 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005169 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005170 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005171
5172 /* "cmd}" or "cmd }..." without semicolon or &:
5173 * } is an ordinary char in this case, even inside { cmd; }
5174 * Pathological example: { ""}; } should exec "}" cmd
5175 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005176 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005177 if (ctx.word.length != 0 /* word} */
5178 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005179 ) {
5180 goto ordinary_char;
5181 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005182 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5183 /* Generally, there should be semicolon: "cmd; }"
5184 * However, bash allows to omit it if "cmd" is
5185 * a group. Examples:
5186 * { { echo 1; } }
5187 * {(echo 1)}
5188 * { echo 0 >&2 | { echo 1; } }
5189 * { while false; do :; done }
5190 * { case a in b) ;; esac }
5191 */
5192 if (ctx.command->group)
5193 goto term_group;
5194 goto ordinary_char;
5195 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005196 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005197 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005198 goto skip_end_trigger;
5199 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005200 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005201 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005202 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005203 && (ch != ';' || heredoc_cnt == 0)
5204#if ENABLE_HUSH_CASE
5205 && (ch != ')'
5206 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005207 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005208 )
5209#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005210 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005211 if (heredoc_cnt) {
5212 /* This is technically valid:
5213 * { cat <<HERE; }; echo Ok
5214 * heredoc
5215 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005216 * HERE
5217 * but we don't support this.
5218 * We require heredoc to be in enclosing {}/(),
5219 * if any.
5220 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005221 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005222 goto parse_error;
5223 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005224 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005225 goto parse_error;
5226 }
5227 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005228 ctx.is_assignment = MAYBE_ASSIGNMENT;
5229 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005230 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005231 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005232 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005233 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005234 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005235#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005236 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005237 if (pstring)
5238 *pstring = ctx.as_string.data;
5239 else
5240 o_free_unsafe(&ctx.as_string);
5241#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005242 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5243 /* Example: bare "{ }", "()" */
5244 G.last_exitcode = 2; /* bash compat */
5245 syntax_error_unexpected_ch(ch);
5246 goto parse_error2;
5247 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005248 debug_printf_parse("parse_stream return %p: "
5249 "end_trigger char found\n",
5250 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005251 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005252 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005253 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005254 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005255 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005256 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005257 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005258
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005259 /* Catch <, > before deciding whether this word is
5260 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5261 switch (ch) {
5262 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005263 redir_fd = redirect_opt_num(&ctx.word);
5264 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005265 goto parse_error;
5266 }
5267 redir_style = REDIRECT_OVERWRITE;
5268 if (next == '>') {
5269 redir_style = REDIRECT_APPEND;
5270 ch = i_getch(input);
5271 nommu_addchr(&ctx.as_string, ch);
5272 }
5273#if 0
5274 else if (next == '(') {
5275 syntax_error(">(process) not supported");
5276 goto parse_error;
5277 }
5278#endif
5279 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5280 goto parse_error;
5281 continue; /* back to top of while (1) */
5282 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005283 redir_fd = redirect_opt_num(&ctx.word);
5284 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005285 goto parse_error;
5286 }
5287 redir_style = REDIRECT_INPUT;
5288 if (next == '<') {
5289 redir_style = REDIRECT_HEREDOC;
5290 heredoc_cnt++;
5291 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5292 ch = i_getch(input);
5293 nommu_addchr(&ctx.as_string, ch);
5294 } else if (next == '>') {
5295 redir_style = REDIRECT_IO;
5296 ch = i_getch(input);
5297 nommu_addchr(&ctx.as_string, ch);
5298 }
5299#if 0
5300 else if (next == '(') {
5301 syntax_error("<(process) not supported");
5302 goto parse_error;
5303 }
5304#endif
5305 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5306 goto parse_error;
5307 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005308 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005309 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005310 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005311 /* note: we do not add it to &ctx.as_string */
5312/* TODO: in bash:
5313 * comment inside $() goes to the next \n, even inside quoted string (!):
5314 * cmd "$(cmd2 #comment)" - syntax error
5315 * cmd "`cmd2 #comment`" - ok
5316 * We accept both (comment ends where command subst ends, in both cases).
5317 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005318 while (1) {
5319 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005320 if (ch == '\n') {
5321 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005322 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005323 }
5324 ch = i_getch(input);
5325 if (ch == EOF)
5326 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005327 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005328 continue; /* back to top of while (1) */
5329 }
5330 break;
Denys Vlasenko1c572692018-04-10 13:09:26 +02005331#if 0 /* looks like we never reach this code */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005332 case '\\':
5333 if (next == '\n') {
5334 /* It's "\<newline>" */
5335#if !BB_MMU
5336 /* Remove trailing '\' from ctx.as_string */
5337 ctx.as_string.data[--ctx.as_string.length] = '\0';
5338#endif
5339 ch = i_getch(input); /* eat it */
5340 continue; /* back to top of while (1) */
5341 }
5342 break;
Denys Vlasenko1c572692018-04-10 13:09:26 +02005343#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005344 }
5345
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005346 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005347 /* check that we are not in word in "a=1 2>word b=1": */
5348 && !ctx.pending_redirect
5349 ) {
5350 /* ch is a special char and thus this word
5351 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005352 ctx.is_assignment = NOT_ASSIGNMENT;
5353 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005354 }
5355
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005356 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5357
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005358 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005359 case SPECIAL_VAR_SYMBOL:
5360 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005361 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5362 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005363 /* fall through */
5364 case '#':
5365 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005366 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005367 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005368 case '\\':
5369 if (next == EOF) {
Denys Vlasenko1c572692018-04-10 13:09:26 +02005370//TODO: in ". FILE" containing "cmd\" (no newline) bash ignores last "\"
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005371 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005372 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005373 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005374 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005375 /* note: ch != '\n' (that case does not reach this place) */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005376 o_addchr(&ctx.word, '\\');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005377 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005378 o_addchr(&ctx.word, ch);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005379 nommu_addchr(&ctx.as_string, ch);
5380 /* Example: echo Hello \2>file
5381 * we need to know that word 2 is quoted */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005382 ctx.word.has_quoted_part = 1;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005383 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005384 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005385 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005386 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005387 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005388 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005389 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005390 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005391 case '\'':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005392 ctx.word.has_quoted_part = 1;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005393 if (next == '\'' && !ctx.pending_redirect)
5394 goto insert_empty_quoted_str_marker;
5395 while (1) {
5396 ch = i_getch(input);
5397 if (ch == EOF) {
5398 syntax_error_unterm_ch('\'');
5399 goto parse_error;
5400 }
5401 nommu_addchr(&ctx.as_string, ch);
5402 if (ch == '\'')
5403 break;
5404 if (ch == SPECIAL_VAR_SYMBOL) {
5405 /* Convert raw ^C to corresponding special variable reference */
5406 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5407 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5408 }
5409 o_addqchr(&ctx.word, ch);
5410 }
5411 continue; /* get next char */
5412 case '"':
5413 ctx.word.has_quoted_part = 1;
5414 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005415 insert_empty_quoted_str_marker:
5416 nommu_addchr(&ctx.as_string, next);
5417 i_getch(input); /* eat second ' */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005418 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5419 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005420 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005421 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005422 if (ctx.is_assignment == NOT_ASSIGNMENT)
5423 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5424 if (!encode_string(&ctx.as_string, &ctx.word, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005425 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005426 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005427 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005428#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005429 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005430 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005431
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005432 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5433 o_addchr(&ctx.word, '`');
5434 USE_FOR_NOMMU(pos = ctx.word.length;)
5435 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005436 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005437# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005438 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005439 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005440# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005441 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5442 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005443 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005444 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005445#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005446 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005447#if ENABLE_HUSH_CASE
5448 case_semi:
5449#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005450 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005451 goto parse_error;
5452 }
5453 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005454#if ENABLE_HUSH_CASE
5455 /* Eat multiple semicolons, detect
5456 * whether it means something special */
5457 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005458 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005459 if (ch != ';')
5460 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005461 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005462 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005463 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005464 ctx.ctx_dsemicolon = 1;
5465 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005466 break;
5467 }
5468 }
5469#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005470 new_cmd:
5471 /* We just finished a cmd. New one may start
5472 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005473 ctx.is_assignment = MAYBE_ASSIGNMENT;
5474 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005475 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005476 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005477 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005478 goto parse_error;
5479 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005480 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005481 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005482 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005483 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005484 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005485 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005486 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005487 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005488 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005489 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005490 goto parse_error;
5491 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005492#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005493 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005494 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005495#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005496 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005497 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005498 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005499 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005500 } else {
5501 /* we could pick up a file descriptor choice here
5502 * with redirect_opt_num(), but bash doesn't do it.
5503 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005504 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005505 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005506 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005507 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005508#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005509 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005510 if (ctx.ctx_res_w == RES_MATCH
5511 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005512 && ctx.word.length == 0 /* not word(... */
5513 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005514 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005515 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005516 }
5517#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005518 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005519 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005520 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005521 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005522 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005523 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005524#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005525 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005526 goto case_semi;
5527#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005528 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005529 /* proper use of this character is caught by end_trigger:
5530 * if we see {, we call parse_group(..., end_trigger='}')
5531 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005532 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005533 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005534 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005535 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005536 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005537 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005538 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005539 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005540
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005541 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005542 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005543 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005544 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005545 struct parse_context *pctx;
5546 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005547
5548 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005549 * Sample for finding leaks on syntax error recovery path.
5550 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005551 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005552 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005553 * while if (true | { true;}); then echo ok; fi; do break; done
5554 * 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 +00005555 */
5556 pctx = &ctx;
5557 do {
5558 /* Update pipe/command counts,
5559 * otherwise freeing may miss some */
5560 done_pipe(pctx, PIPE_SEQ);
5561 debug_printf_clean("freeing list %p from ctx %p\n",
5562 pctx->list_head, pctx);
5563 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005564 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005565 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005566#if !BB_MMU
5567 o_free_unsafe(&pctx->as_string);
5568#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005569 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005570 if (pctx != &ctx) {
5571 free(pctx);
5572 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005573 IF_HAS_KEYWORDS(pctx = p2;)
5574 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005575
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005576 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005577#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005578 if (pstring)
5579 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005580#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005581 debug_leave();
5582 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005583 }
Eric Andersen25f27032001-04-26 23:22:31 +00005584}
5585
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005586
5587/*** Execution routines ***/
5588
5589/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005590#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005591/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5592#define expand_string_to_string(str, do_unbackslash) \
5593 expand_string_to_string(str)
5594#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005595static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005596#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005597static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005598#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005599
5600/* expand_strvec_to_strvec() takes a list of strings, expands
5601 * all variable references within and returns a pointer to
5602 * a list of expanded strings, possibly with larger number
5603 * of strings. (Think VAR="a b"; echo $VAR).
5604 * This new list is allocated as a single malloc block.
5605 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005606 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005607 * Caller can deallocate entire list by single free(list). */
5608
Denys Vlasenko238081f2010-10-03 14:26:26 +02005609/* A horde of its helpers come first: */
5610
5611static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5612{
5613 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005614 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005615
Denys Vlasenko9e800222010-10-03 14:28:04 +02005616#if ENABLE_HUSH_BRACE_EXPANSION
5617 if (c == '{' || c == '}') {
5618 /* { -> \{, } -> \} */
5619 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005620 /* And now we want to add { or } and continue:
5621 * o_addchr(o, c);
5622 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005623 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005624 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005625 }
5626#endif
5627 o_addchr(o, c);
5628 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005629 /* \z -> \\\z; \<eol> -> \\<eol> */
5630 o_addchr(o, '\\');
5631 if (len) {
5632 len--;
5633 o_addchr(o, '\\');
5634 o_addchr(o, *str++);
5635 }
5636 }
5637 }
5638}
5639
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005640/* Store given string, finalizing the word and starting new one whenever
5641 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005642 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5643 * Return in *ended_with_ifs:
5644 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5645 */
5646static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005647{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005648 int last_is_ifs = 0;
5649
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005650 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005651 int word_len;
5652
5653 if (!*str) /* EOL - do not finalize word */
5654 break;
5655 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005656 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005657 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005658 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005659 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005660 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005661 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005662 * Example: "v='\*'; echo b$v" prints "b\*"
5663 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005664 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005665 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005666 /*/ Why can't we do it easier? */
5667 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5668 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5669 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005670 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005671 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005672 if (!*str) /* EOL - do not finalize word */
5673 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005674 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005675
5676 /* We know str here points to at least one IFS char */
5677 last_is_ifs = 1;
5678 str += strspn(str, G.ifs); /* skip IFS chars */
5679 if (!*str) /* EOL - do not finalize word */
5680 break;
5681
5682 /* Start new word... but not always! */
5683 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005684 if (output->has_quoted_part
5685 /* Case "v=' a'; echo $v":
5686 * here nothing precedes the space in $v expansion,
5687 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005688 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005689 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005690 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005691 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005692 o_addchr(output, '\0');
5693 debug_print_list("expand_on_ifs", output, n);
5694 n = o_save_ptr(output, n);
5695 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005696 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005697
5698 if (ended_with_ifs)
5699 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005700 debug_print_list("expand_on_ifs[1]", output, n);
5701 return n;
5702}
5703
5704/* Helper to expand $((...)) and heredoc body. These act as if
5705 * they are in double quotes, with the exception that they are not :).
5706 * Just the rules are similar: "expand only $var and `cmd`"
5707 *
5708 * Returns malloced string.
5709 * As an optimization, we return NULL if expansion is not needed.
5710 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005711#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005712/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5713#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5714 encode_then_expand_string(str)
5715#endif
5716static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005717{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005718#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005719 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005720#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005721 char *exp_str;
5722 struct in_str input;
5723 o_string dest = NULL_O_STRING;
5724
5725 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005726 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005727#if ENABLE_HUSH_TICK
5728 && !strchr(str, '`')
5729#endif
5730 ) {
5731 return NULL;
5732 }
5733
5734 /* We need to expand. Example:
5735 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5736 */
5737 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005738 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005739//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005740 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005741 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005742 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5743 o_free_unsafe(&dest);
5744 return exp_str;
5745}
5746
Denys Vlasenko0b883582016-12-23 16:49:07 +01005747#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005748static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005750 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005751 arith_t res;
5752 char *exp_str;
5753
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005754 math_state.lookupvar = get_local_var_value;
5755 math_state.setvar = set_local_var_from_halves;
5756 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005757 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005758 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005759 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005760 if (errmsg_p)
5761 *errmsg_p = math_state.errmsg;
5762 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005763 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764 return res;
5765}
5766#endif
5767
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005768#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005769/* ${var/[/]pattern[/repl]} helpers */
5770static char *strstr_pattern(char *val, const char *pattern, int *size)
5771{
5772 while (1) {
5773 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5774 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5775 if (end) {
5776 *size = end - val;
5777 return val;
5778 }
5779 if (*val == '\0')
5780 return NULL;
5781 /* Optimization: if "*pat" did not match the start of "string",
5782 * we know that "tring", "ring" etc will not match too:
5783 */
5784 if (pattern[0] == '*')
5785 return NULL;
5786 val++;
5787 }
5788}
5789static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5790{
5791 char *result = NULL;
5792 unsigned res_len = 0;
5793 unsigned repl_len = strlen(repl);
5794
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005795 /* Null pattern never matches, including if "var" is empty */
5796 if (!pattern[0])
5797 return result; /* NULL, no replaces happened */
5798
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005799 while (1) {
5800 int size;
5801 char *s = strstr_pattern(val, pattern, &size);
5802 if (!s)
5803 break;
5804
5805 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005806 strcpy(mempcpy(result + res_len, val, s - val), repl);
5807 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5809
5810 val = s + size;
5811 if (exp_op == '/')
5812 break;
5813 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005814 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005815 result = xrealloc(result, res_len + strlen(val) + 1);
5816 strcpy(result + res_len, val);
5817 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5818 }
5819 debug_printf_varexp("result:'%s'\n", result);
5820 return result;
5821}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005822#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005823
5824/* Helper:
5825 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5826 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005827static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005829 const char *val;
5830 char *to_be_freed;
5831 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005832 char *var;
5833 char first_char;
5834 char exp_op;
5835 char exp_save = exp_save; /* for compiler */
5836 char *exp_saveptr; /* points to expansion operator */
5837 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005838 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005839
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005840 val = NULL;
5841 to_be_freed = NULL;
5842 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005843 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005844 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005845 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005846 arg0 = arg[0];
5847 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005848 exp_op = 0;
5849
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005850 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5851 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5852 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5853 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005854 ) {
5855 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005856 var++;
5857 exp_op = 'L';
5858 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005859 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005860 if (exp_saveptr /* if 2nd char is one of expansion operators */
5861 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5862 ) {
5863 /* ${?:0}, ${#[:]%0} etc */
5864 exp_saveptr = var + 1;
5865 } else {
5866 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5867 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5868 }
5869 exp_op = exp_save = *exp_saveptr;
5870 if (exp_op) {
5871 exp_word = exp_saveptr + 1;
5872 if (exp_op == ':') {
5873 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005874//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005875 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005876 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005877 ) {
5878 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5879 exp_op = ':';
5880 exp_word--;
5881 }
5882 }
5883 *exp_saveptr = '\0';
5884 } /* else: it's not an expansion op, but bare ${var} */
5885 }
5886
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005887 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005888 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005889 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005890 int n = xatoi_positive(var);
5891 if (n < G.global_argc)
5892 val = G.global_argv[n];
5893 /* else val remains NULL: $N with too big N */
5894 } else {
5895 switch (var[0]) {
5896 case '$': /* pid */
5897 val = utoa(G.root_pid);
5898 break;
5899 case '!': /* bg pid */
5900 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5901 break;
5902 case '?': /* exitcode */
5903 val = utoa(G.last_exitcode);
5904 break;
5905 case '#': /* argc */
5906 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5907 break;
5908 default:
5909 val = get_local_var_value(var);
5910 }
5911 }
5912
5913 /* Handle any expansions */
5914 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005915 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005916 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005917 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005918 debug_printf_expand("%s\n", val);
5919 } else if (exp_op) {
5920 if (exp_op == '%' || exp_op == '#') {
5921 /* Standard-mandated substring removal ops:
5922 * ${parameter%word} - remove smallest suffix pattern
5923 * ${parameter%%word} - remove largest suffix pattern
5924 * ${parameter#word} - remove smallest prefix pattern
5925 * ${parameter##word} - remove largest prefix pattern
5926 *
5927 * Word is expanded to produce a glob pattern.
5928 * Then var's value is matched to it and matching part removed.
5929 */
5930 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005931 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005932 char *exp_exp_word;
5933 char *loc;
5934 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005935 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005936 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005937 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005938 /*
5939 * process_bkslash:1 unbackslash:1 breaks this:
5940 * a='a\\'; echo ${a%\\\\} # correct output is: a
5941 * process_bkslash:1 unbackslash:0 breaks this:
5942 * a='a}'; echo ${a%\}} # correct output is: a
5943 */
5944 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005945 if (exp_exp_word)
5946 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005947 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005948 /* HACK ALERT. We depend here on the fact that
5949 * G.global_argv and results of utoa and get_local_var_value
5950 * are actually in writable memory:
5951 * scan_and_match momentarily stores NULs there. */
5952 t = (char*)val;
5953 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005954 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 +02005955 free(exp_exp_word);
5956 if (loc) { /* match was found */
5957 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005958 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005959 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005960 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005961 }
5962 }
5963 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005964#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005965 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005966 /* It's ${var/[/]pattern[/repl]} thing.
5967 * Note that in encoded form it has TWO parts:
5968 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005969 * and if // is used, it is encoded as \:
5970 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005971 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005972 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005973 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005974 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005975 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02005976 * >az >bz
5977 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
5978 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
5979 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
5980 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005981 * (note that a*z _pattern_ is never globbed!)
5982 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005983 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005984 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005985 if (!pattern)
5986 pattern = xstrdup(exp_word);
5987 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5988 *p++ = SPECIAL_VAR_SYMBOL;
5989 exp_word = p;
5990 p = strchr(p, SPECIAL_VAR_SYMBOL);
5991 *p = '\0';
Denys Vlasenkode026252018-04-05 17:04:53 +02005992 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005993 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5994 /* HACK ALERT. We depend here on the fact that
5995 * G.global_argv and results of utoa and get_local_var_value
5996 * are actually in writable memory:
5997 * replace_pattern momentarily stores NULs there. */
5998 t = (char*)val;
5999 to_be_freed = replace_pattern(t,
6000 pattern,
6001 (repl ? repl : exp_word),
6002 exp_op);
6003 if (to_be_freed) /* at least one replace happened */
6004 val = to_be_freed;
6005 free(pattern);
6006 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006007 } else {
6008 /* Empty variable always gives nothing */
6009 // "v=''; echo ${v/*/w}" prints "", not "w"
6010 /* Just skip "replace" part */
6011 *p++ = SPECIAL_VAR_SYMBOL;
6012 p = strchr(p, SPECIAL_VAR_SYMBOL);
6013 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006014 }
6015 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006016#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006018#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006019 /* It's ${var:N[:M]} bashism.
6020 * Note that in encoded form it has TWO parts:
6021 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6022 */
6023 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006024 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006025
Denys Vlasenko063847d2010-09-15 13:33:02 +02006026 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6027 if (errmsg)
6028 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006029 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6030 *p++ = SPECIAL_VAR_SYMBOL;
6031 exp_word = p;
6032 p = strchr(p, SPECIAL_VAR_SYMBOL);
6033 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006034 len = expand_and_evaluate_arith(exp_word, &errmsg);
6035 if (errmsg)
6036 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006037 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006038 if (beg < 0) {
6039 /* negative beg counts from the end */
6040 beg = (arith_t)strlen(val) + beg;
6041 if (beg < 0) /* ${v: -999999} is "" */
6042 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006043 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006044 debug_printf_varexp("from val:'%s'\n", val);
6045 if (len < 0) {
6046 /* in bash, len=-n means strlen()-n */
6047 len = (arith_t)strlen(val) - beg + len;
6048 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006049 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006050 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006051 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006052 arith_err:
6053 val = NULL;
6054 } else {
6055 /* Paranoia. What if user entered 9999999999999
6056 * which fits in arith_t but not int? */
6057 if (len >= INT_MAX)
6058 len = INT_MAX;
6059 val = to_be_freed = xstrndup(val + beg, len);
6060 }
6061 debug_printf_varexp("val:'%s'\n", val);
6062#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006063 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006064 val = NULL;
6065#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006066 } else { /* one of "-=+?" */
6067 /* Standard-mandated substitution ops:
6068 * ${var?word} - indicate error if unset
6069 * If var is unset, word (or a message indicating it is unset
6070 * if word is null) is written to standard error
6071 * and the shell exits with a non-zero exit status.
6072 * Otherwise, the value of var is substituted.
6073 * ${var-word} - use default value
6074 * If var is unset, word is substituted.
6075 * ${var=word} - assign and use default value
6076 * If var is unset, word is assigned to var.
6077 * In all cases, final value of var is substituted.
6078 * ${var+word} - use alternative value
6079 * If var is unset, null is substituted.
6080 * Otherwise, word is substituted.
6081 *
6082 * Word is subjected to tilde expansion, parameter expansion,
6083 * command substitution, and arithmetic expansion.
6084 * If word is not needed, it is not expanded.
6085 *
6086 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6087 * but also treat null var as if it is unset.
6088 */
6089 int use_word = (!val || ((exp_save == ':') && !val[0]));
6090 if (exp_op == '+')
6091 use_word = !use_word;
6092 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6093 (exp_save == ':') ? "true" : "false", use_word);
6094 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006095 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006096 if (to_be_freed)
6097 exp_word = to_be_freed;
6098 if (exp_op == '?') {
6099 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006100 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006101 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006102 exp_word[0]
6103 ? exp_word
6104 : "parameter null or not set"
6105 /* ash has more specific messages, a-la: */
6106 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006107 );
6108//TODO: how interactive bash aborts expansion mid-command?
6109 } else {
6110 val = exp_word;
6111 }
6112
6113 if (exp_op == '=') {
6114 /* ${var=[word]} or ${var:=[word]} */
6115 if (isdigit(var[0]) || var[0] == '#') {
6116 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006117 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006118 val = NULL;
6119 } else {
6120 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006121 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006122 }
6123 }
6124 }
6125 } /* one of "-=+?" */
6126
6127 *exp_saveptr = exp_save;
6128 } /* if (exp_op) */
6129
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006130 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006131
6132 *pp = p;
6133 *to_be_freed_pp = to_be_freed;
6134 return val;
6135}
6136
6137/* Expand all variable references in given string, adding words to list[]
6138 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6139 * to be filled). This routine is extremely tricky: has to deal with
6140 * variables/parameters with whitespace, $* and $@, and constructs like
6141 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006142static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006143{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006144 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006145 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006146 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006147 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006148 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006149 char *p;
6150
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006151 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6152 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153 debug_print_list("expand_vars_to_list", output, n);
6154 n = o_save_ptr(output, n);
6155 debug_print_list("expand_vars_to_list[0]", output, n);
6156
6157 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6158 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159 char *to_be_freed = NULL;
6160 const char *val = NULL;
6161#if ENABLE_HUSH_TICK
6162 o_string subst_result = NULL_O_STRING;
6163#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006164#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006165 char arith_buf[sizeof(arith_t)*3 + 2];
6166#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006167
6168 if (ended_in_ifs) {
6169 o_addchr(output, '\0');
6170 n = o_save_ptr(output, n);
6171 ended_in_ifs = 0;
6172 }
6173
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006174 o_addblock(output, arg, p - arg);
6175 debug_print_list("expand_vars_to_list[1]", output, n);
6176 arg = ++p;
6177 p = strchr(p, SPECIAL_VAR_SYMBOL);
6178
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006179 /* Fetch special var name (if it is indeed one of them)
6180 * and quote bit, force the bit on if singleword expansion -
6181 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006182 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006183
6184 /* Is this variable quoted and thus expansion can't be null?
6185 * "$@" is special. Even if quoted, it can still
6186 * expand to nothing (not even an empty string),
6187 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006188 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006189 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006190
6191 switch (first_ch & 0x7f) {
6192 /* Highest bit in first_ch indicates that var is double-quoted */
6193 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006194 case '@': {
6195 int i;
6196 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006198 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006199 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006200 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006201 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006202 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006203 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6204 if (G.global_argv[i++][0] && G.global_argv[i]) {
6205 /* this argv[] is not empty and not last:
6206 * put terminating NUL, start new word */
6207 o_addchr(output, '\0');
6208 debug_print_list("expand_vars_to_list[2]", output, n);
6209 n = o_save_ptr(output, n);
6210 debug_print_list("expand_vars_to_list[3]", output, n);
6211 }
6212 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006213 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006214 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006215 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006216 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006217 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006218 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006219 while (1) {
6220 o_addQstr(output, G.global_argv[i]);
6221 if (++i >= G.global_argc)
6222 break;
6223 o_addchr(output, '\0');
6224 debug_print_list("expand_vars_to_list[4]", output, n);
6225 n = o_save_ptr(output, n);
6226 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006227 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006228 while (1) {
6229 o_addQstr(output, G.global_argv[i]);
6230 if (!G.global_argv[++i])
6231 break;
6232 if (G.ifs[0])
6233 o_addchr(output, G.ifs[0]);
6234 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006235 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006236 }
6237 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006238 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006239 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6240 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006241 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006242 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006243 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006244 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006245 case SPECIAL_VAR_QUOTED_SVS:
6246 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6247 arg++;
6248 val = SPECIAL_VAR_SYMBOL_STR;
6249 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006250#if ENABLE_HUSH_TICK
6251 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006252 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006253 arg++;
6254 /* Can't just stuff it into output o_string,
6255 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006256 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006257 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6258 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006259 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006260 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6261 val = subst_result.data;
6262 goto store_val;
6263#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006264#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006265 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6266 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267
6268 arg++; /* skip '+' */
6269 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6270 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006271 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006272 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6273 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006274 val = arith_buf;
6275 break;
6276 }
6277#endif
6278 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006279 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006280 IF_HUSH_TICK(store_val:)
6281 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006282 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6283 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006285 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006286 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006287 }
6288 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006289 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006290 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6291 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006292 }
6293 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6295
6296 if (val && val[0]) {
6297 o_addQstr(output, val);
6298 }
6299 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006300
6301 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6302 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006303 if (*p != SPECIAL_VAR_SYMBOL)
6304 *p = SPECIAL_VAR_SYMBOL;
6305
6306#if ENABLE_HUSH_TICK
6307 o_free(&subst_result);
6308#endif
6309 arg = ++p;
6310 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6311
6312 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006313 if (ended_in_ifs) {
6314 o_addchr(output, '\0');
6315 n = o_save_ptr(output, n);
6316 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006317 debug_print_list("expand_vars_to_list[a]", output, n);
6318 /* this part is literal, and it was already pre-quoted
6319 * if needed (much earlier), do not use o_addQstr here! */
6320 o_addstr_with_NUL(output, arg);
6321 debug_print_list("expand_vars_to_list[b]", output, n);
6322 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006323 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 ) {
6325 n--;
6326 /* allow to reuse list[n] later without re-growth */
6327 output->has_empty_slot = 1;
6328 } else {
6329 o_addchr(output, '\0');
6330 }
6331
6332 return n;
6333}
6334
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006335static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006336{
6337 int n;
6338 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006339 o_string output = NULL_O_STRING;
6340
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006341 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006342
6343 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006344 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006345 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006346 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006347 }
6348 debug_print_list("expand_variables", &output, n);
6349
6350 /* output.data (malloced in one block) gets returned in "list" */
6351 list = o_finalize_list(&output, n);
6352 debug_print_strings("expand_variables[1]", list);
6353 return list;
6354}
6355
6356static char **expand_strvec_to_strvec(char **argv)
6357{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006358 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006359}
6360
Denys Vlasenko11752d42018-04-03 08:20:58 +02006361#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006362static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6363{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006364 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006365}
6366#endif
6367
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006368/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006369 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006370 *
6371 * NB: should NOT do globbing!
6372 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6373 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006374static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006376#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006377 const int do_unbackslash = 1;
6378#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006379 char *argv[2], **list;
6380
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006381 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006382 /* This is generally an optimization, but it also
6383 * handles "", which otherwise trips over !list[0] check below.
6384 * (is this ever happens that we actually get str="" here?)
6385 */
6386 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6387 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006388 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006389 return xstrdup(str);
6390 }
6391
6392 argv[0] = (char*)str;
6393 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006394 list = expand_variables(argv, do_unbackslash
6395 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6396 : EXP_FLAG_SINGLEWORD
6397 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006398 if (HUSH_DEBUG)
6399 if (!list[0] || list[1])
6400 bb_error_msg_and_die("BUG in varexp2");
6401 /* actually, just move string 2*sizeof(char*) bytes back */
6402 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006403 if (do_unbackslash)
6404 unbackslash((char*)list);
6405 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006406 return (char*)list;
6407}
6408
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006409#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006410static char* expand_strvec_to_string(char **argv)
6411{
6412 char **list;
6413
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006414 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006415 /* Convert all NULs to spaces */
6416 if (list[0]) {
6417 int n = 1;
6418 while (list[n]) {
6419 if (HUSH_DEBUG)
6420 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6421 bb_error_msg_and_die("BUG in varexp3");
6422 /* bash uses ' ' regardless of $IFS contents */
6423 list[n][-1] = ' ';
6424 n++;
6425 }
6426 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006427 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006428 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6429 return (char*)list;
6430}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006431#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006432
6433static char **expand_assignments(char **argv, int count)
6434{
6435 int i;
6436 char **p;
6437
6438 G.expanded_assignments = p = NULL;
6439 /* Expand assignments into one string each */
6440 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006441 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006442 }
6443 G.expanded_assignments = NULL;
6444 return p;
6445}
6446
6447
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006448static void switch_off_special_sigs(unsigned mask)
6449{
6450 unsigned sig = 0;
6451 while ((mask >>= 1) != 0) {
6452 sig++;
6453 if (!(mask & 1))
6454 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006455#if ENABLE_HUSH_TRAP
6456 if (G_traps) {
6457 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006458 /* trap is '', has to remain SIG_IGN */
6459 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006460 free(G_traps[sig]);
6461 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006462 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006463#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006464 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006465 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006466 }
6467}
6468
Denys Vlasenkob347df92011-08-09 22:49:15 +02006469#if BB_MMU
6470/* never called */
6471void re_execute_shell(char ***to_free, const char *s,
6472 char *g_argv0, char **g_argv,
6473 char **builtin_argv) NORETURN;
6474
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475static void reset_traps_to_defaults(void)
6476{
6477 /* This function is always called in a child shell
6478 * after fork (not vfork, NOMMU doesn't use this function).
6479 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006480 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006481 unsigned mask;
6482
6483 /* Child shells are not interactive.
6484 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6485 * Testcase: (while :; do :; done) + ^Z should background.
6486 * Same goes for SIGTERM, SIGHUP, SIGINT.
6487 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006488 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006489 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006490 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006491
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006492 /* Switch off special sigs */
6493 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006494# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006495 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006496# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006497 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006498 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6499 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006500
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006501# if ENABLE_HUSH_TRAP
6502 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006503 return;
6504
6505 /* Reset all sigs to default except ones with empty traps */
6506 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006507 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006508 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006509 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006510 continue; /* empty trap: has to remain SIG_IGN */
6511 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006512 free(G_traps[sig]);
6513 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006514 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006515 if (sig == 0)
6516 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006517 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006518 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006519# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006520}
6521
6522#else /* !BB_MMU */
6523
6524static void re_execute_shell(char ***to_free, const char *s,
6525 char *g_argv0, char **g_argv,
6526 char **builtin_argv) NORETURN;
6527static void re_execute_shell(char ***to_free, const char *s,
6528 char *g_argv0, char **g_argv,
6529 char **builtin_argv)
6530{
6531# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6532 /* delims + 2 * (number of bytes in printed hex numbers) */
6533 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6534 char *heredoc_argv[4];
6535 struct variable *cur;
6536# if ENABLE_HUSH_FUNCTIONS
6537 struct function *funcp;
6538# endif
6539 char **argv, **pp;
6540 unsigned cnt;
6541 unsigned long long empty_trap_mask;
6542
6543 if (!g_argv0) { /* heredoc */
6544 argv = heredoc_argv;
6545 argv[0] = (char *) G.argv0_for_re_execing;
6546 argv[1] = (char *) "-<";
6547 argv[2] = (char *) s;
6548 argv[3] = NULL;
6549 pp = &argv[3]; /* used as pointer to empty environment */
6550 goto do_exec;
6551 }
6552
6553 cnt = 0;
6554 pp = builtin_argv;
6555 if (pp) while (*pp++)
6556 cnt++;
6557
6558 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006559 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006560 int sig;
6561 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006562 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006563 empty_trap_mask |= 1LL << sig;
6564 }
6565 }
6566
6567 sprintf(param_buf, NOMMU_HACK_FMT
6568 , (unsigned) G.root_pid
6569 , (unsigned) G.root_ppid
6570 , (unsigned) G.last_bg_pid
6571 , (unsigned) G.last_exitcode
6572 , cnt
6573 , empty_trap_mask
6574 IF_HUSH_LOOPS(, G.depth_of_loop)
6575 );
6576# undef NOMMU_HACK_FMT
6577 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6578 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6579 */
6580 cnt += 6;
6581 for (cur = G.top_var; cur; cur = cur->next) {
6582 if (!cur->flg_export || cur->flg_read_only)
6583 cnt += 2;
6584 }
6585# if ENABLE_HUSH_FUNCTIONS
6586 for (funcp = G.top_func; funcp; funcp = funcp->next)
6587 cnt += 3;
6588# endif
6589 pp = g_argv;
6590 while (*pp++)
6591 cnt++;
6592 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6593 *pp++ = (char *) G.argv0_for_re_execing;
6594 *pp++ = param_buf;
6595 for (cur = G.top_var; cur; cur = cur->next) {
6596 if (strcmp(cur->varstr, hush_version_str) == 0)
6597 continue;
6598 if (cur->flg_read_only) {
6599 *pp++ = (char *) "-R";
6600 *pp++ = cur->varstr;
6601 } else if (!cur->flg_export) {
6602 *pp++ = (char *) "-V";
6603 *pp++ = cur->varstr;
6604 }
6605 }
6606# if ENABLE_HUSH_FUNCTIONS
6607 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6608 *pp++ = (char *) "-F";
6609 *pp++ = funcp->name;
6610 *pp++ = funcp->body_as_string;
6611 }
6612# endif
6613 /* We can pass activated traps here. Say, -Tnn:trap_string
6614 *
6615 * However, POSIX says that subshells reset signals with traps
6616 * to SIG_DFL.
6617 * I tested bash-3.2 and it not only does that with true subshells
6618 * of the form ( list ), but with any forked children shells.
6619 * I set trap "echo W" WINCH; and then tried:
6620 *
6621 * { echo 1; sleep 20; echo 2; } &
6622 * while true; do echo 1; sleep 20; echo 2; break; done &
6623 * true | { echo 1; sleep 20; echo 2; } | cat
6624 *
6625 * In all these cases sending SIGWINCH to the child shell
6626 * did not run the trap. If I add trap "echo V" WINCH;
6627 * _inside_ group (just before echo 1), it works.
6628 *
6629 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006630 */
6631 *pp++ = (char *) "-c";
6632 *pp++ = (char *) s;
6633 if (builtin_argv) {
6634 while (*++builtin_argv)
6635 *pp++ = *builtin_argv;
6636 *pp++ = (char *) "";
6637 }
6638 *pp++ = g_argv0;
6639 while (*g_argv)
6640 *pp++ = *g_argv++;
6641 /* *pp = NULL; - is already there */
6642 pp = environ;
6643
6644 do_exec:
6645 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006646 /* Don't propagate SIG_IGN to the child */
6647 if (SPECIAL_JOBSTOP_SIGS != 0)
6648 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649 execve(bb_busybox_exec_path, argv, pp);
6650 /* Fallback. Useful for init=/bin/hush usage etc */
6651 if (argv[0][0] == '/')
6652 execve(argv[0], argv, pp);
6653 xfunc_error_retval = 127;
6654 bb_error_msg_and_die("can't re-execute the shell");
6655}
6656#endif /* !BB_MMU */
6657
6658
6659static int run_and_free_list(struct pipe *pi);
6660
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006661/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006662 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6663 * end_trigger controls how often we stop parsing
6664 * NUL: parse all, execute, return
6665 * ';': parse till ';' or newline, execute, repeat till EOF
6666 */
6667static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006668{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006669 /* Why we need empty flag?
6670 * An obscure corner case "false; ``; echo $?":
6671 * empty command in `` should still set $? to 0.
6672 * But we can't just set $? to 0 at the start,
6673 * this breaks "false; echo `echo $?`" case.
6674 */
6675 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006676 while (1) {
6677 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006678
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006679#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02006680 if (end_trigger == ';') {
6681 G.promptmode = 0; /* PS1 */
6682 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
6683 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006684#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006685 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006686 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6687 /* If we are in "big" script
6688 * (not in `cmd` or something similar)...
6689 */
6690 if (pipe_list == ERR_PTR && end_trigger == ';') {
6691 /* Discard cached input (rest of line) */
6692 int ch = inp->last_char;
6693 while (ch != EOF && ch != '\n') {
6694 //bb_error_msg("Discarded:'%c'", ch);
6695 ch = i_getch(inp);
6696 }
6697 /* Force prompt */
6698 inp->p = NULL;
6699 /* This stream isn't empty */
6700 empty = 0;
6701 continue;
6702 }
6703 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006704 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006705 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006706 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006707 debug_print_tree(pipe_list, 0);
6708 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6709 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006710 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006711 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006712 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006713 }
Eric Andersen25f27032001-04-26 23:22:31 +00006714}
6715
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006716static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006717{
6718 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006719 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6720
Eric Andersen25f27032001-04-26 23:22:31 +00006721 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006722 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006723 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006724}
6725
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006726static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006727{
Eric Andersen25f27032001-04-26 23:22:31 +00006728 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006729 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006730
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006731 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006732 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006733 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006734 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006735}
6736
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006737#if ENABLE_HUSH_TICK
6738static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6739{
6740 pid_t pid;
6741 int channel[2];
6742# if !BB_MMU
6743 char **to_free = NULL;
6744# endif
6745
6746 xpipe(channel);
6747 pid = BB_MMU ? xfork() : xvfork();
6748 if (pid == 0) { /* child */
6749 disable_restore_tty_pgrp_on_exit();
6750 /* Process substitution is not considered to be usual
6751 * 'command execution'.
6752 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6753 */
6754 bb_signals(0
6755 + (1 << SIGTSTP)
6756 + (1 << SIGTTIN)
6757 + (1 << SIGTTOU)
6758 , SIG_IGN);
6759 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6760 close(channel[0]); /* NB: close _first_, then move fd! */
6761 xmove_fd(channel[1], 1);
6762 /* Prevent it from trying to handle ctrl-z etc */
6763 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006764# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006765 /* Awful hack for `trap` or $(trap).
6766 *
6767 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6768 * contains an example where "trap" is executed in a subshell:
6769 *
6770 * save_traps=$(trap)
6771 * ...
6772 * eval "$save_traps"
6773 *
6774 * Standard does not say that "trap" in subshell shall print
6775 * parent shell's traps. It only says that its output
6776 * must have suitable form, but then, in the above example
6777 * (which is not supposed to be normative), it implies that.
6778 *
6779 * bash (and probably other shell) does implement it
6780 * (traps are reset to defaults, but "trap" still shows them),
6781 * but as a result, "trap" logic is hopelessly messed up:
6782 *
6783 * # trap
6784 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6785 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6786 * # true | trap <--- trap is in subshell - no output (ditto)
6787 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6788 * trap -- 'echo Ho' SIGWINCH
6789 * # echo `(trap)` <--- in subshell in subshell - output
6790 * trap -- 'echo Ho' SIGWINCH
6791 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6792 * trap -- 'echo Ho' SIGWINCH
6793 *
6794 * The rules when to forget and when to not forget traps
6795 * get really complex and nonsensical.
6796 *
6797 * Our solution: ONLY bare $(trap) or `trap` is special.
6798 */
6799 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006800 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006801 && skip_whitespace(s + 4)[0] == '\0'
6802 ) {
6803 static const char *const argv[] = { NULL, NULL };
6804 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006805 fflush_all(); /* important */
6806 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006807 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006808# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809# if BB_MMU
6810 reset_traps_to_defaults();
6811 parse_and_run_string(s);
6812 _exit(G.last_exitcode);
6813# else
6814 /* We re-execute after vfork on NOMMU. This makes this script safe:
6815 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6816 * huge=`cat BIG` # was blocking here forever
6817 * echo OK
6818 */
6819 re_execute_shell(&to_free,
6820 s,
6821 G.global_argv[0],
6822 G.global_argv + 1,
6823 NULL);
6824# endif
6825 }
6826
6827 /* parent */
6828 *pid_p = pid;
6829# if ENABLE_HUSH_FAST
6830 G.count_SIGCHLD++;
6831//bb_error_msg("[%d] fork in generate_stream_from_string:"
6832// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6833// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6834# endif
6835 enable_restore_tty_pgrp_on_exit();
6836# if !BB_MMU
6837 free(to_free);
6838# endif
6839 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006840 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006841}
6842
6843/* Return code is exit status of the process that is run. */
6844static int process_command_subs(o_string *dest, const char *s)
6845{
6846 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847 pid_t pid;
6848 int status, ch, eol_cnt;
6849
6850 fp = generate_stream_from_string(s, &pid);
6851
6852 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006853 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006854 while ((ch = getc(fp)) != EOF) {
6855 if (ch == '\0')
6856 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006857 if (ch == '\n') {
6858 eol_cnt++;
6859 continue;
6860 }
6861 while (eol_cnt) {
6862 o_addchr(dest, '\n');
6863 eol_cnt--;
6864 }
6865 o_addQchr(dest, ch);
6866 }
6867
6868 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006869 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006870 /* We need to extract exitcode. Test case
6871 * "true; echo `sleep 1; false` $?"
6872 * should print 1 */
6873 safe_waitpid(pid, &status, 0);
6874 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6875 return WEXITSTATUS(status);
6876}
6877#endif /* ENABLE_HUSH_TICK */
6878
6879
6880static void setup_heredoc(struct redir_struct *redir)
6881{
6882 struct fd_pair pair;
6883 pid_t pid;
6884 int len, written;
6885 /* the _body_ of heredoc (misleading field name) */
6886 const char *heredoc = redir->rd_filename;
6887 char *expanded;
6888#if !BB_MMU
6889 char **to_free;
6890#endif
6891
6892 expanded = NULL;
6893 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006894 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006895 if (expanded)
6896 heredoc = expanded;
6897 }
6898 len = strlen(heredoc);
6899
6900 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6901 xpiped_pair(pair);
6902 xmove_fd(pair.rd, redir->rd_fd);
6903
6904 /* Try writing without forking. Newer kernels have
6905 * dynamically growing pipes. Must use non-blocking write! */
6906 ndelay_on(pair.wr);
6907 while (1) {
6908 written = write(pair.wr, heredoc, len);
6909 if (written <= 0)
6910 break;
6911 len -= written;
6912 if (len == 0) {
6913 close(pair.wr);
6914 free(expanded);
6915 return;
6916 }
6917 heredoc += written;
6918 }
6919 ndelay_off(pair.wr);
6920
6921 /* Okay, pipe buffer was not big enough */
6922 /* Note: we must not create a stray child (bastard? :)
6923 * for the unsuspecting parent process. Child creates a grandchild
6924 * and exits before parent execs the process which consumes heredoc
6925 * (that exec happens after we return from this function) */
6926#if !BB_MMU
6927 to_free = NULL;
6928#endif
6929 pid = xvfork();
6930 if (pid == 0) {
6931 /* child */
6932 disable_restore_tty_pgrp_on_exit();
6933 pid = BB_MMU ? xfork() : xvfork();
6934 if (pid != 0)
6935 _exit(0);
6936 /* grandchild */
6937 close(redir->rd_fd); /* read side of the pipe */
6938#if BB_MMU
6939 full_write(pair.wr, heredoc, len); /* may loop or block */
6940 _exit(0);
6941#else
6942 /* Delegate blocking writes to another process */
6943 xmove_fd(pair.wr, STDOUT_FILENO);
6944 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6945#endif
6946 }
6947 /* parent */
6948#if ENABLE_HUSH_FAST
6949 G.count_SIGCHLD++;
6950//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6951#endif
6952 enable_restore_tty_pgrp_on_exit();
6953#if !BB_MMU
6954 free(to_free);
6955#endif
6956 close(pair.wr);
6957 free(expanded);
6958 wait(NULL); /* wait till child has died */
6959}
6960
Denys Vlasenko2db74612017-07-07 22:07:28 +02006961struct squirrel {
6962 int orig_fd;
6963 int moved_to;
6964 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6965 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6966};
6967
Denys Vlasenko621fc502017-07-24 12:42:17 +02006968static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6969{
6970 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6971 sq[i].orig_fd = orig;
6972 sq[i].moved_to = moved;
6973 sq[i+1].orig_fd = -1; /* end marker */
6974 return sq;
6975}
6976
Denys Vlasenko2db74612017-07-07 22:07:28 +02006977static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6978{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006979 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006980 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006981
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006982 i = 0;
6983 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006984 /* If we collide with an already moved fd... */
6985 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006986 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006987 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6988 if (sq[i].moved_to < 0) /* what? */
6989 xfunc_die();
6990 return sq;
6991 }
6992 if (fd == sq[i].orig_fd) {
6993 /* Example: echo Hello >/dev/null 1>&2 */
6994 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6995 return sq;
6996 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006997 }
6998
Denys Vlasenko2db74612017-07-07 22:07:28 +02006999 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007000 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007001 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7002 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007003 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007004 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007005}
7006
Denys Vlasenko657e9002017-07-30 23:34:04 +02007007static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7008{
7009 int i;
7010
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007011 i = 0;
7012 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007013 /* If we collide with an already moved fd... */
7014 if (fd == sq[i].orig_fd) {
7015 /* Examples:
7016 * "echo 3>FILE 3>&- 3>FILE"
7017 * "echo 3>&- 3>FILE"
7018 * No need for last redirect to insert
7019 * another "need to close 3" indicator.
7020 */
7021 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7022 return sq;
7023 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007024 }
7025
7026 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7027 return append_squirrel(sq, i, fd, -1);
7028}
7029
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007030/* fd: redirect wants this fd to be used (e.g. 3>file).
7031 * Move all conflicting internally used fds,
7032 * and remember them so that we can restore them later.
7033 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007034static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007035{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007036 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7037 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007038
7039#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007040 if (fd == G.interactive_fd) {
7041 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007042 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007043 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7044 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007045 }
7046#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007047 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7048 * (1) Redirect in a forked child. No need to save FILEs' fds,
7049 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007050 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7051 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007052 * "fileno(fd) = new_fd" can't be done.
7053 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007054 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007055 return 0;
7056
Denys Vlasenko2db74612017-07-07 22:07:28 +02007057 /* If this one of script's fds? */
7058 if (save_FILEs_on_redirect(fd, avoid_fd))
7059 return 1; /* yes. "we closed fd" */
7060
7061 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7062 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7063 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007064}
7065
Denys Vlasenko2db74612017-07-07 22:07:28 +02007066static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007067{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007068 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007069 int i;
7070 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007071 if (sq[i].moved_to >= 0) {
7072 /* We simply die on error */
7073 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7074 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7075 } else {
7076 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7077 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7078 close(sq[i].orig_fd);
7079 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007080 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007081 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007082 }
7083
Denys Vlasenko2db74612017-07-07 22:07:28 +02007084 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007085
7086 restore_redirected_FILEs();
7087}
7088
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007089#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007090static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007091{
7092 if (G_interactive_fd)
7093 close(G_interactive_fd);
7094 close_all_FILE_list();
7095}
7096#endif
7097
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007098static int internally_opened_fd(int fd, struct squirrel *sq)
7099{
7100 int i;
7101
7102#if ENABLE_HUSH_INTERACTIVE
7103 if (fd == G.interactive_fd)
7104 return 1;
7105#endif
7106 /* If this one of script's fds? */
7107 if (fd_in_FILEs(fd))
7108 return 1;
7109
7110 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7111 if (fd == sq[i].moved_to)
7112 return 1;
7113 }
7114 return 0;
7115}
7116
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007117/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7118 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007119static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007120{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007121 struct redir_struct *redir;
7122
7123 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007124 int newfd;
7125 int closed;
7126
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007127 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007128 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007129 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007130 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7131 * of the heredoc */
7132 debug_printf_parse("set heredoc '%s'\n",
7133 redir->rd_filename);
7134 setup_heredoc(redir);
7135 continue;
7136 }
7137
7138 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007139 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007140 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007141 int mode;
7142
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007143 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007144 /*
7145 * Examples:
7146 * "cmd >" (no filename)
7147 * "cmd > <file" (2nd redirect starts too early)
7148 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007149 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007150 continue;
7151 }
7152 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007153 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007154 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007155 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007156 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007157 /* Error message from open_or_warn can be lost
7158 * if stderr has been redirected, but bash
7159 * and ash both lose it as well
7160 * (though zsh doesn't!)
7161 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007162 return 1;
7163 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007164 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007165 /* open() gave us precisely the fd we wanted.
7166 * This means that this fd was not busy
7167 * (not opened to anywhere).
7168 * Remember to close it on restore:
7169 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007170 *sqp = add_squirrel_closed(*sqp, newfd);
7171 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007172 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007173 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007174 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7175 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007176 }
7177
Denys Vlasenko657e9002017-07-30 23:34:04 +02007178 if (newfd == redir->rd_fd)
7179 continue;
7180
7181 /* if "N>FILE": move newfd to redir->rd_fd */
7182 /* if "N>&M": dup newfd to redir->rd_fd */
7183 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7184
7185 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7186 if (newfd == REDIRFD_CLOSE) {
7187 /* "N>&-" means "close me" */
7188 if (!closed) {
7189 /* ^^^ optimization: saving may already
7190 * have closed it. If not... */
7191 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007192 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007193 /* Sometimes we do another close on restore, getting EBADF.
7194 * Consider "echo 3>FILE 3>&-"
7195 * first redirect remembers "need to close 3",
7196 * and second redirect closes 3! Restore code then closes 3 again.
7197 */
7198 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007199 /* if newfd is a script fd or saved fd, simulate EBADF */
7200 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7201 //errno = EBADF;
7202 //bb_perror_msg_and_die("can't duplicate file descriptor");
7203 newfd = -1; /* same effect as code above */
7204 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007205 xdup2(newfd, redir->rd_fd);
7206 if (redir->rd_dup == REDIRFD_TO_FILE)
7207 /* "rd_fd > FILE" */
7208 close(newfd);
7209 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007210 }
7211 }
7212 return 0;
7213}
7214
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007215static char *find_in_path(const char *arg)
7216{
7217 char *ret = NULL;
7218 const char *PATH = get_local_var_value("PATH");
7219
7220 if (!PATH)
7221 return NULL;
7222
7223 while (1) {
7224 const char *end = strchrnul(PATH, ':');
7225 int sz = end - PATH; /* must be int! */
7226
7227 free(ret);
7228 if (sz != 0) {
7229 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7230 } else {
7231 /* We have xxx::yyyy in $PATH,
7232 * it means "use current dir" */
7233 ret = xstrdup(arg);
7234 }
7235 if (access(ret, F_OK) == 0)
7236 break;
7237
7238 if (*end == '\0') {
7239 free(ret);
7240 return NULL;
7241 }
7242 PATH = end + 1;
7243 }
7244
7245 return ret;
7246}
7247
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007248static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007249 const struct built_in_command *x,
7250 const struct built_in_command *end)
7251{
7252 while (x != end) {
7253 if (strcmp(name, x->b_cmd) != 0) {
7254 x++;
7255 continue;
7256 }
7257 debug_printf_exec("found builtin '%s'\n", name);
7258 return x;
7259 }
7260 return NULL;
7261}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007262static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007263{
7264 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7265}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007266static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007267{
7268 const struct built_in_command *x = find_builtin1(name);
7269 if (x)
7270 return x;
7271 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7272}
7273
7274#if ENABLE_HUSH_FUNCTIONS
7275static struct function **find_function_slot(const char *name)
7276{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007277 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007278 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007279
7280 while ((funcp = *funcpp) != NULL) {
7281 if (strcmp(name, funcp->name) == 0) {
7282 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007283 break;
7284 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007285 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007286 }
7287 return funcpp;
7288}
7289
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007290static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007291{
7292 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007293 return funcp;
7294}
7295
7296/* Note: takes ownership on name ptr */
7297static struct function *new_function(char *name)
7298{
7299 struct function **funcpp = find_function_slot(name);
7300 struct function *funcp = *funcpp;
7301
7302 if (funcp != NULL) {
7303 struct command *cmd = funcp->parent_cmd;
7304 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7305 if (!cmd) {
7306 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7307 free(funcp->name);
7308 /* Note: if !funcp->body, do not free body_as_string!
7309 * This is a special case of "-F name body" function:
7310 * body_as_string was not malloced! */
7311 if (funcp->body) {
7312 free_pipe_list(funcp->body);
7313# if !BB_MMU
7314 free(funcp->body_as_string);
7315# endif
7316 }
7317 } else {
7318 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7319 cmd->argv[0] = funcp->name;
7320 cmd->group = funcp->body;
7321# if !BB_MMU
7322 cmd->group_as_string = funcp->body_as_string;
7323# endif
7324 }
7325 } else {
7326 debug_printf_exec("remembering new function '%s'\n", name);
7327 funcp = *funcpp = xzalloc(sizeof(*funcp));
7328 /*funcp->next = NULL;*/
7329 }
7330
7331 funcp->name = name;
7332 return funcp;
7333}
7334
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007335# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007336static void unset_func(const char *name)
7337{
7338 struct function **funcpp = find_function_slot(name);
7339 struct function *funcp = *funcpp;
7340
7341 if (funcp != NULL) {
7342 debug_printf_exec("freeing function '%s'\n", funcp->name);
7343 *funcpp = funcp->next;
7344 /* funcp is unlinked now, deleting it.
7345 * Note: if !funcp->body, the function was created by
7346 * "-F name body", do not free ->body_as_string
7347 * and ->name as they were not malloced. */
7348 if (funcp->body) {
7349 free_pipe_list(funcp->body);
7350 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007351# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007352 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007353# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007354 }
7355 free(funcp);
7356 }
7357}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007358# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007359
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007360static void remove_nested_vars(void)
7361{
7362 struct variable *cur;
7363 struct variable **cur_pp;
7364
7365 cur_pp = &G.top_var;
7366 while ((cur = *cur_pp) != NULL) {
7367 if (cur->var_nest_level <= G.var_nest_level) {
7368 cur_pp = &cur->next;
7369 continue;
7370 }
7371 /* Unexport */
7372 if (cur->flg_export) {
7373 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7374 bb_unsetenv(cur->varstr);
7375 }
7376 /* Remove from global list */
7377 *cur_pp = cur->next;
7378 /* Free */
7379 if (!cur->max_len) {
7380 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7381 free(cur->varstr);
7382 }
7383 free(cur);
7384 }
7385}
7386
7387static void enter_var_nest_level(void)
7388{
7389 G.var_nest_level++;
7390 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7391
7392 /* Try: f() { echo -n .; f; }; f
7393 * struct variable::var_nest_level is uint16_t,
7394 * thus limiting recursion to < 2^16.
7395 * In any case, with 8 Mbyte stack SEGV happens
7396 * not too long after 2^16 recursions anyway.
7397 */
7398 if (G.var_nest_level > 0xff00)
7399 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7400}
7401
7402static void leave_var_nest_level(void)
7403{
7404 G.var_nest_level--;
7405 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7406 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7407 bb_error_msg_and_die("BUG: nesting underflow");
7408
7409 remove_nested_vars();
7410}
7411
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007412# if BB_MMU
7413#define exec_function(to_free, funcp, argv) \
7414 exec_function(funcp, argv)
7415# endif
7416static void exec_function(char ***to_free,
7417 const struct function *funcp,
7418 char **argv) NORETURN;
7419static void exec_function(char ***to_free,
7420 const struct function *funcp,
7421 char **argv)
7422{
7423# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007424 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007425
7426 argv[0] = G.global_argv[0];
7427 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007428 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007429
7430// Example when we are here: "cmd | func"
7431// func will run with saved-redirect fds open.
7432// $ f() { echo /proc/self/fd/*; }
7433// $ true | f
7434// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7435// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7436// Same in script:
7437// $ . ./SCRIPT
7438// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7439// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7440// They are CLOEXEC so external programs won't see them, but
7441// for "more correctness" we might want to close those extra fds here:
7442//? close_saved_fds_and_FILE_fds();
7443
Denys Vlasenko332e4112018-04-04 22:32:59 +02007444 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007445 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007446 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007447 IF_HUSH_LOCAL(G.func_nest_level++;)
7448
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007449 /* On MMU, funcp->body is always non-NULL */
7450 n = run_list(funcp->body);
7451 fflush_all();
7452 _exit(n);
7453# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007454//? close_saved_fds_and_FILE_fds();
7455
7456//TODO: check whether "true | func_with_return" works
7457
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007458 re_execute_shell(to_free,
7459 funcp->body_as_string,
7460 G.global_argv[0],
7461 argv + 1,
7462 NULL);
7463# endif
7464}
7465
7466static int run_function(const struct function *funcp, char **argv)
7467{
7468 int rc;
7469 save_arg_t sv;
7470 smallint sv_flg;
7471
7472 save_and_replace_G_args(&sv, argv);
7473
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007474 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007475 sv_flg = G_flag_return_in_progress;
7476 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007477
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007478 /* Make "local" variables properly shadow previous ones */
7479 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007480 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007481
7482 /* On MMU, funcp->body is always non-NULL */
7483# if !BB_MMU
7484 if (!funcp->body) {
7485 /* Function defined by -F */
7486 parse_and_run_string(funcp->body_as_string);
7487 rc = G.last_exitcode;
7488 } else
7489# endif
7490 {
7491 rc = run_list(funcp->body);
7492 }
7493
Denys Vlasenko332e4112018-04-04 22:32:59 +02007494 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007495 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007496
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007497 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007498
7499 restore_G_args(&sv, argv);
7500
7501 return rc;
7502}
7503#endif /* ENABLE_HUSH_FUNCTIONS */
7504
7505
7506#if BB_MMU
7507#define exec_builtin(to_free, x, argv) \
7508 exec_builtin(x, argv)
7509#else
7510#define exec_builtin(to_free, x, argv) \
7511 exec_builtin(to_free, argv)
7512#endif
7513static void exec_builtin(char ***to_free,
7514 const struct built_in_command *x,
7515 char **argv) NORETURN;
7516static void exec_builtin(char ***to_free,
7517 const struct built_in_command *x,
7518 char **argv)
7519{
7520#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007521 int rcode;
7522 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007523//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007524 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007525 fflush_all();
7526 _exit(rcode);
7527#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007528 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007529 /* On NOMMU, we must never block!
7530 * Example: { sleep 99 | read line; } & echo Ok
7531 */
7532 re_execute_shell(to_free,
7533 argv[0],
7534 G.global_argv[0],
7535 G.global_argv + 1,
7536 argv);
7537#endif
7538}
7539
7540
7541static void execvp_or_die(char **argv) NORETURN;
7542static void execvp_or_die(char **argv)
7543{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007544 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007545 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007546 /* Don't propagate SIG_IGN to the child */
7547 if (SPECIAL_JOBSTOP_SIGS != 0)
7548 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007549 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007550 e = 2;
7551 if (errno == EACCES) e = 126;
7552 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007553 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007554 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007555}
7556
7557#if ENABLE_HUSH_MODE_X
7558static void dump_cmd_in_x_mode(char **argv)
7559{
7560 if (G_x_mode && argv) {
7561 /* We want to output the line in one write op */
7562 char *buf, *p;
7563 int len;
7564 int n;
7565
7566 len = 3;
7567 n = 0;
7568 while (argv[n])
7569 len += strlen(argv[n++]) + 1;
7570 buf = xmalloc(len);
7571 buf[0] = '+';
7572 p = buf + 1;
7573 n = 0;
7574 while (argv[n])
7575 p += sprintf(p, " %s", argv[n++]);
7576 *p++ = '\n';
7577 *p = '\0';
7578 fputs(buf, stderr);
7579 free(buf);
7580 }
7581}
7582#else
7583# define dump_cmd_in_x_mode(argv) ((void)0)
7584#endif
7585
Denys Vlasenko57000292018-01-12 14:41:45 +01007586#if ENABLE_HUSH_COMMAND
7587static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7588{
7589 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007590
Denys Vlasenko57000292018-01-12 14:41:45 +01007591 if (!opt_vV)
7592 return;
7593
7594 to_free = NULL;
7595 if (!explanation) {
7596 char *path = getenv("PATH");
7597 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007598 if (!explanation)
7599 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007600 if (opt_vV != 'V')
7601 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7602 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007603 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007604 free(to_free);
7605 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007606 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007607}
7608#else
7609# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7610#endif
7611
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007612#if BB_MMU
7613#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7614 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7615#define pseudo_exec(nommu_save, command, argv_expanded) \
7616 pseudo_exec(command, argv_expanded)
7617#endif
7618
7619/* Called after [v]fork() in run_pipe, or from builtin_exec.
7620 * Never returns.
7621 * Don't exit() here. If you don't exec, use _exit instead.
7622 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007623 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007624 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007625static void pseudo_exec_argv(nommu_save_t *nommu_save,
7626 char **argv, int assignment_cnt,
7627 char **argv_expanded) NORETURN;
7628static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7629 char **argv, int assignment_cnt,
7630 char **argv_expanded)
7631{
Denys Vlasenko57000292018-01-12 14:41:45 +01007632 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007633 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007634 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007635 IF_HUSH_COMMAND(char opt_vV = 0;)
7636 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007637
7638 new_env = expand_assignments(argv, assignment_cnt);
7639 dump_cmd_in_x_mode(new_env);
7640
7641 if (!argv[assignment_cnt]) {
7642 /* Case when we are here: ... | var=val | ...
7643 * (note that we do not exit early, i.e., do not optimize out
7644 * expand_assignments(): think about ... | var=`sleep 1` | ...
7645 */
7646 free_strings(new_env);
7647 _exit(EXIT_SUCCESS);
7648 }
7649
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007650 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007651#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007652 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007653#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007654 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007655 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007656#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007657 set_vars_and_save_old(new_env);
7658 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007659
7660 if (argv_expanded) {
7661 argv = argv_expanded;
7662 } else {
7663 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7664#if !BB_MMU
7665 nommu_save->argv = argv;
7666#endif
7667 }
7668 dump_cmd_in_x_mode(argv);
7669
7670#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7671 if (strchr(argv[0], '/') != NULL)
7672 goto skip;
7673#endif
7674
Denys Vlasenko75481d32017-07-31 05:27:09 +02007675#if ENABLE_HUSH_FUNCTIONS
7676 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007677 funcp = find_function(argv[0]);
7678 if (funcp)
7679 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007680#endif
7681
Denys Vlasenko57000292018-01-12 14:41:45 +01007682#if ENABLE_HUSH_COMMAND
7683 /* "command BAR": run BAR without looking it up among functions
7684 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7685 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7686 */
7687 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7688 char *p;
7689
7690 argv++;
7691 p = *argv;
7692 if (p[0] != '-' || !p[1])
7693 continue; /* bash allows "command command command [-OPT] BAR" */
7694
7695 for (;;) {
7696 p++;
7697 switch (*p) {
7698 case '\0':
7699 argv++;
7700 p = *argv;
7701 if (p[0] != '-' || !p[1])
7702 goto after_opts;
7703 continue; /* next arg is also -opts, process it too */
7704 case 'v':
7705 case 'V':
7706 opt_vV = *p;
7707 continue;
7708 default:
7709 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7710 }
7711 }
7712 }
7713 after_opts:
7714# if ENABLE_HUSH_FUNCTIONS
7715 if (opt_vV && find_function(argv[0]))
7716 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7717# endif
7718#endif
7719
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007720 /* Check if the command matches any of the builtins.
7721 * Depending on context, this might be redundant. But it's
7722 * easier to waste a few CPU cycles than it is to figure out
7723 * if this is one of those cases.
7724 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007725 /* Why "BB_MMU ? :" difference in logic? -
7726 * On NOMMU, it is more expensive to re-execute shell
7727 * just in order to run echo or test builtin.
7728 * It's better to skip it here and run corresponding
7729 * non-builtin later. */
7730 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7731 if (x) {
7732 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7733 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007734 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007735
7736#if ENABLE_FEATURE_SH_STANDALONE
7737 /* Check if the command matches any busybox applets */
7738 {
7739 int a = find_applet_by_name(argv[0]);
7740 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007741 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742# if BB_MMU /* see above why on NOMMU it is not allowed */
7743 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007744 /* Do not leak open fds from opened script files etc.
7745 * Testcase: interactive "ls -l /proc/self/fd"
7746 * should not show tty fd open.
7747 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007748 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007749//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007750//This casuses test failures in
7751//redir_children_should_not_see_saved_fd_2.tests
7752//redir_children_should_not_see_saved_fd_3.tests
7753//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007754 /* Without this, "rm -i FILE" can't be ^C'ed: */
7755 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007756 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007757 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007758 }
7759# endif
7760 /* Re-exec ourselves */
7761 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007762 /* Don't propagate SIG_IGN to the child */
7763 if (SPECIAL_JOBSTOP_SIGS != 0)
7764 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007765 execv(bb_busybox_exec_path, argv);
7766 /* If they called chroot or otherwise made the binary no longer
7767 * executable, fall through */
7768 }
7769 }
7770#endif
7771
7772#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7773 skip:
7774#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007775 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007776 execvp_or_die(argv);
7777}
7778
7779/* Called after [v]fork() in run_pipe
7780 */
7781static void pseudo_exec(nommu_save_t *nommu_save,
7782 struct command *command,
7783 char **argv_expanded) NORETURN;
7784static void pseudo_exec(nommu_save_t *nommu_save,
7785 struct command *command,
7786 char **argv_expanded)
7787{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007788#if ENABLE_HUSH_FUNCTIONS
7789 if (command->cmd_type == CMD_FUNCDEF) {
7790 /* Ignore funcdefs in pipes:
7791 * true | f() { cmd }
7792 */
7793 _exit(0);
7794 }
7795#endif
7796
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007797 if (command->argv) {
7798 pseudo_exec_argv(nommu_save, command->argv,
7799 command->assignment_cnt, argv_expanded);
7800 }
7801
7802 if (command->group) {
7803 /* Cases when we are here:
7804 * ( list )
7805 * { list } &
7806 * ... | ( list ) | ...
7807 * ... | { list } | ...
7808 */
7809#if BB_MMU
7810 int rcode;
7811 debug_printf_exec("pseudo_exec: run_list\n");
7812 reset_traps_to_defaults();
7813 rcode = run_list(command->group);
7814 /* OK to leak memory by not calling free_pipe_list,
7815 * since this process is about to exit */
7816 _exit(rcode);
7817#else
7818 re_execute_shell(&nommu_save->argv_from_re_execing,
7819 command->group_as_string,
7820 G.global_argv[0],
7821 G.global_argv + 1,
7822 NULL);
7823#endif
7824 }
7825
7826 /* Case when we are here: ... | >file */
7827 debug_printf_exec("pseudo_exec'ed null command\n");
7828 _exit(EXIT_SUCCESS);
7829}
7830
7831#if ENABLE_HUSH_JOB
7832static const char *get_cmdtext(struct pipe *pi)
7833{
7834 char **argv;
7835 char *p;
7836 int len;
7837
7838 /* This is subtle. ->cmdtext is created only on first backgrounding.
7839 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7840 * On subsequent bg argv is trashed, but we won't use it */
7841 if (pi->cmdtext)
7842 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007843
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007844 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007845 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007846 pi->cmdtext = xzalloc(1);
7847 return pi->cmdtext;
7848 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007849 len = 0;
7850 do {
7851 len += strlen(*argv) + 1;
7852 } while (*++argv);
7853 p = xmalloc(len);
7854 pi->cmdtext = p;
7855 argv = pi->cmds[0].argv;
7856 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007857 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007858 *p++ = ' ';
7859 } while (*++argv);
7860 p[-1] = '\0';
7861 return pi->cmdtext;
7862}
7863
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007864static void remove_job_from_table(struct pipe *pi)
7865{
7866 struct pipe *prev_pipe;
7867
7868 if (pi == G.job_list) {
7869 G.job_list = pi->next;
7870 } else {
7871 prev_pipe = G.job_list;
7872 while (prev_pipe->next != pi)
7873 prev_pipe = prev_pipe->next;
7874 prev_pipe->next = pi->next;
7875 }
7876 G.last_jobid = 0;
7877 if (G.job_list)
7878 G.last_jobid = G.job_list->jobid;
7879}
7880
7881static void delete_finished_job(struct pipe *pi)
7882{
7883 remove_job_from_table(pi);
7884 free_pipe(pi);
7885}
7886
7887static void clean_up_last_dead_job(void)
7888{
7889 if (G.job_list && !G.job_list->alive_cmds)
7890 delete_finished_job(G.job_list);
7891}
7892
Denys Vlasenko16096292017-07-10 10:00:28 +02007893static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007894{
7895 struct pipe *job, **jobp;
7896 int i;
7897
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007898 clean_up_last_dead_job();
7899
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007900 /* Find the end of the list, and find next job ID to use */
7901 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007902 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007903 while ((job = *jobp) != NULL) {
7904 if (job->jobid > i)
7905 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007906 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007907 }
7908 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007909
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007910 /* Create a new job struct at the end */
7911 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007912 job->next = NULL;
7913 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7914 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7915 for (i = 0; i < pi->num_cmds; i++) {
7916 job->cmds[i].pid = pi->cmds[i].pid;
7917 /* all other fields are not used and stay zero */
7918 }
7919 job->cmdtext = xstrdup(get_cmdtext(pi));
7920
7921 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007922 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007923 G.last_jobid = job->jobid;
7924}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007925#endif /* JOB */
7926
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007927static int job_exited_or_stopped(struct pipe *pi)
7928{
7929 int rcode, i;
7930
7931 if (pi->alive_cmds != pi->stopped_cmds)
7932 return -1;
7933
7934 /* All processes in fg pipe have exited or stopped */
7935 rcode = 0;
7936 i = pi->num_cmds;
7937 while (--i >= 0) {
7938 rcode = pi->cmds[i].cmd_exitcode;
7939 /* usually last process gives overall exitstatus,
7940 * but with "set -o pipefail", last *failed* process does */
7941 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7942 break;
7943 }
7944 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7945 return rcode;
7946}
7947
Denys Vlasenko7e675362016-10-28 21:57:31 +02007948static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007949{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007950#if ENABLE_HUSH_JOB
7951 struct pipe *pi;
7952#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007953 int i, dead;
7954
7955 dead = WIFEXITED(status) || WIFSIGNALED(status);
7956
7957#if DEBUG_JOBS
7958 if (WIFSTOPPED(status))
7959 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7960 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7961 if (WIFSIGNALED(status))
7962 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7963 childpid, WTERMSIG(status), WEXITSTATUS(status));
7964 if (WIFEXITED(status))
7965 debug_printf_jobs("pid %d exited, exitcode %d\n",
7966 childpid, WEXITSTATUS(status));
7967#endif
7968 /* Were we asked to wait for a fg pipe? */
7969 if (fg_pipe) {
7970 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007971
Denys Vlasenko7e675362016-10-28 21:57:31 +02007972 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007973 int rcode;
7974
Denys Vlasenko7e675362016-10-28 21:57:31 +02007975 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7976 if (fg_pipe->cmds[i].pid != childpid)
7977 continue;
7978 if (dead) {
7979 int ex;
7980 fg_pipe->cmds[i].pid = 0;
7981 fg_pipe->alive_cmds--;
7982 ex = WEXITSTATUS(status);
7983 /* bash prints killer signal's name for *last*
7984 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7985 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7986 */
7987 if (WIFSIGNALED(status)) {
7988 int sig = WTERMSIG(status);
7989 if (i == fg_pipe->num_cmds-1)
7990 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7991 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7992 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7993 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7994 * Maybe we need to use sig | 128? */
7995 ex = sig + 128;
7996 }
7997 fg_pipe->cmds[i].cmd_exitcode = ex;
7998 } else {
7999 fg_pipe->stopped_cmds++;
8000 }
8001 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8002 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008003 rcode = job_exited_or_stopped(fg_pipe);
8004 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008005/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8006 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8007 * and "killall -STOP cat" */
8008 if (G_interactive_fd) {
8009#if ENABLE_HUSH_JOB
8010 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008011 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008012#endif
8013 return rcode;
8014 }
8015 if (fg_pipe->alive_cmds == 0)
8016 return rcode;
8017 }
8018 /* There are still running processes in the fg_pipe */
8019 return -1;
8020 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008021 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008022 }
8023
8024#if ENABLE_HUSH_JOB
8025 /* We were asked to wait for bg or orphaned children */
8026 /* No need to remember exitcode in this case */
8027 for (pi = G.job_list; pi; pi = pi->next) {
8028 for (i = 0; i < pi->num_cmds; i++) {
8029 if (pi->cmds[i].pid == childpid)
8030 goto found_pi_and_prognum;
8031 }
8032 }
8033 /* Happens when shell is used as init process (init=/bin/sh) */
8034 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8035 return -1; /* this wasn't a process from fg_pipe */
8036
8037 found_pi_and_prognum:
8038 if (dead) {
8039 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008040 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008041 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008042 rcode = 128 + WTERMSIG(status);
8043 pi->cmds[i].cmd_exitcode = rcode;
8044 if (G.last_bg_pid == pi->cmds[i].pid)
8045 G.last_bg_pid_exitcode = rcode;
8046 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008047 pi->alive_cmds--;
8048 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008049 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008050 printf(JOB_STATUS_FORMAT, pi->jobid,
8051 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008052 delete_finished_job(pi);
8053 } else {
8054/*
8055 * bash deletes finished jobs from job table only in interactive mode,
8056 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8057 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8058 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8059 * We only retain one "dead" job, if it's the single job on the list.
8060 * This covers most of real-world scenarios where this is useful.
8061 */
8062 if (pi != G.job_list)
8063 delete_finished_job(pi);
8064 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008065 }
8066 } else {
8067 /* child stopped */
8068 pi->stopped_cmds++;
8069 }
8070#endif
8071 return -1; /* this wasn't a process from fg_pipe */
8072}
8073
8074/* Check to see if any processes have exited -- if they have,
8075 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008076 *
8077 * If non-NULL fg_pipe: wait for its completion or stop.
8078 * Return its exitcode or zero if stopped.
8079 *
8080 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8081 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8082 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8083 * or 0 if no children changed status.
8084 *
8085 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8086 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8087 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008088 */
8089static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8090{
8091 int attributes;
8092 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008093 int rcode = 0;
8094
8095 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8096
8097 attributes = WUNTRACED;
8098 if (fg_pipe == NULL)
8099 attributes |= WNOHANG;
8100
8101 errno = 0;
8102#if ENABLE_HUSH_FAST
8103 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8104//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8105//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8106 /* There was neither fork nor SIGCHLD since last waitpid */
8107 /* Avoid doing waitpid syscall if possible */
8108 if (!G.we_have_children) {
8109 errno = ECHILD;
8110 return -1;
8111 }
8112 if (fg_pipe == NULL) { /* is WNOHANG set? */
8113 /* We have children, but they did not exit
8114 * or stop yet (we saw no SIGCHLD) */
8115 return 0;
8116 }
8117 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8118 }
8119#endif
8120
8121/* Do we do this right?
8122 * bash-3.00# sleep 20 | false
8123 * <ctrl-Z pressed>
8124 * [3]+ Stopped sleep 20 | false
8125 * bash-3.00# echo $?
8126 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8127 * [hush 1.14.0: yes we do it right]
8128 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008129 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008130 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008131#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008132 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008133 i = G.count_SIGCHLD;
8134#endif
8135 childpid = waitpid(-1, &status, attributes);
8136 if (childpid <= 0) {
8137 if (childpid && errno != ECHILD)
8138 bb_perror_msg("waitpid");
8139#if ENABLE_HUSH_FAST
8140 else { /* Until next SIGCHLD, waitpid's are useless */
8141 G.we_have_children = (childpid == 0);
8142 G.handled_SIGCHLD = i;
8143//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8144 }
8145#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008146 /* ECHILD (no children), or 0 (no change in children status) */
8147 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008148 break;
8149 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008150 rcode = process_wait_result(fg_pipe, childpid, status);
8151 if (rcode >= 0) {
8152 /* fg_pipe exited or stopped */
8153 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008154 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008155 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008156 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008157 rcode = WEXITSTATUS(status);
8158 if (WIFSIGNALED(status))
8159 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008160 if (WIFSTOPPED(status))
8161 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8162 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008163 rcode++;
8164 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008165 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008166 /* This wasn't one of our processes, or */
8167 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008168 } /* while (waitpid succeeds)... */
8169
8170 return rcode;
8171}
8172
8173#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008174static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008175{
8176 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008177 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008178 if (G_saved_tty_pgrp) {
8179 /* Job finished, move the shell to the foreground */
8180 p = getpgrp(); /* our process group id */
8181 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8182 tcsetpgrp(G_interactive_fd, p);
8183 }
8184 return rcode;
8185}
8186#endif
8187
8188/* Start all the jobs, but don't wait for anything to finish.
8189 * See checkjobs().
8190 *
8191 * Return code is normally -1, when the caller has to wait for children
8192 * to finish to determine the exit status of the pipe. If the pipe
8193 * is a simple builtin command, however, the action is done by the
8194 * time run_pipe returns, and the exit code is provided as the
8195 * return value.
8196 *
8197 * Returns -1 only if started some children. IOW: we have to
8198 * mask out retvals of builtins etc with 0xff!
8199 *
8200 * The only case when we do not need to [v]fork is when the pipe
8201 * is single, non-backgrounded, non-subshell command. Examples:
8202 * cmd ; ... { list } ; ...
8203 * cmd && ... { list } && ...
8204 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008205 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008206 * or (if SH_STANDALONE) an applet, and we can run the { list }
8207 * with run_list. If it isn't one of these, we fork and exec cmd.
8208 *
8209 * Cases when we must fork:
8210 * non-single: cmd | cmd
8211 * backgrounded: cmd & { list } &
8212 * subshell: ( list ) [&]
8213 */
8214#if !ENABLE_HUSH_MODE_X
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008215#define redirect_and_varexp_helper(old_vars_p, command, squirrel, argv_expanded) \
8216 redirect_and_varexp_helper(old_vars_p, command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008217#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008218static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008219 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008220 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008221 char **argv_expanded)
8222{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008223 /* Assignments occur before redirects. Try:
8224 * a=`sleep 1` sleep 2 3>/qwe/rty
8225 */
8226
8227 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8228 dump_cmd_in_x_mode(new_env);
8229 dump_cmd_in_x_mode(argv_expanded);
8230 /* this takes ownership of new_env[i] elements, and frees new_env: */
8231 set_vars_and_save_old(new_env);
8232
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008233 /* setup_redirects acts on file descriptors, not FILEs.
8234 * This is perfect for work that comes after exec().
8235 * Is it really safe for inline use? Experimentally,
8236 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008237 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008238}
8239static NOINLINE int run_pipe(struct pipe *pi)
8240{
8241 static const char *const null_ptr = NULL;
8242
8243 int cmd_no;
8244 int next_infd;
8245 struct command *command;
8246 char **argv_expanded;
8247 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008248 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008249 int rcode;
8250
8251 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8252 debug_enter();
8253
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008254 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8255 * Result should be 3 lines: q w e, qwe, q w e
8256 */
8257 G.ifs = get_local_var_value("IFS");
8258 if (!G.ifs)
8259 G.ifs = defifs;
8260
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008261 IF_HUSH_JOB(pi->pgrp = -1;)
8262 pi->stopped_cmds = 0;
8263 command = &pi->cmds[0];
8264 argv_expanded = NULL;
8265
8266 if (pi->num_cmds != 1
8267 || pi->followup == PIPE_BG
8268 || command->cmd_type == CMD_SUBSHELL
8269 ) {
8270 goto must_fork;
8271 }
8272
8273 pi->alive_cmds = 1;
8274
8275 debug_printf_exec(": group:%p argv:'%s'\n",
8276 command->group, command->argv ? command->argv[0] : "NONE");
8277
8278 if (command->group) {
8279#if ENABLE_HUSH_FUNCTIONS
8280 if (command->cmd_type == CMD_FUNCDEF) {
8281 /* "executing" func () { list } */
8282 struct function *funcp;
8283
8284 funcp = new_function(command->argv[0]);
8285 /* funcp->name is already set to argv[0] */
8286 funcp->body = command->group;
8287# if !BB_MMU
8288 funcp->body_as_string = command->group_as_string;
8289 command->group_as_string = NULL;
8290# endif
8291 command->group = NULL;
8292 command->argv[0] = NULL;
8293 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8294 funcp->parent_cmd = command;
8295 command->child_func = funcp;
8296
8297 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8298 debug_leave();
8299 return EXIT_SUCCESS;
8300 }
8301#endif
8302 /* { list } */
8303 debug_printf("non-subshell group\n");
8304 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008305 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008306 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008307//FIXME: we need to pass squirrel down into run_list()
8308//for SH_STANDALONE case, or else this construct:
8309// { find /proc/self/fd; true; } >FILE; cmd2
8310//has no way of closing saved fd#1 for "find",
8311//and in SH_STANDALONE mode, "find" is not execed,
8312//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008313 rcode = run_list(command->group) & 0xff;
8314 }
8315 restore_redirects(squirrel);
8316 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8317 debug_leave();
8318 debug_printf_exec("run_pipe: return %d\n", rcode);
8319 return rcode;
8320 }
8321
8322 argv = command->argv ? command->argv : (char **) &null_ptr;
8323 {
8324 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008325 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8326 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008327 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008328 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008329
Denys Vlasenko5807e182018-02-08 19:19:04 +01008330#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008331 if (G.lineno_var)
8332 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8333#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008334
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008335 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008336 /* Assignments, but no command.
8337 * Ensure redirects take effect (that is, create files).
8338 * Try "a=t >file"
8339 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008340 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008341 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008342 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008343 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008344 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008345
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008346 /* Set shell variables */
8347 if (G_x_mode)
8348 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008349 i = 0;
8350 while (i < command->assignment_cnt) {
8351 char *p = expand_string_to_string(argv[i], /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008352 if (G_x_mode)
8353 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008354 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008355 if (set_local_var(p, /*flag:*/ 0)) {
8356 /* assignment to readonly var / putenv error? */
8357 rcode = 1;
8358 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008359 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008360 }
8361 if (G_x_mode)
8362 bb_putchar_stderr('\n');
8363 /* Redirect error sets $? to 1. Otherwise,
8364 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008365 * Else, clear $?:
8366 * false; q=`exit 2`; echo $? - should print 2
8367 * false; x=1; echo $? - should print 0
8368 * Because of the 2nd case, we can't just use G.last_exitcode.
8369 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008370 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008371 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008372 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8373 debug_leave();
8374 debug_printf_exec("run_pipe: return %d\n", rcode);
8375 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008376 }
8377
8378 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008379#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008380 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008381 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008382 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008383#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008384 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008385
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008386 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008387 if (!argv_expanded[0]) {
8388 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008389 /* `false` still has to set exitcode 1 */
8390 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008391 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008392 }
8393
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008394 old_vars = NULL;
8395 sv_shadowed = G.shadowed_vars_pp;
8396
Denys Vlasenko75481d32017-07-31 05:27:09 +02008397 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008398 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8399 IF_HUSH_FUNCTIONS(x = NULL;)
8400 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008401 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008402 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008403 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8404 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008405 /*
8406 * Variable assignments are executed, but then "forgotten":
8407 * a=`sleep 1;echo A` exec 3>&-; echo $a
8408 * sleeps, but prints nothing.
8409 */
8410 enter_var_nest_level();
8411 G.shadowed_vars_pp = &old_vars;
8412 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8413 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008414 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008415
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008416 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008417 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008418
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008419 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008420 * a=b true; env | grep ^a=
8421 */
8422 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008423 /* Collect all variables "shadowed" by helper
8424 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8425 * into old_vars list:
8426 */
8427 G.shadowed_vars_pp = &old_vars;
8428 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008429 if (rcode == 0) {
8430 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008431 /* Do not collect *to old_vars list* vars shadowed
8432 * by e.g. "local VAR" builtin (collect them
8433 * in the previously nested list instead):
8434 * don't want them to be restored immediately
8435 * after "local" completes.
8436 */
8437 G.shadowed_vars_pp = sv_shadowed;
8438
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008439 debug_printf_exec(": builtin '%s' '%s'...\n",
8440 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008441 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008442 rcode = x->b_function(argv_expanded) & 0xff;
8443 fflush_all();
8444 }
8445#if ENABLE_HUSH_FUNCTIONS
8446 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008447 debug_printf_exec(": function '%s' '%s'...\n",
8448 funcp->name, argv_expanded[1]);
8449 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008450 /*
8451 * But do collect *to old_vars list* vars shadowed
8452 * within function execution. To that end, restore
8453 * this pointer _after_ function run:
8454 */
8455 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008456 }
8457#endif
8458 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008459 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008460 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008461 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008462 if (n < 0 || !APPLET_IS_NOFORK(n))
8463 goto must_fork;
8464
8465 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008466 /* Collect all variables "shadowed" by helper into old_vars list */
8467 G.shadowed_vars_pp = &old_vars;
8468 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8469 G.shadowed_vars_pp = sv_shadowed;
8470
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008471 if (rcode == 0) {
8472 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8473 argv_expanded[0], argv_expanded[1]);
8474 /*
8475 * Note: signals (^C) can't interrupt here.
8476 * We remember them and they will be acted upon
8477 * after applet returns.
8478 * This makes applets which can run for a long time
8479 * and/or wait for user input ineligible for NOFORK:
8480 * for example, "yes" or "rm" (rm -i waits for input).
8481 */
8482 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008483 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008484 } else
8485 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008486
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008487 restore_redirects(squirrel);
8488 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008489 leave_var_nest_level();
8490 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008491
8492 /*
8493 * Try "usleep 99999999" + ^C + "echo $?"
8494 * with FEATURE_SH_NOFORK=y.
8495 */
8496 if (!funcp) {
8497 /* It was builtin or nofork.
8498 * if this would be a real fork/execed program,
8499 * it should have died if a fatal sig was received.
8500 * But OTOH, there was no separate process,
8501 * the sig was sent to _shell_, not to non-existing
8502 * child.
8503 * Let's just handle ^C only, this one is obvious:
8504 * we aren't ok with exitcode 0 when ^C was pressed
8505 * during builtin/nofork.
8506 */
8507 if (sigismember(&G.pending_set, SIGINT))
8508 rcode = 128 + SIGINT;
8509 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008510 free(argv_expanded);
8511 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8512 debug_leave();
8513 debug_printf_exec("run_pipe return %d\n", rcode);
8514 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008515 }
8516
8517 must_fork:
8518 /* NB: argv_expanded may already be created, and that
8519 * might include `cmd` runs! Do not rerun it! We *must*
8520 * use argv_expanded if it's non-NULL */
8521
8522 /* Going to fork a child per each pipe member */
8523 pi->alive_cmds = 0;
8524 next_infd = 0;
8525
8526 cmd_no = 0;
8527 while (cmd_no < pi->num_cmds) {
8528 struct fd_pair pipefds;
8529#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008530 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008531 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008532 nommu_save.old_vars = NULL;
8533 nommu_save.argv = NULL;
8534 nommu_save.argv_from_re_execing = NULL;
8535#endif
8536 command = &pi->cmds[cmd_no];
8537 cmd_no++;
8538 if (command->argv) {
8539 debug_printf_exec(": pipe member '%s' '%s'...\n",
8540 command->argv[0], command->argv[1]);
8541 } else {
8542 debug_printf_exec(": pipe member with no argv\n");
8543 }
8544
8545 /* pipes are inserted between pairs of commands */
8546 pipefds.rd = 0;
8547 pipefds.wr = 1;
8548 if (cmd_no < pi->num_cmds)
8549 xpiped_pair(pipefds);
8550
Denys Vlasenko5807e182018-02-08 19:19:04 +01008551#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008552 if (G.lineno_var)
8553 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8554#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008555
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008556 command->pid = BB_MMU ? fork() : vfork();
8557 if (!command->pid) { /* child */
8558#if ENABLE_HUSH_JOB
8559 disable_restore_tty_pgrp_on_exit();
8560 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8561
8562 /* Every child adds itself to new process group
8563 * with pgid == pid_of_first_child_in_pipe */
8564 if (G.run_list_level == 1 && G_interactive_fd) {
8565 pid_t pgrp;
8566 pgrp = pi->pgrp;
8567 if (pgrp < 0) /* true for 1st process only */
8568 pgrp = getpid();
8569 if (setpgid(0, pgrp) == 0
8570 && pi->followup != PIPE_BG
8571 && G_saved_tty_pgrp /* we have ctty */
8572 ) {
8573 /* We do it in *every* child, not just first,
8574 * to avoid races */
8575 tcsetpgrp(G_interactive_fd, pgrp);
8576 }
8577 }
8578#endif
8579 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8580 /* 1st cmd in backgrounded pipe
8581 * should have its stdin /dev/null'ed */
8582 close(0);
8583 if (open(bb_dev_null, O_RDONLY))
8584 xopen("/", O_RDONLY);
8585 } else {
8586 xmove_fd(next_infd, 0);
8587 }
8588 xmove_fd(pipefds.wr, 1);
8589 if (pipefds.rd > 1)
8590 close(pipefds.rd);
8591 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008592 * and the pipe fd (fd#1) is available for dup'ing:
8593 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8594 * of cmd1 goes into pipe.
8595 */
8596 if (setup_redirects(command, NULL)) {
8597 /* Happens when redir file can't be opened:
8598 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8599 * FOO
8600 * hush: can't open '/qwe/rty': No such file or directory
8601 * BAZ
8602 * (echo BAR is not executed, it hits _exit(1) below)
8603 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008604 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008605 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008606
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008607 /* Stores to nommu_save list of env vars putenv'ed
8608 * (NOMMU, on MMU we don't need that) */
8609 /* cast away volatility... */
8610 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8611 /* pseudo_exec() does not return */
8612 }
8613
8614 /* parent or error */
8615#if ENABLE_HUSH_FAST
8616 G.count_SIGCHLD++;
8617//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8618#endif
8619 enable_restore_tty_pgrp_on_exit();
8620#if !BB_MMU
8621 /* Clean up after vforked child */
8622 free(nommu_save.argv);
8623 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008624 G.var_nest_level = sv_var_nest_level;
8625 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008626 add_vars(nommu_save.old_vars);
8627#endif
8628 free(argv_expanded);
8629 argv_expanded = NULL;
8630 if (command->pid < 0) { /* [v]fork failed */
8631 /* Clearly indicate, was it fork or vfork */
8632 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8633 } else {
8634 pi->alive_cmds++;
8635#if ENABLE_HUSH_JOB
8636 /* Second and next children need to know pid of first one */
8637 if (pi->pgrp < 0)
8638 pi->pgrp = command->pid;
8639#endif
8640 }
8641
8642 if (cmd_no > 1)
8643 close(next_infd);
8644 if (cmd_no < pi->num_cmds)
8645 close(pipefds.wr);
8646 /* Pass read (output) pipe end to next iteration */
8647 next_infd = pipefds.rd;
8648 }
8649
8650 if (!pi->alive_cmds) {
8651 debug_leave();
8652 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8653 return 1;
8654 }
8655
8656 debug_leave();
8657 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8658 return -1;
8659}
8660
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008661/* NB: called by pseudo_exec, and therefore must not modify any
8662 * global data until exec/_exit (we can be a child after vfork!) */
8663static int run_list(struct pipe *pi)
8664{
8665#if ENABLE_HUSH_CASE
8666 char *case_word = NULL;
8667#endif
8668#if ENABLE_HUSH_LOOPS
8669 struct pipe *loop_top = NULL;
8670 char **for_lcur = NULL;
8671 char **for_list = NULL;
8672#endif
8673 smallint last_followup;
8674 smalluint rcode;
8675#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8676 smalluint cond_code = 0;
8677#else
8678 enum { cond_code = 0 };
8679#endif
8680#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008681 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008682 smallint last_rword; /* ditto */
8683#endif
8684
8685 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8686 debug_enter();
8687
8688#if ENABLE_HUSH_LOOPS
8689 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008690 {
8691 struct pipe *cpipe;
8692 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8693 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8694 continue;
8695 /* current word is FOR or IN (BOLD in comments below) */
8696 if (cpipe->next == NULL) {
8697 syntax_error("malformed for");
8698 debug_leave();
8699 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8700 return 1;
8701 }
8702 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8703 if (cpipe->next->res_word == RES_DO)
8704 continue;
8705 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8706 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8707 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8708 ) {
8709 syntax_error("malformed for");
8710 debug_leave();
8711 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8712 return 1;
8713 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008714 }
8715 }
8716#endif
8717
8718 /* Past this point, all code paths should jump to ret: label
8719 * in order to return, no direct "return" statements please.
8720 * This helps to ensure that no memory is leaked. */
8721
8722#if ENABLE_HUSH_JOB
8723 G.run_list_level++;
8724#endif
8725
8726#if HAS_KEYWORDS
8727 rword = RES_NONE;
8728 last_rword = RES_XXXX;
8729#endif
8730 last_followup = PIPE_SEQ;
8731 rcode = G.last_exitcode;
8732
8733 /* Go through list of pipes, (maybe) executing them. */
8734 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008735 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008736 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008737
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008738 if (G.flag_SIGINT)
8739 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008740 if (G_flag_return_in_progress == 1)
8741 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008742
8743 IF_HAS_KEYWORDS(rword = pi->res_word;)
8744 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8745 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008746
8747 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008748 if (
8749#if ENABLE_HUSH_IF
8750 rword == RES_IF || rword == RES_ELIF ||
8751#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008752 pi->followup != PIPE_SEQ
8753 ) {
8754 G.errexit_depth++;
8755 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008756#if ENABLE_HUSH_LOOPS
8757 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8758 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8759 ) {
8760 /* start of a loop: remember where loop starts */
8761 loop_top = pi;
8762 G.depth_of_loop++;
8763 }
8764#endif
8765 /* Still in the same "if...", "then..." or "do..." branch? */
8766 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8767 if ((rcode == 0 && last_followup == PIPE_OR)
8768 || (rcode != 0 && last_followup == PIPE_AND)
8769 ) {
8770 /* It is "<true> || CMD" or "<false> && CMD"
8771 * and we should not execute CMD */
8772 debug_printf_exec("skipped cmd because of || or &&\n");
8773 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008774 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008775 }
8776 }
8777 last_followup = pi->followup;
8778 IF_HAS_KEYWORDS(last_rword = rword;)
8779#if ENABLE_HUSH_IF
8780 if (cond_code) {
8781 if (rword == RES_THEN) {
8782 /* if false; then ... fi has exitcode 0! */
8783 G.last_exitcode = rcode = EXIT_SUCCESS;
8784 /* "if <false> THEN cmd": skip cmd */
8785 continue;
8786 }
8787 } else {
8788 if (rword == RES_ELSE || rword == RES_ELIF) {
8789 /* "if <true> then ... ELSE/ELIF cmd":
8790 * skip cmd and all following ones */
8791 break;
8792 }
8793 }
8794#endif
8795#if ENABLE_HUSH_LOOPS
8796 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8797 if (!for_lcur) {
8798 /* first loop through for */
8799
8800 static const char encoded_dollar_at[] ALIGN1 = {
8801 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8802 }; /* encoded representation of "$@" */
8803 static const char *const encoded_dollar_at_argv[] = {
8804 encoded_dollar_at, NULL
8805 }; /* argv list with one element: "$@" */
8806 char **vals;
8807
8808 vals = (char**)encoded_dollar_at_argv;
8809 if (pi->next->res_word == RES_IN) {
8810 /* if no variable values after "in" we skip "for" */
8811 if (!pi->next->cmds[0].argv) {
8812 G.last_exitcode = rcode = EXIT_SUCCESS;
8813 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8814 break;
8815 }
8816 vals = pi->next->cmds[0].argv;
8817 } /* else: "for var; do..." -> assume "$@" list */
8818 /* create list of variable values */
8819 debug_print_strings("for_list made from", vals);
8820 for_list = expand_strvec_to_strvec(vals);
8821 for_lcur = for_list;
8822 debug_print_strings("for_list", for_list);
8823 }
8824 if (!*for_lcur) {
8825 /* "for" loop is over, clean up */
8826 free(for_list);
8827 for_list = NULL;
8828 for_lcur = NULL;
8829 break;
8830 }
8831 /* Insert next value from for_lcur */
8832 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008833 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008834 continue;
8835 }
8836 if (rword == RES_IN) {
8837 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8838 }
8839 if (rword == RES_DONE) {
8840 continue; /* "done" has no cmds too */
8841 }
8842#endif
8843#if ENABLE_HUSH_CASE
8844 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008845 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02008846 case_word = expand_string_to_string(pi->cmds->argv[0], 1);
8847 debug_printf_exec("CASE word1:'%s'\n", case_word);
8848 //unbackslash(case_word);
8849 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008850 continue;
8851 }
8852 if (rword == RES_MATCH) {
8853 char **argv;
8854
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008855 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008856 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8857 break;
8858 /* all prev words didn't match, does this one match? */
8859 argv = pi->cmds->argv;
8860 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008861 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008862 /* TODO: which FNM_xxx flags to use? */
8863 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008864 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008865 free(pattern);
8866 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008867 free(case_word);
8868 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008869 break;
8870 }
8871 argv++;
8872 }
8873 continue;
8874 }
8875 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008876 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008877 if (cond_code != 0)
8878 continue; /* not matched yet, skip this pipe */
8879 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008880 if (rword == RES_ESAC) {
8881 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8882 if (case_word) {
8883 /* "case" did not match anything: still set $? (to 0) */
8884 G.last_exitcode = rcode = EXIT_SUCCESS;
8885 }
8886 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008887#endif
8888 /* Just pressing <enter> in shell should check for jobs.
8889 * OTOH, in non-interactive shell this is useless
8890 * and only leads to extra job checks */
8891 if (pi->num_cmds == 0) {
8892 if (G_interactive_fd)
8893 goto check_jobs_and_continue;
8894 continue;
8895 }
8896
8897 /* After analyzing all keywords and conditions, we decided
8898 * to execute this pipe. NB: have to do checkjobs(NULL)
8899 * after run_pipe to collect any background children,
8900 * even if list execution is to be stopped. */
8901 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008902#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008903 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008904#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008905 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8906 if (r != -1) {
8907 /* We ran a builtin, function, or group.
8908 * rcode is already known
8909 * and we don't need to wait for anything. */
8910 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8911 G.last_exitcode = rcode;
8912 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008913#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008914 /* Was it "break" or "continue"? */
8915 if (G.flag_break_continue) {
8916 smallint fbc = G.flag_break_continue;
8917 /* We might fall into outer *loop*,
8918 * don't want to break it too */
8919 if (loop_top) {
8920 G.depth_break_continue--;
8921 if (G.depth_break_continue == 0)
8922 G.flag_break_continue = 0;
8923 /* else: e.g. "continue 2" should *break* once, *then* continue */
8924 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8925 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008926 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008927 break;
8928 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008929 /* "continue": simulate end of loop */
8930 rword = RES_DONE;
8931 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008932 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008933#endif
8934 if (G_flag_return_in_progress == 1) {
8935 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8936 break;
8937 }
8938 } else if (pi->followup == PIPE_BG) {
8939 /* What does bash do with attempts to background builtins? */
8940 /* even bash 3.2 doesn't do that well with nested bg:
8941 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8942 * I'm NOT treating inner &'s as jobs */
8943#if ENABLE_HUSH_JOB
8944 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008945 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008946#endif
8947 /* Last command's pid goes to $! */
8948 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008949 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008950 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008951/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008952 rcode = EXIT_SUCCESS;
8953 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008954 } else {
8955#if ENABLE_HUSH_JOB
8956 if (G.run_list_level == 1 && G_interactive_fd) {
8957 /* Waits for completion, then fg's main shell */
8958 rcode = checkjobs_and_fg_shell(pi);
8959 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008960 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008961 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008962#endif
8963 /* This one just waits for completion */
8964 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8965 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8966 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008967 G.last_exitcode = rcode;
8968 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008969 }
8970
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008971 /* Handle "set -e" */
8972 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8973 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8974 if (G.errexit_depth == 0)
8975 hush_exit(rcode);
8976 }
8977 G.errexit_depth = sv_errexit_depth;
8978
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008979 /* Analyze how result affects subsequent commands */
8980#if ENABLE_HUSH_IF
8981 if (rword == RES_IF || rword == RES_ELIF)
8982 cond_code = rcode;
8983#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008984 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008985 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008986 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008987#if ENABLE_HUSH_LOOPS
8988 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008989 if (pi->next
8990 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008991 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008992 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008993 if (rword == RES_WHILE) {
8994 if (rcode) {
8995 /* "while false; do...done" - exitcode 0 */
8996 G.last_exitcode = rcode = EXIT_SUCCESS;
8997 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008998 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008999 }
9000 }
9001 if (rword == RES_UNTIL) {
9002 if (!rcode) {
9003 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009004 break;
9005 }
9006 }
9007 }
9008#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009009 } /* for (pi) */
9010
9011#if ENABLE_HUSH_JOB
9012 G.run_list_level--;
9013#endif
9014#if ENABLE_HUSH_LOOPS
9015 if (loop_top)
9016 G.depth_of_loop--;
9017 free(for_list);
9018#endif
9019#if ENABLE_HUSH_CASE
9020 free(case_word);
9021#endif
9022 debug_leave();
9023 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9024 return rcode;
9025}
9026
9027/* Select which version we will use */
9028static int run_and_free_list(struct pipe *pi)
9029{
9030 int rcode = 0;
9031 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009032 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009033 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9034 rcode = run_list(pi);
9035 }
9036 /* free_pipe_list has the side effect of clearing memory.
9037 * In the long run that function can be merged with run_list,
9038 * but doing that now would hobble the debugging effort. */
9039 free_pipe_list(pi);
9040 debug_printf_exec("run_and_free_list return %d\n", rcode);
9041 return rcode;
9042}
9043
9044
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009045static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009046{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009047 sighandler_t old_handler;
9048 unsigned sig = 0;
9049 while ((mask >>= 1) != 0) {
9050 sig++;
9051 if (!(mask & 1))
9052 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009053 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009054 /* POSIX allows shell to re-enable SIGCHLD
9055 * even if it was SIG_IGN on entry.
9056 * Therefore we skip IGN check for it:
9057 */
9058 if (sig == SIGCHLD)
9059 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009060 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9061 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9062 */
9063 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009064 if (old_handler == SIG_IGN) {
9065 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009066 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009067#if ENABLE_HUSH_TRAP
9068 if (!G_traps)
9069 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9070 free(G_traps[sig]);
9071 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9072#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009073 }
9074 }
9075}
9076
9077/* Called a few times only (or even once if "sh -c") */
9078static void install_special_sighandlers(void)
9079{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009080 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009081
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009082 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009083 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009084 if (G_interactive_fd) {
9085 mask |= SPECIAL_INTERACTIVE_SIGS;
9086 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009087 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009088 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009089 /* Careful, do not re-install handlers we already installed */
9090 if (G.special_sig_mask != mask) {
9091 unsigned diff = mask & ~G.special_sig_mask;
9092 G.special_sig_mask = mask;
9093 install_sighandlers(diff);
9094 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009095}
9096
9097#if ENABLE_HUSH_JOB
9098/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009099/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009100static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009101{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009102 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009103
9104 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009105 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009106 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9107 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009108 + (1 << SIGBUS ) * HUSH_DEBUG
9109 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009110 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009111 + (1 << SIGABRT)
9112 /* bash 3.2 seems to handle these just like 'fatal' ones */
9113 + (1 << SIGPIPE)
9114 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009115 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009116 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009117 * we never want to restore pgrp on exit, and this fn is not called
9118 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009119 /*+ (1 << SIGHUP )*/
9120 /*+ (1 << SIGTERM)*/
9121 /*+ (1 << SIGINT )*/
9122 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009123 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009124
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009125 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009126}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009127#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009128
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009129static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009130{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009131 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009132 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009133 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009134 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009135 break;
9136 case 'x':
9137 IF_HUSH_MODE_X(G_x_mode = state;)
9138 break;
9139 case 'o':
9140 if (!o_opt) {
9141 /* "set -+o" without parameter.
9142 * in bash, set -o produces this output:
9143 * pipefail off
9144 * and set +o:
9145 * set +o pipefail
9146 * We always use the second form.
9147 */
9148 const char *p = o_opt_strings;
9149 idx = 0;
9150 while (*p) {
9151 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9152 idx++;
9153 p += strlen(p) + 1;
9154 }
9155 break;
9156 }
9157 idx = index_in_strings(o_opt_strings, o_opt);
9158 if (idx >= 0) {
9159 G.o_opt[idx] = state;
9160 break;
9161 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009162 case 'e':
9163 G.o_opt[OPT_O_ERREXIT] = state;
9164 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009165 default:
9166 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009167 }
9168 return EXIT_SUCCESS;
9169}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009170
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009171int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009172int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009173{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009174 enum {
9175 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009176 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009177 };
9178 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009179 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009180 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009181 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009182 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009183
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009184 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009185 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009186 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009187
Denys Vlasenko10c01312011-05-11 11:49:21 +02009188#if ENABLE_HUSH_FAST
9189 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9190#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009191#if !BB_MMU
9192 G.argv0_for_re_execing = argv[0];
9193#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009194
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009195 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009196 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9197 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009198 shell_ver = xzalloc(sizeof(*shell_ver));
9199 shell_ver->flg_export = 1;
9200 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009201 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009202 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009203 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009204
Denys Vlasenko605067b2010-09-06 12:10:51 +02009205 /* Create shell local variables from the values
9206 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009207 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009208 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009209 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009210 if (e) while (*e) {
9211 char *value = strchr(*e, '=');
9212 if (value) { /* paranoia */
9213 cur_var->next = xzalloc(sizeof(*cur_var));
9214 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009215 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009216 cur_var->max_len = strlen(*e);
9217 cur_var->flg_export = 1;
9218 }
9219 e++;
9220 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009221 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009222 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9223 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009224
9225 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009226 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009227
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009228#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9229 /* Set (but not export) PS1/2 unless already set */
9230 if (!get_local_var_value("PS1"))
9231 set_local_var_from_halves("PS1", "\\w \\$ ");
9232 if (!get_local_var_value("PS2"))
9233 set_local_var_from_halves("PS2", "> ");
9234#endif
9235
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009236#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009237 /* Set (but not export) HOSTNAME unless already set */
9238 if (!get_local_var_value("HOSTNAME")) {
9239 struct utsname uts;
9240 uname(&uts);
9241 set_local_var_from_halves("HOSTNAME", uts.nodename);
9242 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009243 /* bash also exports SHLVL and _,
9244 * and sets (but doesn't export) the following variables:
9245 * BASH=/bin/bash
9246 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9247 * BASH_VERSION='3.2.0(1)-release'
9248 * HOSTTYPE=i386
9249 * MACHTYPE=i386-pc-linux-gnu
9250 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009251 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009252 * EUID=<NNNNN>
9253 * UID=<NNNNN>
9254 * GROUPS=()
9255 * LINES=<NNN>
9256 * COLUMNS=<NNN>
9257 * BASH_ARGC=()
9258 * BASH_ARGV=()
9259 * BASH_LINENO=()
9260 * BASH_SOURCE=()
9261 * DIRSTACK=()
9262 * PIPESTATUS=([0]="0")
9263 * HISTFILE=/<xxx>/.bash_history
9264 * HISTFILESIZE=500
9265 * HISTSIZE=500
9266 * MAILCHECK=60
9267 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9268 * SHELL=/bin/bash
9269 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9270 * TERM=dumb
9271 * OPTERR=1
9272 * OPTIND=1
9273 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009274 * PS4='+ '
9275 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009276#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009277
Denys Vlasenko5807e182018-02-08 19:19:04 +01009278#if ENABLE_HUSH_LINENO_VAR
9279 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009280 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9281 set_local_var(p, /*flags*/ 0);
9282 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9283 }
9284#endif
9285
Denis Vlasenko38f63192007-01-22 09:03:07 +00009286#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009287 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009288#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009289
Eric Andersen94ac2442001-05-22 19:05:18 +00009290 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009291 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009292
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009293 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009294
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009295 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009296 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009297 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009298 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009299 * in order to intercept (more) signals.
9300 */
9301
9302 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009303 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009304 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009305 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009306 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009307 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009308#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009309 "<:$:R:V:"
9310# if ENABLE_HUSH_FUNCTIONS
9311 "F:"
9312# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009313#endif
9314 );
9315 if (opt <= 0)
9316 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009317 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009318 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009319 /* Possibilities:
9320 * sh ... -c 'script'
9321 * sh ... -c 'script' ARG0 [ARG1...]
9322 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009323 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009324 * "" needs to be replaced with NULL
9325 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009326 * Note: the form without ARG0 never happens:
9327 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009328 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009329 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009330 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009331 G.root_ppid = getppid();
9332 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009333 G.global_argv = argv + optind;
9334 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009335 if (builtin_argc) {
9336 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9337 const struct built_in_command *x;
9338
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009339 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009340 x = find_builtin(optarg);
9341 if (x) { /* paranoia */
9342 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9343 G.global_argv += builtin_argc;
9344 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009345 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009346 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009347 }
9348 goto final_return;
9349 }
9350 if (!G.global_argv[0]) {
9351 /* -c 'script' (no params): prevent empty $0 */
9352 G.global_argv--; /* points to argv[i] of 'script' */
9353 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009354 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009355 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009356 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009357 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009358 goto final_return;
9359 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009360 /* Well, we cannot just declare interactiveness,
9361 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009362 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009363 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009364 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009365 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009366 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009367 case 'l':
9368 flags |= OPT_login;
9369 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009370#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009371 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009372 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009373 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009374 case '$': {
9375 unsigned long long empty_trap_mask;
9376
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009377 G.root_pid = bb_strtou(optarg, &optarg, 16);
9378 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009379 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9380 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009381 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9382 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009383 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009384 optarg++;
9385 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009386 optarg++;
9387 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9388 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009389 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009390 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009391# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009392 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009393 for (sig = 1; sig < NSIG; sig++) {
9394 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009395 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009396 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009397 }
9398 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009399# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009400 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009401# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009402 optarg++;
9403 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009404# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009405# if ENABLE_HUSH_FUNCTIONS
9406 /* nommu uses re-exec trick for "... | func | ...",
9407 * should allow "return".
9408 * This accidentally allows returns in subshells.
9409 */
9410 G_flag_return_in_progress = -1;
9411# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009412 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009413 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009414 case 'R':
9415 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009416 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009417 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009418# if ENABLE_HUSH_FUNCTIONS
9419 case 'F': {
9420 struct function *funcp = new_function(optarg);
9421 /* funcp->name is already set to optarg */
9422 /* funcp->body is set to NULL. It's a special case. */
9423 funcp->body_as_string = argv[optind];
9424 optind++;
9425 break;
9426 }
9427# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009428#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009429 case 'n':
9430 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009431 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009432 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009433 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009434 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009435#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009436 fprintf(stderr, "Usage: sh [FILE]...\n"
9437 " or: sh -c command [args]...\n\n");
9438 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009439#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009440 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009441#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009442 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009443 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009444
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009445 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9446 G.global_argc = argc - (optind - 1);
9447 G.global_argv = argv + (optind - 1);
9448 G.global_argv[0] = argv[0];
9449
Denys Vlasenkodea47882009-10-09 15:40:49 +02009450 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009451 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009452 G.root_ppid = getppid();
9453 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009454
9455 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009456 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009457 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009458 debug_printf("sourcing /etc/profile\n");
9459 input = fopen_for_read("/etc/profile");
9460 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009461 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009462 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009463 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009464 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009465 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009466 /* bash: after sourcing /etc/profile,
9467 * tries to source (in the given order):
9468 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009469 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009470 * bash also sources ~/.bash_logout on exit.
9471 * If called as sh, skips .bash_XXX files.
9472 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009473 }
9474
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009475 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9476 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009477 FILE *input;
9478 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009479 * "bash <script>" (which is never interactive (unless -i?))
9480 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009481 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009482 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009483 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009484 G.global_argc--;
9485 G.global_argv++;
9486 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009487 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009488 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009489 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009490 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009491 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009492 parse_and_run_file(input);
9493#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009494 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009495#endif
9496 goto final_return;
9497 }
9498
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009499 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009500 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009501 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009502
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009503 /* A shell is interactive if the '-i' flag was given,
9504 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009505 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009506 * no arguments remaining or the -s flag given
9507 * standard input is a terminal
9508 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009509 * Refer to Posix.2, the description of the 'sh' utility.
9510 */
9511#if ENABLE_HUSH_JOB
9512 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009513 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9514 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9515 if (G_saved_tty_pgrp < 0)
9516 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009517
9518 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009519 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009520 if (G_interactive_fd < 0) {
9521 /* try to dup to any fd */
9522 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009523 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009524 /* give up */
9525 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009526 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009527 }
9528 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009529// TODO: track & disallow any attempts of user
9530// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009531 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009532 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009533 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009534 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009535
Mike Frysinger38478a62009-05-20 04:48:06 -04009536 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009537 /* If we were run as 'hush &', sleep until we are
9538 * in the foreground (tty pgrp == our pgrp).
9539 * If we get started under a job aware app (like bash),
9540 * make sure we are now in charge so we don't fight over
9541 * who gets the foreground */
9542 while (1) {
9543 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009544 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9545 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009546 break;
9547 /* send TTIN to ourself (should stop us) */
9548 kill(- shell_pgrp, SIGTTIN);
9549 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009550 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009551
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009552 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009553 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009554
Mike Frysinger38478a62009-05-20 04:48:06 -04009555 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009556 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009557 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009558 /* Put ourselves in our own process group
9559 * (bash, too, does this only if ctty is available) */
9560 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9561 /* Grab control of the terminal */
9562 tcsetpgrp(G_interactive_fd, getpid());
9563 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009564 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009565
9566# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9567 {
9568 const char *hp = get_local_var_value("HISTFILE");
9569 if (!hp) {
9570 hp = get_local_var_value("HOME");
9571 if (hp)
9572 hp = concat_path_file(hp, ".hush_history");
9573 } else {
9574 hp = xstrdup(hp);
9575 }
9576 if (hp) {
9577 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009578 //set_local_var(xasprintf("HISTFILE=%s", ...));
9579 }
9580# if ENABLE_FEATURE_SH_HISTFILESIZE
9581 hp = get_local_var_value("HISTFILESIZE");
9582 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9583# endif
9584 }
9585# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009586 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009587 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009588 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009589#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009590 /* No job control compiled in, only prompt/line editing */
9591 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009592 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009593 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009594 /* try to dup to any fd */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009595 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009596 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009597 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009598 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009599 }
9600 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009601 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009602 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009603 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009604 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009605#else
9606 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009607 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009608#endif
9609 /* bash:
9610 * if interactive but not a login shell, sources ~/.bashrc
9611 * (--norc turns this off, --rcfile <file> overrides)
9612 */
9613
9614 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009615 /* note: ash and hush share this string */
9616 printf("\n\n%s %s\n"
9617 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9618 "\n",
9619 bb_banner,
9620 "hush - the humble shell"
9621 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009622 }
9623
Denis Vlasenkof9375282009-04-05 19:13:39 +00009624 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009625
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009626 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009627 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009628}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009629
9630
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009631/*
9632 * Built-ins
9633 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009634static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009635{
9636 return 0;
9637}
9638
Denys Vlasenko265062d2017-01-10 15:13:30 +01009639#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009640static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009641{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009642 int argc = string_array_len(argv);
9643 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009644}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009645#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009646#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009647static int FAST_FUNC builtin_test(char **argv)
9648{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009649 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009650}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009651#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009652#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009653static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009654{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009655 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009656}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009657#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009658#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009659static int FAST_FUNC builtin_printf(char **argv)
9660{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009661 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009662}
9663#endif
9664
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009665#if ENABLE_HUSH_HELP
9666static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9667{
9668 const struct built_in_command *x;
9669
9670 printf(
9671 "Built-in commands:\n"
9672 "------------------\n");
9673 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9674 if (x->b_descr)
9675 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9676 }
9677 return EXIT_SUCCESS;
9678}
9679#endif
9680
9681#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9682static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9683{
9684 show_history(G.line_input_state);
9685 return EXIT_SUCCESS;
9686}
9687#endif
9688
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009689static char **skip_dash_dash(char **argv)
9690{
9691 argv++;
9692 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9693 argv++;
9694 return argv;
9695}
9696
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009697static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009698{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009699 const char *newdir;
9700
9701 argv = skip_dash_dash(argv);
9702 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009703 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009704 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009705 * bash says "bash: cd: HOME not set" and does nothing
9706 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009707 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009708 const char *home = get_local_var_value("HOME");
9709 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009710 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009711 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009712 /* Mimic bash message exactly */
9713 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009714 return EXIT_FAILURE;
9715 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009716 /* Read current dir (get_cwd(1) is inside) and set PWD.
9717 * Note: do not enforce exporting. If PWD was unset or unexported,
9718 * set it again, but do not export. bash does the same.
9719 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009720 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009721 return EXIT_SUCCESS;
9722}
9723
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009724static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9725{
9726 puts(get_cwd(0));
9727 return EXIT_SUCCESS;
9728}
9729
9730static int FAST_FUNC builtin_eval(char **argv)
9731{
9732 int rcode = EXIT_SUCCESS;
9733
9734 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009735 if (argv[0]) {
9736 char *str = NULL;
9737
9738 if (argv[1]) {
9739 /* "The eval utility shall construct a command by
9740 * concatenating arguments together, separating
9741 * each with a <space> character."
9742 */
9743 char *p;
9744 unsigned len = 0;
9745 char **pp = argv;
9746 do
9747 len += strlen(*pp) + 1;
9748 while (*++pp);
9749 str = p = xmalloc(len);
9750 pp = argv;
9751 do {
9752 p = stpcpy(p, *pp);
9753 *p++ = ' ';
9754 } while (*++pp);
9755 p[-1] = '\0';
9756 }
9757
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009758 /* bash:
9759 * eval "echo Hi; done" ("done" is syntax error):
9760 * "echo Hi" will not execute too.
9761 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009762 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009763 free(str);
9764 rcode = G.last_exitcode;
9765 }
9766 return rcode;
9767}
9768
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009769static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009770{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009771 argv = skip_dash_dash(argv);
9772 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009773 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009774
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009775 /* Careful: we can end up here after [v]fork. Do not restore
9776 * tty pgrp then, only top-level shell process does that */
9777 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9778 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9779
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009780 /* Saved-redirect fds, script fds and G_interactive_fd are still
9781 * open here. However, they are all CLOEXEC, and execv below
9782 * closes them. Try interactive "exec ls -l /proc/self/fd",
9783 * it should show no extra open fds in the "ls" process.
9784 * If we'd try to run builtins/NOEXECs, this would need improving.
9785 */
9786 //close_saved_fds_and_FILE_fds();
9787
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009788 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009789 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009790 * and tcsetpgrp, and this is inherently racy.
9791 */
9792 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009793}
9794
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009795static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009796{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009797 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009798
9799 /* interactive bash:
9800 * # trap "echo EEE" EXIT
9801 * # exit
9802 * exit
9803 * There are stopped jobs.
9804 * (if there are _stopped_ jobs, running ones don't count)
9805 * # exit
9806 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009807 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009808 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009809 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009810 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009811
9812 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009813 argv = skip_dash_dash(argv);
9814 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009815 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009816 /* mimic bash: exit 123abc == exit 255 + error msg */
9817 xfunc_error_retval = 255;
9818 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009819 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009820}
9821
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009822#if ENABLE_HUSH_TYPE
9823/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9824static int FAST_FUNC builtin_type(char **argv)
9825{
9826 int ret = EXIT_SUCCESS;
9827
9828 while (*++argv) {
9829 const char *type;
9830 char *path = NULL;
9831
9832 if (0) {} /* make conditional compile easier below */
9833 /*else if (find_alias(*argv))
9834 type = "an alias";*/
9835#if ENABLE_HUSH_FUNCTIONS
9836 else if (find_function(*argv))
9837 type = "a function";
9838#endif
9839 else if (find_builtin(*argv))
9840 type = "a shell builtin";
9841 else if ((path = find_in_path(*argv)) != NULL)
9842 type = path;
9843 else {
9844 bb_error_msg("type: %s: not found", *argv);
9845 ret = EXIT_FAILURE;
9846 continue;
9847 }
9848
9849 printf("%s is %s\n", *argv, type);
9850 free(path);
9851 }
9852
9853 return ret;
9854}
9855#endif
9856
9857#if ENABLE_HUSH_READ
9858/* Interruptibility of read builtin in bash
9859 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9860 *
9861 * Empty trap makes read ignore corresponding signal, for any signal.
9862 *
9863 * SIGINT:
9864 * - terminates non-interactive shell;
9865 * - interrupts read in interactive shell;
9866 * if it has non-empty trap:
9867 * - executes trap and returns to command prompt in interactive shell;
9868 * - executes trap and returns to read in non-interactive shell;
9869 * SIGTERM:
9870 * - is ignored (does not interrupt) read in interactive shell;
9871 * - terminates non-interactive shell;
9872 * if it has non-empty trap:
9873 * - executes trap and returns to read;
9874 * SIGHUP:
9875 * - terminates shell (regardless of interactivity);
9876 * if it has non-empty trap:
9877 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009878 * SIGCHLD from children:
9879 * - does not interrupt read regardless of interactivity:
9880 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009881 */
9882static int FAST_FUNC builtin_read(char **argv)
9883{
9884 const char *r;
9885 char *opt_n = NULL;
9886 char *opt_p = NULL;
9887 char *opt_t = NULL;
9888 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009889 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009890 const char *ifs;
9891 int read_flags;
9892
9893 /* "!": do not abort on errors.
9894 * Option string must start with "sr" to match BUILTIN_READ_xxx
9895 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009896 read_flags = getopt32(argv,
9897#if BASH_READ_D
9898 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9899#else
9900 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9901#endif
9902 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009903 if (read_flags == (uint32_t)-1)
9904 return EXIT_FAILURE;
9905 argv += optind;
9906 ifs = get_local_var_value("IFS"); /* can be NULL */
9907
9908 again:
9909 r = shell_builtin_read(set_local_var_from_halves,
9910 argv,
9911 ifs,
9912 read_flags,
9913 opt_n,
9914 opt_p,
9915 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009916 opt_u,
9917 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009918 );
9919
9920 if ((uintptr_t)r == 1 && errno == EINTR) {
9921 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009922 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009923 goto again;
9924 }
9925
9926 if ((uintptr_t)r > 1) {
9927 bb_error_msg("%s", r);
9928 r = (char*)(uintptr_t)1;
9929 }
9930
9931 return (uintptr_t)r;
9932}
9933#endif
9934
9935#if ENABLE_HUSH_UMASK
9936static int FAST_FUNC builtin_umask(char **argv)
9937{
9938 int rc;
9939 mode_t mask;
9940
9941 rc = 1;
9942 mask = umask(0);
9943 argv = skip_dash_dash(argv);
9944 if (argv[0]) {
9945 mode_t old_mask = mask;
9946
9947 /* numeric umasks are taken as-is */
9948 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9949 if (!isdigit(argv[0][0]))
9950 mask ^= 0777;
9951 mask = bb_parse_mode(argv[0], mask);
9952 if (!isdigit(argv[0][0]))
9953 mask ^= 0777;
9954 if ((unsigned)mask > 0777) {
9955 mask = old_mask;
9956 /* bash messages:
9957 * bash: umask: 'q': invalid symbolic mode operator
9958 * bash: umask: 999: octal number out of range
9959 */
9960 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9961 rc = 0;
9962 }
9963 } else {
9964 /* Mimic bash */
9965 printf("%04o\n", (unsigned) mask);
9966 /* fall through and restore mask which we set to 0 */
9967 }
9968 umask(mask);
9969
9970 return !rc; /* rc != 0 - success */
9971}
9972#endif
9973
Denys Vlasenko41ade052017-01-08 18:56:24 +01009974#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009975static void print_escaped(const char *s)
9976{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009977 if (*s == '\'')
9978 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009979 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009980 const char *p = strchrnul(s, '\'');
9981 /* print 'xxxx', possibly just '' */
9982 printf("'%.*s'", (int)(p - s), s);
9983 if (*p == '\0')
9984 break;
9985 s = p;
9986 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009987 /* s points to '; print "'''...'''" */
9988 putchar('"');
9989 do putchar('\''); while (*++s == '\'');
9990 putchar('"');
9991 } while (*s);
9992}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009993#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009994
Denys Vlasenko1e660422017-07-17 21:10:50 +02009995#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009996static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009997{
9998 do {
9999 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010000 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010001
10002 /* So far we do not check that name is valid (TODO?) */
10003
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010004 if (*name_end == '\0') {
10005 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010006
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010007 vpp = get_ptr_to_local_var(name, name_end - name);
10008 var = vpp ? *vpp : NULL;
10009
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010010 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010011 /* export -n NAME (without =VALUE) */
10012 if (var) {
10013 var->flg_export = 0;
10014 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10015 unsetenv(name);
10016 } /* else: export -n NOT_EXISTING_VAR: no-op */
10017 continue;
10018 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010019 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010020 /* export NAME (without =VALUE) */
10021 if (var) {
10022 var->flg_export = 1;
10023 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10024 putenv(var->varstr);
10025 continue;
10026 }
10027 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010028 if (flags & SETFLAG_MAKE_RO) {
10029 /* readonly NAME (without =VALUE) */
10030 if (var) {
10031 var->flg_read_only = 1;
10032 continue;
10033 }
10034 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010035# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010036 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010037 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010038 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10039 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010040 /* "local x=abc; ...; local x" - ignore second local decl */
10041 continue;
10042 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010043 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010044# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010045 /* Exporting non-existing variable.
10046 * bash does not put it in environment,
10047 * but remembers that it is exported,
10048 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010049 * We just set it to "" and export.
10050 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010051 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010052 * bash sets the value to "".
10053 */
10054 /* Or, it's "readonly NAME" (without =VALUE).
10055 * bash remembers NAME and disallows its creation
10056 * in the future.
10057 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010058 name = xasprintf("%s=", name);
10059 } else {
10060 /* (Un)exporting/making local NAME=VALUE */
10061 name = xstrdup(name);
10062 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010063 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010064 if (set_local_var(name, flags))
10065 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010066 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010067 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010068}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010069#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010070
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010071#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010072static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010073{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010074 unsigned opt_unexport;
10075
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010076#if ENABLE_HUSH_EXPORT_N
10077 /* "!": do not abort on errors */
10078 opt_unexport = getopt32(argv, "!n");
10079 if (opt_unexport == (uint32_t)-1)
10080 return EXIT_FAILURE;
10081 argv += optind;
10082#else
10083 opt_unexport = 0;
10084 argv++;
10085#endif
10086
10087 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010088 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010089 if (e) {
10090 while (*e) {
10091#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010092 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010093#else
10094 /* ash emits: export VAR='VAL'
10095 * bash: declare -x VAR="VAL"
10096 * we follow ash example */
10097 const char *s = *e++;
10098 const char *p = strchr(s, '=');
10099
10100 if (!p) /* wtf? take next variable */
10101 continue;
10102 /* export var= */
10103 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010104 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010105 putchar('\n');
10106#endif
10107 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010108 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010109 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010110 return EXIT_SUCCESS;
10111 }
10112
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010113 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010114}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010115#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010116
Denys Vlasenko295fef82009-06-03 12:47:26 +020010117#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010118static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010119{
10120 if (G.func_nest_level == 0) {
10121 bb_error_msg("%s: not in a function", argv[0]);
10122 return EXIT_FAILURE; /* bash compat */
10123 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010124 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010125 /* Since all builtins run in a nested variable level,
10126 * need to use level - 1 here. Or else the variable will be removed at once
10127 * after builtin returns.
10128 */
10129 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010130}
10131#endif
10132
Denys Vlasenko1e660422017-07-17 21:10:50 +020010133#if ENABLE_HUSH_READONLY
10134static int FAST_FUNC builtin_readonly(char **argv)
10135{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010136 argv++;
10137 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010138 /* bash: readonly [-p]: list all readonly VARs
10139 * (-p has no effect in bash)
10140 */
10141 struct variable *e;
10142 for (e = G.top_var; e; e = e->next) {
10143 if (e->flg_read_only) {
10144//TODO: quote value: readonly VAR='VAL'
10145 printf("readonly %s\n", e->varstr);
10146 }
10147 }
10148 return EXIT_SUCCESS;
10149 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010150 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010151}
10152#endif
10153
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010154#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010155/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10156static int FAST_FUNC builtin_unset(char **argv)
10157{
10158 int ret;
10159 unsigned opts;
10160
10161 /* "!": do not abort on errors */
10162 /* "+": stop at 1st non-option */
10163 opts = getopt32(argv, "!+vf");
10164 if (opts == (unsigned)-1)
10165 return EXIT_FAILURE;
10166 if (opts == 3) {
10167 bb_error_msg("unset: -v and -f are exclusive");
10168 return EXIT_FAILURE;
10169 }
10170 argv += optind;
10171
10172 ret = EXIT_SUCCESS;
10173 while (*argv) {
10174 if (!(opts & 2)) { /* not -f */
10175 if (unset_local_var(*argv)) {
10176 /* unset <nonexistent_var> doesn't fail.
10177 * Error is when one tries to unset RO var.
10178 * Message was printed by unset_local_var. */
10179 ret = EXIT_FAILURE;
10180 }
10181 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010182# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010183 else {
10184 unset_func(*argv);
10185 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010186# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010187 argv++;
10188 }
10189 return ret;
10190}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010191#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010192
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010193#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010194/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10195 * built-in 'set' handler
10196 * SUSv3 says:
10197 * set [-abCefhmnuvx] [-o option] [argument...]
10198 * set [+abCefhmnuvx] [+o option] [argument...]
10199 * set -- [argument...]
10200 * set -o
10201 * set +o
10202 * Implementations shall support the options in both their hyphen and
10203 * plus-sign forms. These options can also be specified as options to sh.
10204 * Examples:
10205 * Write out all variables and their values: set
10206 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10207 * Turn on the -x and -v options: set -xv
10208 * Unset all positional parameters: set --
10209 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10210 * Set the positional parameters to the expansion of x, even if x expands
10211 * with a leading '-' or '+': set -- $x
10212 *
10213 * So far, we only support "set -- [argument...]" and some of the short names.
10214 */
10215static int FAST_FUNC builtin_set(char **argv)
10216{
10217 int n;
10218 char **pp, **g_argv;
10219 char *arg = *++argv;
10220
10221 if (arg == NULL) {
10222 struct variable *e;
10223 for (e = G.top_var; e; e = e->next)
10224 puts(e->varstr);
10225 return EXIT_SUCCESS;
10226 }
10227
10228 do {
10229 if (strcmp(arg, "--") == 0) {
10230 ++argv;
10231 goto set_argv;
10232 }
10233 if (arg[0] != '+' && arg[0] != '-')
10234 break;
10235 for (n = 1; arg[n]; ++n) {
10236 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10237 goto error;
10238 if (arg[n] == 'o' && argv[1])
10239 argv++;
10240 }
10241 } while ((arg = *++argv) != NULL);
10242 /* Now argv[0] is 1st argument */
10243
10244 if (arg == NULL)
10245 return EXIT_SUCCESS;
10246 set_argv:
10247
10248 /* NB: G.global_argv[0] ($0) is never freed/changed */
10249 g_argv = G.global_argv;
10250 if (G.global_args_malloced) {
10251 pp = g_argv;
10252 while (*++pp)
10253 free(*pp);
10254 g_argv[1] = NULL;
10255 } else {
10256 G.global_args_malloced = 1;
10257 pp = xzalloc(sizeof(pp[0]) * 2);
10258 pp[0] = g_argv[0]; /* retain $0 */
10259 g_argv = pp;
10260 }
10261 /* This realloc's G.global_argv */
10262 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10263
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010264 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010265
10266 return EXIT_SUCCESS;
10267
10268 /* Nothing known, so abort */
10269 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010270 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010271 return EXIT_FAILURE;
10272}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010273#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010274
10275static int FAST_FUNC builtin_shift(char **argv)
10276{
10277 int n = 1;
10278 argv = skip_dash_dash(argv);
10279 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010280 n = bb_strtou(argv[0], NULL, 10);
10281 if (errno || n < 0) {
10282 /* shared string with ash.c */
10283 bb_error_msg("Illegal number: %s", argv[0]);
10284 /*
10285 * ash aborts in this case.
10286 * bash prints error message and set $? to 1.
10287 * Interestingly, for "shift 99999" bash does not
10288 * print error message, but does set $? to 1
10289 * (and does no shifting at all).
10290 */
10291 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010292 }
10293 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010294 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010295 int m = 1;
10296 while (m <= n)
10297 free(G.global_argv[m++]);
10298 }
10299 G.global_argc -= n;
10300 memmove(&G.global_argv[1], &G.global_argv[n+1],
10301 G.global_argc * sizeof(G.global_argv[0]));
10302 return EXIT_SUCCESS;
10303 }
10304 return EXIT_FAILURE;
10305}
10306
Denys Vlasenko74d40582017-08-11 01:32:46 +020010307#if ENABLE_HUSH_GETOPTS
10308static int FAST_FUNC builtin_getopts(char **argv)
10309{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010310/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10311
Denys Vlasenko74d40582017-08-11 01:32:46 +020010312TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010313If a required argument is not found, and getopts is not silent,
10314a question mark (?) is placed in VAR, OPTARG is unset, and a
10315diagnostic message is printed. If getopts is silent, then a
10316colon (:) is placed in VAR and OPTARG is set to the option
10317character found.
10318
10319Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010320
10321"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010322*/
10323 char cbuf[2];
10324 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010325 int c, n, exitcode, my_opterr;
10326 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010327
10328 optstring = *++argv;
10329 if (!optstring || !(var = *++argv)) {
10330 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10331 return EXIT_FAILURE;
10332 }
10333
Denys Vlasenko238ff982017-08-29 13:38:30 +020010334 if (argv[1])
10335 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10336 else
10337 argv = G.global_argv;
10338 cbuf[1] = '\0';
10339
10340 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010341 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010342 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010343 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010344 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010345 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010346
10347 /* getopts stops on first non-option. Add "+" to force that */
10348 /*if (optstring[0] != '+')*/ {
10349 char *s = alloca(strlen(optstring) + 2);
10350 sprintf(s, "+%s", optstring);
10351 optstring = s;
10352 }
10353
Denys Vlasenko238ff982017-08-29 13:38:30 +020010354 /* Naively, now we should just
10355 * cp = get_local_var_value("OPTIND");
10356 * optind = cp ? atoi(cp) : 0;
10357 * optarg = NULL;
10358 * opterr = my_opterr;
10359 * c = getopt(string_array_len(argv), argv, optstring);
10360 * and be done? Not so fast...
10361 * Unlike normal getopt() usage in C programs, here
10362 * each successive call will (usually) have the same argv[] CONTENTS,
10363 * but not the ADDRESSES. Worse yet, it's possible that between
10364 * invocations of "getopts", there will be calls to shell builtins
10365 * which use getopt() internally. Example:
10366 * while getopts "abc" RES -a -bc -abc de; do
10367 * unset -ff func
10368 * done
10369 * This would not work correctly: getopt() call inside "unset"
10370 * modifies internal libc state which is tracking position in
10371 * multi-option strings ("-abc"). At best, it can skip options
10372 * or return the same option infinitely. With glibc implementation
10373 * of getopt(), it would use outright invalid pointers and return
10374 * garbage even _without_ "unset" mangling internal state.
10375 *
10376 * We resort to resetting getopt() state and calling it N times,
10377 * until we get Nth result (or failure).
10378 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10379 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010380 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010381 count = 0;
10382 n = string_array_len(argv);
10383 do {
10384 optarg = NULL;
10385 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10386 c = getopt(n, argv, optstring);
10387 if (c < 0)
10388 break;
10389 count++;
10390 } while (count <= G.getopt_count);
10391
10392 /* Set OPTIND. Prevent resetting of the magic counter! */
10393 set_local_var_from_halves("OPTIND", utoa(optind));
10394 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010395 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010396
10397 /* Set OPTARG */
10398 /* Always set or unset, never left as-is, even on exit/error:
10399 * "If no option was found, or if the option that was found
10400 * does not have an option-argument, OPTARG shall be unset."
10401 */
10402 cp = optarg;
10403 if (c == '?') {
10404 /* If ":optstring" and unknown option is seen,
10405 * it is stored to OPTARG.
10406 */
10407 if (optstring[1] == ':') {
10408 cbuf[0] = optopt;
10409 cp = cbuf;
10410 }
10411 }
10412 if (cp)
10413 set_local_var_from_halves("OPTARG", cp);
10414 else
10415 unset_local_var("OPTARG");
10416
10417 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010418 exitcode = EXIT_SUCCESS;
10419 if (c < 0) { /* -1: end of options */
10420 exitcode = EXIT_FAILURE;
10421 c = '?';
10422 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010423
Denys Vlasenko238ff982017-08-29 13:38:30 +020010424 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010425 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010426 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010427
Denys Vlasenko74d40582017-08-11 01:32:46 +020010428 return exitcode;
10429}
10430#endif
10431
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010432static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010433{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010434 char *arg_path, *filename;
10435 FILE *input;
10436 save_arg_t sv;
10437 char *args_need_save;
10438#if ENABLE_HUSH_FUNCTIONS
10439 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010440#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010441
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010442 argv = skip_dash_dash(argv);
10443 filename = argv[0];
10444 if (!filename) {
10445 /* bash says: "bash: .: filename argument required" */
10446 return 2; /* bash compat */
10447 }
10448 arg_path = NULL;
10449 if (!strchr(filename, '/')) {
10450 arg_path = find_in_path(filename);
10451 if (arg_path)
10452 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010453 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010454 errno = ENOENT;
10455 bb_simple_perror_msg(filename);
10456 return EXIT_FAILURE;
10457 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010458 }
10459 input = remember_FILE(fopen_or_warn(filename, "r"));
10460 free(arg_path);
10461 if (!input) {
10462 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10463 /* POSIX: non-interactive shell should abort here,
10464 * not merely fail. So far no one complained :)
10465 */
10466 return EXIT_FAILURE;
10467 }
10468
10469#if ENABLE_HUSH_FUNCTIONS
10470 sv_flg = G_flag_return_in_progress;
10471 /* "we are inside sourced file, ok to use return" */
10472 G_flag_return_in_progress = -1;
10473#endif
10474 args_need_save = argv[1]; /* used as a boolean variable */
10475 if (args_need_save)
10476 save_and_replace_G_args(&sv, argv);
10477
10478 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10479 G.last_exitcode = 0;
10480 parse_and_run_file(input);
10481 fclose_and_forget(input);
10482
10483 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10484 restore_G_args(&sv, argv);
10485#if ENABLE_HUSH_FUNCTIONS
10486 G_flag_return_in_progress = sv_flg;
10487#endif
10488
10489 return G.last_exitcode;
10490}
10491
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010492#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010493static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010494{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010495 int sig;
10496 char *new_cmd;
10497
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010498 if (!G_traps)
10499 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010500
10501 argv++;
10502 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010503 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010504 /* No args: print all trapped */
10505 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010506 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010507 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010508 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010509 /* note: bash adds "SIG", but only if invoked
10510 * as "bash". If called as "sh", or if set -o posix,
10511 * then it prints short signal names.
10512 * We are printing short names: */
10513 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010514 }
10515 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010516 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010517 return EXIT_SUCCESS;
10518 }
10519
10520 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010521 /* If first arg is a number: reset all specified signals */
10522 sig = bb_strtou(*argv, NULL, 10);
10523 if (errno == 0) {
10524 int ret;
10525 process_sig_list:
10526 ret = EXIT_SUCCESS;
10527 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010528 sighandler_t handler;
10529
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010530 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010531 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010532 ret = EXIT_FAILURE;
10533 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010534 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010535 continue;
10536 }
10537
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010538 free(G_traps[sig]);
10539 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010540
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010541 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010542 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010543
10544 /* There is no signal for 0 (EXIT) */
10545 if (sig == 0)
10546 continue;
10547
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010548 if (new_cmd)
10549 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10550 else
10551 /* We are removing trap handler */
10552 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010553 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010554 }
10555 return ret;
10556 }
10557
10558 if (!argv[1]) { /* no second arg */
10559 bb_error_msg("trap: invalid arguments");
10560 return EXIT_FAILURE;
10561 }
10562
10563 /* First arg is "-": reset all specified to default */
10564 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10565 /* Everything else: set arg as signal handler
10566 * (includes "" case, which ignores signal) */
10567 if (argv[0][0] == '-') {
10568 if (argv[0][1] == '\0') { /* "-" */
10569 /* new_cmd remains NULL: "reset these sigs" */
10570 goto reset_traps;
10571 }
10572 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10573 argv++;
10574 }
10575 /* else: "-something", no special meaning */
10576 }
10577 new_cmd = *argv;
10578 reset_traps:
10579 argv++;
10580 goto process_sig_list;
10581}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010582#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010583
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010584#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010585static struct pipe *parse_jobspec(const char *str)
10586{
10587 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010588 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010589
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010590 if (sscanf(str, "%%%u", &jobnum) != 1) {
10591 if (str[0] != '%'
10592 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10593 ) {
10594 bb_error_msg("bad argument '%s'", str);
10595 return NULL;
10596 }
10597 /* It is "%%", "%+" or "%" - current job */
10598 jobnum = G.last_jobid;
10599 if (jobnum == 0) {
10600 bb_error_msg("no current job");
10601 return NULL;
10602 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010603 }
10604 for (pi = G.job_list; pi; pi = pi->next) {
10605 if (pi->jobid == jobnum) {
10606 return pi;
10607 }
10608 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010609 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010610 return NULL;
10611}
10612
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010613static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10614{
10615 struct pipe *job;
10616 const char *status_string;
10617
10618 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10619 for (job = G.job_list; job; job = job->next) {
10620 if (job->alive_cmds == job->stopped_cmds)
10621 status_string = "Stopped";
10622 else
10623 status_string = "Running";
10624
10625 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10626 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010627
10628 clean_up_last_dead_job();
10629
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010630 return EXIT_SUCCESS;
10631}
10632
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010633/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010634static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010635{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010636 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010637 struct pipe *pi;
10638
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010639 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010640 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010641
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010642 /* If they gave us no args, assume they want the last backgrounded task */
10643 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010644 for (pi = G.job_list; pi; pi = pi->next) {
10645 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010646 goto found;
10647 }
10648 }
10649 bb_error_msg("%s: no current job", argv[0]);
10650 return EXIT_FAILURE;
10651 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010652
10653 pi = parse_jobspec(argv[1]);
10654 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010655 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010656 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010657 /* TODO: bash prints a string representation
10658 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010659 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010660 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010661 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010662 }
10663
10664 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010665 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10666 for (i = 0; i < pi->num_cmds; i++) {
10667 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010668 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010669 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010670
10671 i = kill(- pi->pgrp, SIGCONT);
10672 if (i < 0) {
10673 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010674 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010675 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010676 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010677 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010678 }
10679
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010680 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010681 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010682 return checkjobs_and_fg_shell(pi);
10683 }
10684 return EXIT_SUCCESS;
10685}
10686#endif
10687
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010688#if ENABLE_HUSH_KILL
10689static int FAST_FUNC builtin_kill(char **argv)
10690{
10691 int ret = 0;
10692
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010693# if ENABLE_HUSH_JOB
10694 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10695 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010696
10697 do {
10698 struct pipe *pi;
10699 char *dst;
10700 int j, n;
10701
10702 if (argv[i][0] != '%')
10703 continue;
10704 /*
10705 * "kill %N" - job kill
10706 * Converting to pgrp / pid kill
10707 */
10708 pi = parse_jobspec(argv[i]);
10709 if (!pi) {
10710 /* Eat bad jobspec */
10711 j = i;
10712 do {
10713 j++;
10714 argv[j - 1] = argv[j];
10715 } while (argv[j]);
10716 ret = 1;
10717 i--;
10718 continue;
10719 }
10720 /*
10721 * In jobs started under job control, we signal
10722 * entire process group by kill -PGRP_ID.
10723 * This happens, f.e., in interactive shell.
10724 *
10725 * Otherwise, we signal each child via
10726 * kill PID1 PID2 PID3.
10727 * Testcases:
10728 * sh -c 'sleep 1|sleep 1 & kill %1'
10729 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10730 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10731 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010732 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010733 dst = alloca(n * sizeof(int)*4);
10734 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010735 if (G_interactive_fd)
10736 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010737 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010738 struct command *cmd = &pi->cmds[j];
10739 /* Skip exited members of the job */
10740 if (cmd->pid == 0)
10741 continue;
10742 /*
10743 * kill_main has matching code to expect
10744 * leading space. Needed to not confuse
10745 * negative pids with "kill -SIGNAL_NO" syntax
10746 */
10747 dst += sprintf(dst, " %u", (int)cmd->pid);
10748 }
10749 *dst = '\0';
10750 } while (argv[++i]);
10751 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010752# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010753
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010754 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010755 ret = run_applet_main(argv, kill_main);
10756 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010757 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010758 return ret;
10759}
10760#endif
10761
10762#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010763/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010764#if !ENABLE_HUSH_JOB
10765# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10766#endif
10767static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010768{
10769 int ret = 0;
10770 for (;;) {
10771 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010772 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010773
Denys Vlasenko830ea352016-11-08 04:59:11 +010010774 if (!sigisemptyset(&G.pending_set))
10775 goto check_sig;
10776
Denys Vlasenko7e675362016-10-28 21:57:31 +020010777 /* waitpid is not interruptible by SA_RESTARTed
10778 * signals which we use. Thus, this ugly dance:
10779 */
10780
10781 /* Make sure possible SIGCHLD is stored in kernel's
10782 * pending signal mask before we call waitpid.
10783 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010784 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010785 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010786 sigfillset(&oldset); /* block all signals, remember old set */
10787 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010788
10789 if (!sigisemptyset(&G.pending_set)) {
10790 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010791 goto restore;
10792 }
10793
10794 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010795/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010796 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010797 debug_printf_exec("checkjobs:%d\n", ret);
10798#if ENABLE_HUSH_JOB
10799 if (waitfor_pipe) {
10800 int rcode = job_exited_or_stopped(waitfor_pipe);
10801 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10802 if (rcode >= 0) {
10803 ret = rcode;
10804 sigprocmask(SIG_SETMASK, &oldset, NULL);
10805 break;
10806 }
10807 }
10808#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010809 /* if ECHILD, there are no children (ret is -1 or 0) */
10810 /* if ret == 0, no children changed state */
10811 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010812 if (errno == ECHILD || ret) {
10813 ret--;
10814 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010815 ret = 0;
10816 sigprocmask(SIG_SETMASK, &oldset, NULL);
10817 break;
10818 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010819 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010820 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10821 /* Note: sigsuspend invokes signal handler */
10822 sigsuspend(&oldset);
10823 restore:
10824 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010825 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010826 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010827 sig = check_and_run_traps();
10828 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010829 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010830 ret = 128 + sig;
10831 break;
10832 }
10833 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10834 }
10835 return ret;
10836}
10837
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010838static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010839{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010840 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010841 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010842
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010843 argv = skip_dash_dash(argv);
10844 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010845 /* Don't care about wait results */
10846 /* Note 1: must wait until there are no more children */
10847 /* Note 2: must be interruptible */
10848 /* Examples:
10849 * $ sleep 3 & sleep 6 & wait
10850 * [1] 30934 sleep 3
10851 * [2] 30935 sleep 6
10852 * [1] Done sleep 3
10853 * [2] Done sleep 6
10854 * $ sleep 3 & sleep 6 & wait
10855 * [1] 30936 sleep 3
10856 * [2] 30937 sleep 6
10857 * [1] Done sleep 3
10858 * ^C <-- after ~4 sec from keyboard
10859 * $
10860 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010861 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010862 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010863
Denys Vlasenko7e675362016-10-28 21:57:31 +020010864 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010865 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010866 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010867#if ENABLE_HUSH_JOB
10868 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010869 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010870 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010871 wait_pipe = parse_jobspec(*argv);
10872 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010873 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010874 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010875 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010876 } else {
10877 /* waiting on "last dead job" removes it */
10878 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010879 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010880 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010881 /* else: parse_jobspec() already emitted error msg */
10882 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010883 }
10884#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010885 /* mimic bash message */
10886 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010887 ret = EXIT_FAILURE;
10888 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010889 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010890
Denys Vlasenko7e675362016-10-28 21:57:31 +020010891 /* Do we have such child? */
10892 ret = waitpid(pid, &status, WNOHANG);
10893 if (ret < 0) {
10894 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010895 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010896 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010897 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010898 /* "wait $!" but last bg task has already exited. Try:
10899 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10900 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010901 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010902 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010903 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010904 } else {
10905 /* Example: "wait 1". mimic bash message */
10906 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010907 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010908 } else {
10909 /* ??? */
10910 bb_perror_msg("wait %s", *argv);
10911 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010912 continue; /* bash checks all argv[] */
10913 }
10914 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010915 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010916 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010917 } else {
10918 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010919 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010920 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010921 if (WIFSIGNALED(status))
10922 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010923 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010924 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010925
10926 return ret;
10927}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010928#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010929
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010930#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10931static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10932{
10933 if (argv[1]) {
10934 def = bb_strtou(argv[1], NULL, 10);
10935 if (errno || def < def_min || argv[2]) {
10936 bb_error_msg("%s: bad arguments", argv[0]);
10937 def = UINT_MAX;
10938 }
10939 }
10940 return def;
10941}
10942#endif
10943
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010944#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010945static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010946{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010947 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010948 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010949 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010950 /* if we came from builtin_continue(), need to undo "= 1" */
10951 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010952 return EXIT_SUCCESS; /* bash compat */
10953 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010954 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010955
10956 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10957 if (depth == UINT_MAX)
10958 G.flag_break_continue = BC_BREAK;
10959 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010960 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010961
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010962 return EXIT_SUCCESS;
10963}
10964
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010965static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010966{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010967 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10968 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010969}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010970#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010971
10972#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010973static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010974{
10975 int rc;
10976
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010977 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010978 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10979 return EXIT_FAILURE; /* bash compat */
10980 }
10981
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010982 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010983
10984 /* bash:
10985 * out of range: wraps around at 256, does not error out
10986 * non-numeric param:
10987 * f() { false; return qwe; }; f; echo $?
10988 * bash: return: qwe: numeric argument required <== we do this
10989 * 255 <== we also do this
10990 */
10991 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10992 return rc;
10993}
10994#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010995
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010996#if ENABLE_HUSH_TIMES
10997static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10998{
10999 static const uint8_t times_tbl[] ALIGN1 = {
11000 ' ', offsetof(struct tms, tms_utime),
11001 '\n', offsetof(struct tms, tms_stime),
11002 ' ', offsetof(struct tms, tms_cutime),
11003 '\n', offsetof(struct tms, tms_cstime),
11004 0
11005 };
11006 const uint8_t *p;
11007 unsigned clk_tck;
11008 struct tms buf;
11009
11010 clk_tck = bb_clk_tck();
11011
11012 times(&buf);
11013 p = times_tbl;
11014 do {
11015 unsigned sec, frac;
11016 unsigned long t;
11017 t = *(clock_t *)(((char *) &buf) + p[1]);
11018 sec = t / clk_tck;
11019 frac = t % clk_tck;
11020 printf("%um%u.%03us%c",
11021 sec / 60, sec % 60,
11022 (frac * 1000) / clk_tck,
11023 p[0]);
11024 p += 2;
11025 } while (*p);
11026
11027 return EXIT_SUCCESS;
11028}
11029#endif
11030
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011031#if ENABLE_HUSH_MEMLEAK
11032static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11033{
11034 void *p;
11035 unsigned long l;
11036
11037# ifdef M_TRIM_THRESHOLD
11038 /* Optional. Reduces probability of false positives */
11039 malloc_trim(0);
11040# endif
11041 /* Crude attempt to find where "free memory" starts,
11042 * sans fragmentation. */
11043 p = malloc(240);
11044 l = (unsigned long)p;
11045 free(p);
11046 p = malloc(3400);
11047 if (l < (unsigned long)p) l = (unsigned long)p;
11048 free(p);
11049
11050
11051# if 0 /* debug */
11052 {
11053 struct mallinfo mi = mallinfo();
11054 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11055 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11056 }
11057# endif
11058
11059 if (!G.memleak_value)
11060 G.memleak_value = l;
11061
11062 l -= G.memleak_value;
11063 if ((long)l < 0)
11064 l = 0;
11065 l /= 1024;
11066 if (l > 127)
11067 l = 127;
11068
11069 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11070 return l;
11071}
11072#endif