blob: 971a16affa1521c847efbe7be170f3a846156da3 [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)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000443#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000444
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000445#define ERR_PTR ((void*)(long)1)
446
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100447#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000448
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200449#define _SPECIAL_VARS_STR "_*@$!?#"
450#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
451#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100452#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200453/* Support / and // replace ops */
454/* Note that // is stored as \ in "encoded" string representation */
455# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
456# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
457# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
458#else
459# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
460# define VAR_SUBST_OPS "%#:-=+?"
461# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
462#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200463
Denys Vlasenko932b9972018-01-11 12:39:48 +0100464#define SPECIAL_VAR_SYMBOL_STR "\3"
465#define SPECIAL_VAR_SYMBOL 3
466/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
467#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000468
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200469struct variable;
470
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000471static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
472
473/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000474 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000475 */
476#if !BB_MMU
477typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200478 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000479 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000480 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000481} nommu_save_t;
482#endif
483
Denys Vlasenko9b782552010-09-08 13:33:26 +0200484enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000485 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000486#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000487 RES_IF ,
488 RES_THEN ,
489 RES_ELIF ,
490 RES_ELSE ,
491 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000492#endif
493#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000494 RES_FOR ,
495 RES_WHILE ,
496 RES_UNTIL ,
497 RES_DO ,
498 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000499#endif
500#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000501 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000502#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000503#if ENABLE_HUSH_CASE
504 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200505 /* three pseudo-keywords support contrived "case" syntax: */
506 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
507 RES_MATCH , /* "word)" */
508 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000509 RES_ESAC ,
510#endif
511 RES_XXXX ,
512 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200513};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000514
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000515typedef struct o_string {
516 char *data;
517 int length; /* position where data is appended */
518 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200519 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000520 /* At least some part of the string was inside '' or "",
521 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200522 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000523 smallint has_empty_slot;
524 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
525} 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};
533enum {
534 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000535 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200536 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200537 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200538 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000539};
540/* Used for initialization: o_string foo = NULL_O_STRING; */
541#define NULL_O_STRING { NULL }
542
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200543#ifndef debug_printf_parse
544static const char *const assignment_flag[] = {
545 "MAYBE_ASSIGNMENT",
546 "DEFINITELY_ASSIGNMENT",
547 "NOT_ASSIGNMENT",
548 "WORD_IS_KEYWORD",
549};
550#endif
551
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000552typedef struct in_str {
553 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000554#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000555 smallint promptmode; /* 0: PS1, 1: PS2 */
556#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200557 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200558 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000559 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000560} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000561
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200562/* The descrip member of this structure is only used to make
563 * debugging output pretty */
564static const struct {
565 int mode;
566 signed char default_fd;
567 char descrip[3];
568} redir_table[] = {
569 { O_RDONLY, 0, "<" },
570 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
571 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
572 { O_CREAT|O_RDWR, 1, "<>" },
573 { O_RDONLY, 0, "<<" },
574/* Should not be needed. Bogus default_fd helps in debugging */
575/* { O_RDONLY, 77, "<<" }, */
576};
577
Eric Andersen25f27032001-04-26 23:22:31 +0000578struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000579 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000580 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000581 int rd_fd; /* fd to redirect */
582 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
583 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000584 smallint rd_type; /* (enum redir_type) */
585 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000586 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200587 * bit 0: do we need to trim leading tabs?
588 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000589 */
Eric Andersen25f27032001-04-26 23:22:31 +0000590};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000591typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200592 REDIRECT_INPUT = 0,
593 REDIRECT_OVERWRITE = 1,
594 REDIRECT_APPEND = 2,
595 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000596 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200597 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000598
599 REDIRFD_CLOSE = -3,
600 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000601 REDIRFD_TO_FILE = -1,
602 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000603
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000604 HEREDOC_SKIPTABS = 1,
605 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000606} redir_type;
607
Eric Andersen25f27032001-04-26 23:22:31 +0000608
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000609struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000610 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200611 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100612#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100613 unsigned lineno;
614#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200615 smallint cmd_type; /* CMD_xxx */
616#define CMD_NORMAL 0
617#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200618#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
619/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
620 * "export v=t*"
621 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200622# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000623#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200624#if ENABLE_HUSH_FUNCTIONS
625# define CMD_FUNCDEF 3
626#endif
627
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100628 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200629 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
630 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000631#if !BB_MMU
632 char *group_as_string;
633#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000634#if ENABLE_HUSH_FUNCTIONS
635 struct function *child_func;
636/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200637 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000638 * When we execute "f1() {a;}" cmd, we create new function and clear
639 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200640 * When we execute "f1() {b;}", we notice that f1 exists,
641 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000642 * we put those fields back into cmd->xxx
643 * (struct function has ->parent_cmd ptr to facilitate that).
644 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
645 * Without this trick, loop would execute a;b;b;b;...
646 * instead of correct sequence a;b;a;b;...
647 * When command is freed, it severs the link
648 * (sets ->child_func->parent_cmd to NULL).
649 */
650#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000651 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000652/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
653 * and on execution these are substituted with their values.
654 * Substitution can make _several_ words out of one argv[n]!
655 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000656 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000657 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000658 struct redir_struct *redirects; /* I/O redirections */
659};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000660/* Is there anything in this command at all? */
661#define IS_NULL_CMD(cmd) \
662 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
663
Eric Andersen25f27032001-04-26 23:22:31 +0000664struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000665 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000666 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000667 int alive_cmds; /* number of commands running (not exited) */
668 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000669#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100670 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000671 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000672 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000673#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000674 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000675 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000676 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
677 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000678};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000679typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100680 PIPE_SEQ = 0,
681 PIPE_AND = 1,
682 PIPE_OR = 2,
683 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000684} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000685/* Is there anything in this pipe at all? */
686#define IS_NULL_PIPE(pi) \
687 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000688
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000689/* This holds pointers to the various results of parsing */
690struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000691 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000692 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000693 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000694 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* last command in pipe (being constructed right now) */
696 struct command *command;
697 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000698 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000699#if !BB_MMU
700 o_string as_string;
701#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000702#if HAS_KEYWORDS
703 smallint ctx_res_w;
704 smallint ctx_inverted; /* "! cmd | cmd" */
705#if ENABLE_HUSH_CASE
706 smallint ctx_dsemicolon; /* ";;" seen */
707#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000708 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
709 int old_flag;
710 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000711 * example: "if pipe1; pipe2; then pipe3; fi"
712 * when we see "if" or "then", we malloc and copy current context,
713 * and make ->stack point to it. then we parse pipeN.
714 * when closing "then" / fi" / whatever is found,
715 * we move list_head into ->stack->command->group,
716 * copy ->stack into current context, and delete ->stack.
717 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000718 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000719 struct parse_context *stack;
720#endif
721};
722
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000723/* On program start, environ points to initial environment.
724 * putenv adds new pointers into it, unsetenv removes them.
725 * Neither of these (de)allocates the strings.
726 * setenv allocates new strings in malloc space and does putenv,
727 * and thus setenv is unusable (leaky) for shell's purposes */
728#define setenv(...) setenv_is_leaky_dont_use()
729struct variable {
730 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000731 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000732 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200733 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000734 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000735 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000736};
737
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000738enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000739 BC_BREAK = 1,
740 BC_CONTINUE = 2,
741};
742
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000743#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000744struct function {
745 struct function *next;
746 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000747 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000748 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200749# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000750 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200751# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000752};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000753#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000754
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000755
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100756/* set -/+o OPT support. (TODO: make it optional)
757 * bash supports the following opts:
758 * allexport off
759 * braceexpand on
760 * emacs on
761 * errexit off
762 * errtrace off
763 * functrace off
764 * hashall on
765 * histexpand off
766 * history on
767 * ignoreeof off
768 * interactive-comments on
769 * keyword off
770 * monitor on
771 * noclobber off
772 * noexec off
773 * noglob off
774 * nolog off
775 * notify off
776 * nounset off
777 * onecmd off
778 * physical off
779 * pipefail off
780 * posix off
781 * privileged off
782 * verbose off
783 * vi off
784 * xtrace off
785 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800786static const char o_opt_strings[] ALIGN1 =
787 "pipefail\0"
788 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200789 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800790#if ENABLE_HUSH_MODE_X
791 "xtrace\0"
792#endif
793 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100794enum {
795 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800796 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200797 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800798#if ENABLE_HUSH_MODE_X
799 OPT_O_XTRACE,
800#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100801 NUM_OPT_O
802};
803
804
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200805struct FILE_list {
806 struct FILE_list *next;
807 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200808 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200809};
810
811
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000812/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000813/* Sorted roughly by size (smaller offsets == smaller code) */
814struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000815 /* interactive_fd != 0 means we are an interactive shell.
816 * If we are, then saved_tty_pgrp can also be != 0, meaning
817 * that controlling tty is available. With saved_tty_pgrp == 0,
818 * job control still works, but terminal signals
819 * (^C, ^Z, ^Y, ^\) won't work at all, and background
820 * process groups can only be created with "cmd &".
821 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
822 * to give tty to the foreground process group,
823 * and will take it back when the group is stopped (^Z)
824 * or killed (^C).
825 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000826#if ENABLE_HUSH_INTERACTIVE
827 /* 'interactive_fd' is a fd# open to ctty, if we have one
828 * _AND_ if we decided to act interactively */
829 int interactive_fd;
830 const char *PS1;
831 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000832# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000833#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000834# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000835#endif
836#if ENABLE_FEATURE_EDITING
837 line_input_t *line_input_state;
838#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000839 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200840 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000841 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200842#if ENABLE_HUSH_RANDOM_SUPPORT
843 random_t random_gen;
844#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000845#if ENABLE_HUSH_JOB
846 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100847 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000848 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400850# define G_saved_tty_pgrp (G.saved_tty_pgrp)
851#else
852# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000853#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200854 /* How deeply are we in context where "set -e" is ignored */
855 int errexit_depth;
856 /* "set -e" rules (do we follow them correctly?):
857 * Exit if pipe, list, or compound command exits with a non-zero status.
858 * Shell does not exit if failed command is part of condition in
859 * if/while, part of && or || list except the last command, any command
860 * in a pipe but the last, or if the command's return value is being
861 * inverted with !. If a compound command other than a subshell returns a
862 * non-zero status because a command failed while -e was being ignored, the
863 * shell does not exit. A trap on ERR, if set, is executed before the shell
864 * exits [ERR is a bashism].
865 *
866 * If a compound command or function executes in a context where -e is
867 * ignored, none of the commands executed within are affected by the -e
868 * setting. If a compound command or function sets -e while executing in a
869 * context where -e is ignored, that setting does not have any effect until
870 * the compound command or the command containing the function call completes.
871 */
872
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100873 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100874#if ENABLE_HUSH_MODE_X
875# define G_x_mode (G.o_opt[OPT_O_XTRACE])
876#else
877# define G_x_mode 0
878#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000879 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000880#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000881 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000882#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000883#if ENABLE_HUSH_FUNCTIONS
884 /* 0: outside of a function (or sourced file)
885 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000886 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000887 */
888 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200889# define G_flag_return_in_progress (G.flag_return_in_progress)
890#else
891# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000892#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000893 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200894 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000895 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200896 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200897 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100898#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000899 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000900 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100901# define G_global_args_malloced (G.global_args_malloced)
902#else
903# define G_global_args_malloced 0
904#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000905 /* how many non-NULL argv's we have. NB: $# + 1 */
906 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000907 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000908#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000909 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000910#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000911#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000912 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000913 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000914#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200915#if ENABLE_HUSH_GETOPTS
916 unsigned getopt_count;
917#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000918 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000919 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200920 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200921 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200922 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200923 unsigned var_nest_level;
924#if ENABLE_HUSH_FUNCTIONS
925# if ENABLE_HUSH_LOCAL
926 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200927# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200928 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000929#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000930 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200931#if ENABLE_HUSH_FAST
932 unsigned count_SIGCHLD;
933 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200934 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200935#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100936#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100937 unsigned lineno;
938 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100939#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200940 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200941 /* Which signals have non-DFL handler (even with no traps set)?
942 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200943 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200944 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200945 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200946 * Other than these two times, never modified.
947 */
948 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200949#if ENABLE_HUSH_JOB
950 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100951# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200952#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200953# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200954#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100955#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000956 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100957# define G_traps G.traps
958#else
959# define G_traps ((char**)NULL)
960#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200961 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100962#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000963 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100964#endif
965#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000966 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000967#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200968 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200969#if ENABLE_FEATURE_EDITING
970 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
971#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000972};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000973#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000974/* Not #defining name to G.name - this quickly gets unwieldy
975 * (too many defines). Also, I actually prefer to see when a variable
976 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000977#define INIT_G() do { \
978 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200979 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
980 sigfillset(&G.sa.sa_mask); \
981 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000982} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000983
984
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000985/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200986static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100987#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200988static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100989#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200990static int builtin_eval(char **argv) FAST_FUNC;
991static int builtin_exec(char **argv) FAST_FUNC;
992static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100993#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200994static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100995#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +0200996#if ENABLE_HUSH_READONLY
997static int builtin_readonly(char **argv) FAST_FUNC;
998#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000999#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001000static int builtin_fg_bg(char **argv) FAST_FUNC;
1001static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001003#if ENABLE_HUSH_GETOPTS
1004static int builtin_getopts(char **argv) FAST_FUNC;
1005#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001006#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001007static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001008#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001009#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001010static int builtin_history(char **argv) FAST_FUNC;
1011#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001012#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001013static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001014#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001015#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001016static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001017#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001018#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001019static int builtin_printf(char **argv) FAST_FUNC;
1020#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001022#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001023static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001024#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001025#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001026static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001027#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001028static int builtin_shift(char **argv) FAST_FUNC;
1029static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001030#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001031static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001032#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001033#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001034static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001035#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001036#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001038#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001039#if ENABLE_HUSH_TIMES
1040static int builtin_times(char **argv) FAST_FUNC;
1041#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001043#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001045#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001046#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001048#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001049#if ENABLE_HUSH_KILL
1050static int builtin_kill(char **argv) FAST_FUNC;
1051#endif
1052#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001054#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001055#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001056static int builtin_break(char **argv) FAST_FUNC;
1057static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001058#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001059#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001061#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001062
1063/* Table of built-in functions. They can be forked or not, depending on
1064 * context: within pipes, they fork. As simple commands, they do not.
1065 * When used in non-forking context, they can change global variables
1066 * in the parent shell process. If forked, of course they cannot.
1067 * For example, 'unset foo | whatever' will parse and run, but foo will
1068 * still be set at the end. */
1069struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001070 const char *b_cmd;
1071 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001073 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001074# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001076# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001077#endif
1078};
1079
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001080static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001081 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001082 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001083#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001084 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001085#endif
1086#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001087 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001088#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001089 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001090#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001091 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001093 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1094 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001095 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001096#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001097 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001098#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001100 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001102#if ENABLE_HUSH_GETOPTS
1103 BLTIN("getopts" , builtin_getopts , NULL),
1104#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001108#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001109 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001110#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001111#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001112 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001113#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001114#if ENABLE_HUSH_KILL
1115 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1116#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001117#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001118 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001119#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001120#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001121 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001122#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001123#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001124 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001125#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001126#if ENABLE_HUSH_READONLY
1127 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1128#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001129#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001130 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001131#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001132#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001133 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001134#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001136#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001137 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001138#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001139#if ENABLE_HUSH_TIMES
1140 BLTIN("times" , builtin_times , NULL),
1141#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001142#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001144#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001145 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001146#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001147 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001148#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001149#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001150 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001151#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001152#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001153 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001154#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001155#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001156 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001157#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001158#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001159 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001160#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001161};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001162/* These builtins won't be used if we are on NOMMU and need to re-exec
1163 * (it's cheaper to run an external program in this case):
1164 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001165static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001166#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001168#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001169#if BASH_TEST2
1170 BLTIN("[[" , builtin_test , NULL),
1171#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001172#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001174#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001175#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001176 BLTIN("printf" , builtin_printf , NULL),
1177#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001178 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001179#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001180 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001181#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001182};
1183
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001184
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001185/* Debug printouts.
1186 */
1187#if HUSH_DEBUG
1188/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001189# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001190# define debug_enter() (G.debug_indent++)
1191# define debug_leave() (G.debug_indent--)
1192#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001193# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001194# define debug_enter() ((void)0)
1195# define debug_leave() ((void)0)
1196#endif
1197
1198#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001199# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001200#endif
1201
1202#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001203# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001204#endif
1205
1206#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001207#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001208#endif
1209
1210#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001211# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001212#endif
1213
1214#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001215# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001216# define DEBUG_JOBS 1
1217#else
1218# define DEBUG_JOBS 0
1219#endif
1220
1221#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001222# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001223# define DEBUG_EXPAND 1
1224#else
1225# define DEBUG_EXPAND 0
1226#endif
1227
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001228#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001229# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001230#endif
1231
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001232#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001233# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001234# define DEBUG_GLOB 1
1235#else
1236# define DEBUG_GLOB 0
1237#endif
1238
Denys Vlasenko2db74612017-07-07 22:07:28 +02001239#ifndef debug_printf_redir
1240# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1241#endif
1242
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001243#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001244# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001245#endif
1246
1247#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001248# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249#endif
1250
1251#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001252# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253# define DEBUG_CLEAN 1
1254#else
1255# define DEBUG_CLEAN 0
1256#endif
1257
1258#if DEBUG_EXPAND
1259static void debug_print_strings(const char *prefix, char **vv)
1260{
1261 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001262 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001263 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001265}
1266#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001267# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001268#endif
1269
1270
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001271/* Leak hunting. Use hush_leaktool.sh for post-processing.
1272 */
1273#if LEAK_HUNTING
1274static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001275{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001276 void *ptr = xmalloc((size + 0xff) & ~0xff);
1277 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1278 return ptr;
1279}
1280static void *xxrealloc(int lineno, void *ptr, size_t size)
1281{
1282 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1283 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1284 return ptr;
1285}
1286static char *xxstrdup(int lineno, const char *str)
1287{
1288 char *ptr = xstrdup(str);
1289 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1290 return ptr;
1291}
1292static void xxfree(void *ptr)
1293{
1294 fdprintf(2, "free %p\n", ptr);
1295 free(ptr);
1296}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001297# define xmalloc(s) xxmalloc(__LINE__, s)
1298# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1299# define xstrdup(s) xxstrdup(__LINE__, s)
1300# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001301#endif
1302
1303
1304/* Syntax and runtime errors. They always abort scripts.
1305 * In interactive use they usually discard unparsed and/or unexecuted commands
1306 * and return to the prompt.
1307 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1308 */
1309#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001310# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001311# define syntax_error(lineno, msg) syntax_error(msg)
1312# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1313# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1314# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1315# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001316#endif
1317
Denys Vlasenko39701202017-08-02 19:44:05 +02001318static void die_if_script(void)
1319{
1320 if (!G_interactive_fd) {
1321 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1322 xfunc_error_retval = G.last_exitcode;
1323 xfunc_die();
1324 }
1325}
1326
1327static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001328{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001329 va_list p;
1330
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001331#if HUSH_DEBUG >= 2
1332 bb_error_msg("hush.c:%u", lineno);
1333#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001334 va_start(p, fmt);
1335 bb_verror_msg(fmt, p, NULL);
1336 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001337 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001338}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001339
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001340static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001341{
1342 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001343 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001344 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001345 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001346 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001347}
1348
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001349static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001350{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001351 bb_error_msg("syntax error at '%s'", msg);
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_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001356{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001357 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001358//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1359// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001360}
1361
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001362static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001363{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001364 char msg[2] = { ch, '\0' };
1365 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001366}
1367
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001368static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001369{
1370 char msg[2];
1371 msg[0] = ch;
1372 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001373#if HUSH_DEBUG >= 2
1374 bb_error_msg("hush.c:%u", lineno);
1375#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001376 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001377 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001378}
1379
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001380#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001381# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001382# undef syntax_error
1383# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001384# undef syntax_error_unterm_ch
1385# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001386# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001387#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001388# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001389# define syntax_error(msg) syntax_error(__LINE__, msg)
1390# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1391# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1392# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1393# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001394#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001395
Denis Vlasenko552433b2009-04-04 19:29:21 +00001396
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001397#if ENABLE_HUSH_INTERACTIVE
1398static void cmdedit_update_prompt(void);
1399#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001400# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001401#endif
1402
1403
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001404/* Utility functions
1405 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001406/* Replace each \x with x in place, return ptr past NUL. */
1407static char *unbackslash(char *src)
1408{
Denys Vlasenko71885402009-09-24 01:44:13 +02001409 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001410 while (1) {
1411 if (*src == '\\')
1412 src++;
1413 if ((*dst++ = *src++) == '\0')
1414 break;
1415 }
1416 return dst;
1417}
1418
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001419static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001420{
1421 int i;
1422 unsigned count1;
1423 unsigned count2;
1424 char **v;
1425
1426 v = strings;
1427 count1 = 0;
1428 if (v) {
1429 while (*v) {
1430 count1++;
1431 v++;
1432 }
1433 }
1434 count2 = 0;
1435 v = add;
1436 while (*v) {
1437 count2++;
1438 v++;
1439 }
1440 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1441 v[count1 + count2] = NULL;
1442 i = count2;
1443 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001444 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001445 return v;
1446}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001447#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001448static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1449{
1450 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1451 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1452 return ptr;
1453}
1454#define add_strings_to_strings(strings, add, need_to_dup) \
1455 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1456#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001457
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001458/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001459static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001460{
1461 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001462 v[0] = add;
1463 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001464 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001465}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001466#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001467static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1468{
1469 char **ptr = add_string_to_strings(strings, add);
1470 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1471 return ptr;
1472}
1473#define add_string_to_strings(strings, add) \
1474 xx_add_string_to_strings(__LINE__, strings, add)
1475#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001476
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001477static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001478{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001479 char **v;
1480
1481 if (!strings)
1482 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001483 v = strings;
1484 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001485 free(*v);
1486 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001487 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001488 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001489}
1490
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001491static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001492{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001493 int newfd;
1494 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001495 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1496 if (newfd >= 0) {
1497 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1498 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1499 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001500 if (errno == EBUSY)
1501 goto repeat;
1502 if (errno == EINTR)
1503 goto repeat;
1504 }
1505 return newfd;
1506}
1507
Denys Vlasenko657e9002017-07-30 23:34:04 +02001508static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001509{
1510 int newfd;
1511 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001512 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001513 if (newfd < 0) {
1514 if (errno == EBUSY)
1515 goto repeat;
1516 if (errno == EINTR)
1517 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001518 /* fd was not open? */
1519 if (errno == EBADF)
1520 return fd;
1521 xfunc_die();
1522 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001523 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1524 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001525 close(fd);
1526 return newfd;
1527}
1528
1529
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001530/* Manipulating the list of open FILEs */
1531static FILE *remember_FILE(FILE *fp)
1532{
1533 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001534 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001535 n->next = G.FILE_list;
1536 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001537 n->fp = fp;
1538 n->fd = fileno(fp);
1539 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001540 }
1541 return fp;
1542}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001543static void fclose_and_forget(FILE *fp)
1544{
1545 struct FILE_list **pp = &G.FILE_list;
1546 while (*pp) {
1547 struct FILE_list *cur = *pp;
1548 if (cur->fp == fp) {
1549 *pp = cur->next;
1550 free(cur);
1551 break;
1552 }
1553 pp = &cur->next;
1554 }
1555 fclose(fp);
1556}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001557static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001558{
1559 struct FILE_list *fl = G.FILE_list;
1560 while (fl) {
1561 if (fd == fl->fd) {
1562 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001563 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001564 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 +02001565 return 1;
1566 }
1567 fl = fl->next;
1568 }
1569 return 0;
1570}
1571static void restore_redirected_FILEs(void)
1572{
1573 struct FILE_list *fl = G.FILE_list;
1574 while (fl) {
1575 int should_be = fileno(fl->fp);
1576 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001577 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001578 xmove_fd(fl->fd, should_be);
1579 fl->fd = should_be;
1580 }
1581 fl = fl->next;
1582 }
1583}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001584#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001585static void close_all_FILE_list(void)
1586{
1587 struct FILE_list *fl = G.FILE_list;
1588 while (fl) {
1589 /* fclose would also free FILE object.
1590 * It is disastrous if we share memory with a vforked parent.
1591 * I'm not sure we never come here after vfork.
1592 * Therefore just close fd, nothing more.
1593 */
1594 /*fclose(fl->fp); - unsafe */
1595 close(fl->fd);
1596 fl = fl->next;
1597 }
1598}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001599#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001600static int fd_in_FILEs(int fd)
1601{
1602 struct FILE_list *fl = G.FILE_list;
1603 while (fl) {
1604 if (fl->fd == fd)
1605 return 1;
1606 fl = fl->next;
1607 }
1608 return 0;
1609}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001610
1611
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001612/* Helpers for setting new $n and restoring them back
1613 */
1614typedef struct save_arg_t {
1615 char *sv_argv0;
1616 char **sv_g_argv;
1617 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001618 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001619} save_arg_t;
1620
1621static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1622{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001623 sv->sv_argv0 = argv[0];
1624 sv->sv_g_argv = G.global_argv;
1625 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001626 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001627
1628 argv[0] = G.global_argv[0]; /* retain $0 */
1629 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001630 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001631
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001632 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001633}
1634
1635static void restore_G_args(save_arg_t *sv, char **argv)
1636{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001637#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001638 if (G.global_args_malloced) {
1639 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001640 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001641 while (*++pp) /* note: does not free $0 */
1642 free(*pp);
1643 free(G.global_argv);
1644 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001645#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001646 argv[0] = sv->sv_argv0;
1647 G.global_argv = sv->sv_g_argv;
1648 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001649 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001650}
1651
1652
Denis Vlasenkod5762932009-03-31 11:22:57 +00001653/* Basic theory of signal handling in shell
1654 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001655 * This does not describe what hush does, rather, it is current understanding
1656 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001657 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1658 *
1659 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1660 * is finished or backgrounded. It is the same in interactive and
1661 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001662 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001663 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001664 * backgrounds (i.e. stops) or kills all members of currently running
1665 * pipe.
1666 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001667 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001668 * or by SIGINT in interactive shell.
1669 *
1670 * Trap handlers will execute even within trap handlers. (right?)
1671 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001672 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1673 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001674 *
1675 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001676 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001677 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001678 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001679 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001680 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001681 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001682 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001683 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001684 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001685 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001686 *
1687 * SIGQUIT: ignore
1688 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001689 * SIGHUP (interactive):
1690 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001691 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001692 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1693 * that all pipe members are stopped. Try this in bash:
1694 * while :; do :; done - ^Z does not background it
1695 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001696 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001697 * of the command line, show prompt. NB: ^C does not send SIGINT
1698 * to interactive shell while shell is waiting for a pipe,
1699 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001700 * Example 1: this waits 5 sec, but does not execute ls:
1701 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1702 * Example 2: this does not wait and does not execute ls:
1703 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1704 * Example 3: this does not wait 5 sec, but executes ls:
1705 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001706 * Example 4: this does not wait and does not execute ls:
1707 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001708 *
1709 * (What happens to signals which are IGN on shell start?)
1710 * (What happens with signal mask on shell start?)
1711 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001712 * Old implementation
1713 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001714 * We use in-kernel pending signal mask to determine which signals were sent.
1715 * We block all signals which we don't want to take action immediately,
1716 * i.e. we block all signals which need to have special handling as described
1717 * above, and all signals which have traps set.
1718 * After each pipe execution, we extract any pending signals via sigtimedwait()
1719 * and act on them.
1720 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001721 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 * sigset_t blocked_set: current blocked signal set
1723 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001724 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001725 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001726 * "trap 'cmd' SIGxxx":
1727 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001728 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001729 * unblock signals with special interactive handling
1730 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001731 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001732 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001733 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001734 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001735 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001736 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001737 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001738 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001739 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001740 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001741 * Standard says "When a subshell is entered, traps that are not being ignored
1742 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001743 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001744 *
1745 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001746 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001747 * masked signals are not visible!
1748 *
1749 * New implementation
1750 * ==================
1751 * We record each signal we are interested in by installing signal handler
1752 * for them - a bit like emulating kernel pending signal mask in userspace.
1753 * We are interested in: signals which need to have special handling
1754 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001755 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001756 * After each pipe execution, we extract any pending signals
1757 * and act on them.
1758 *
1759 * unsigned special_sig_mask: a mask of shell-special signals.
1760 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1761 * char *traps[sig] if trap for sig is set (even if it's '').
1762 * sigset_t pending_set: set of sigs we received.
1763 *
1764 * "trap - SIGxxx":
1765 * if sig is in special_sig_mask, set handler back to:
1766 * record_pending_signo, or to IGN if it's a tty stop signal
1767 * if sig is in fatal_sig_mask, set handler back to sigexit.
1768 * else: set handler back to SIG_DFL
1769 * "trap 'cmd' SIGxxx":
1770 * set handler to record_pending_signo.
1771 * "trap '' SIGxxx":
1772 * set handler to SIG_IGN.
1773 * after [v]fork, if we plan to be a shell:
1774 * set signals with special interactive handling to SIG_DFL
1775 * (because child shell is not interactive),
1776 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1777 * after [v]fork, if we plan to exec:
1778 * POSIX says fork clears pending signal mask in child - no need to clear it.
1779 *
1780 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1781 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1782 *
1783 * Note (compat):
1784 * Standard says "When a subshell is entered, traps that are not being ignored
1785 * are set to the default actions". bash interprets it so that traps which
1786 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001787 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001788enum {
1789 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001790 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001791 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001792 | (1 << SIGHUP)
1793 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001794 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001795#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001796 | (1 << SIGTTIN)
1797 | (1 << SIGTTOU)
1798 | (1 << SIGTSTP)
1799#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001800 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001801};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001802
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001803static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001804{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001805 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001806#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001807 if (sig == SIGCHLD) {
1808 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001809//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 +02001810 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001811#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001812}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001813
Denys Vlasenko0806e402011-05-12 23:06:20 +02001814static sighandler_t install_sighandler(int sig, sighandler_t handler)
1815{
1816 struct sigaction old_sa;
1817
1818 /* We could use signal() to install handlers... almost:
1819 * except that we need to mask ALL signals while handlers run.
1820 * I saw signal nesting in strace, race window isn't small.
1821 * SA_RESTART is also needed, but in Linux, signal()
1822 * sets SA_RESTART too.
1823 */
1824 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1825 /* sigfillset(&G.sa.sa_mask); - already done */
1826 /* G.sa.sa_flags = SA_RESTART; - already done */
1827 G.sa.sa_handler = handler;
1828 sigaction(sig, &G.sa, &old_sa);
1829 return old_sa.sa_handler;
1830}
1831
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001832static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001833
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001834static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001835static void restore_ttypgrp_and__exit(void)
1836{
1837 /* xfunc has failed! die die die */
1838 /* no EXIT traps, this is an escape hatch! */
1839 G.exiting = 1;
1840 hush_exit(xfunc_error_retval);
1841}
1842
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001843#if ENABLE_HUSH_JOB
1844
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001845/* Needed only on some libc:
1846 * It was observed that on exit(), fgetc'ed buffered data
1847 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1848 * With the net effect that even after fork(), not vfork(),
1849 * exit() in NOEXECed applet in "sh SCRIPT":
1850 * noexec_applet_here
1851 * echo END_OF_SCRIPT
1852 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1853 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001854 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001855 * and in `cmd` handling.
1856 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1857 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001858static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001859static void fflush_and__exit(void)
1860{
1861 fflush_all();
1862 _exit(xfunc_error_retval);
1863}
1864
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001865/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001866# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001867/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001868# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001869
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001870/* Restores tty foreground process group, and exits.
1871 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001872 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001873 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001874 * We also call it if xfunc is exiting.
1875 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001876static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001877static void sigexit(int sig)
1878{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001879 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001880 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001881 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1882 /* Disable all signals: job control, SIGPIPE, etc.
1883 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1884 */
1885 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001886 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001887 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001888
1889 /* Not a signal, just exit */
1890 if (sig <= 0)
1891 _exit(- sig);
1892
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001893 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001894}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001895#else
1896
Denys Vlasenko8391c482010-05-22 17:50:43 +02001897# define disable_restore_tty_pgrp_on_exit() ((void)0)
1898# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001899
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001900#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001901
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001902static sighandler_t pick_sighandler(unsigned sig)
1903{
1904 sighandler_t handler = SIG_DFL;
1905 if (sig < sizeof(unsigned)*8) {
1906 unsigned sigmask = (1 << sig);
1907
1908#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001909 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001910 if (G_fatal_sig_mask & sigmask)
1911 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001912 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001913#endif
1914 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001915 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001916 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001917 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001918 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001919 * in an endless loop when we try to do some
1920 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001921 */
1922 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1923 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001924 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001925 }
1926 return handler;
1927}
1928
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001929/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001930static void hush_exit(int exitcode)
1931{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001932#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1933 save_history(G.line_input_state);
1934#endif
1935
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001936 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001937 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001938 char *argv[3];
1939 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001940 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001941 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001942 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001943 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001944 * "trap" will still show it, if executed
1945 * in the handler */
1946 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001947 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001948
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001949#if ENABLE_FEATURE_CLEAN_UP
1950 {
1951 struct variable *cur_var;
1952 if (G.cwd != bb_msg_unknown)
1953 free((char*)G.cwd);
1954 cur_var = G.top_var;
1955 while (cur_var) {
1956 struct variable *tmp = cur_var;
1957 if (!cur_var->max_len)
1958 free(cur_var->varstr);
1959 cur_var = cur_var->next;
1960 free(tmp);
1961 }
1962 }
1963#endif
1964
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001965 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001966#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001967 sigexit(- (exitcode & 0xff));
1968#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001969 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001970#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001971}
1972
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001973
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001974//TODO: return a mask of ALL handled sigs?
1975static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001976{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001977 int last_sig = 0;
1978
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001979 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001980 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001981
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001982 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001983 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001984 sig = 0;
1985 do {
1986 sig++;
1987 if (sigismember(&G.pending_set, sig)) {
1988 sigdelset(&G.pending_set, sig);
1989 goto got_sig;
1990 }
1991 } while (sig < NSIG);
1992 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001993 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001994 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001995 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001996 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001997 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001998 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001999 char *argv[3];
2000 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002001 argv[1] = xstrdup(G_traps[sig]);
2002 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002003 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002004 save_rcode = G.last_exitcode;
2005 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002006 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002007//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002008 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002009 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002010 } /* else: "" trap, ignoring signal */
2011 continue;
2012 }
2013 /* not a trap: special action */
2014 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002015 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002016 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002017 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002018 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002019 break;
2020#if ENABLE_HUSH_JOB
2021 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002022//TODO: why are we doing this? ash and dash don't do this,
2023//they have no handler for SIGHUP at all,
2024//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002025 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002026 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002027 /* bash is observed to signal whole process groups,
2028 * not individual processes */
2029 for (job = G.job_list; job; job = job->next) {
2030 if (job->pgrp <= 0)
2031 continue;
2032 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2033 if (kill(- job->pgrp, SIGHUP) == 0)
2034 kill(- job->pgrp, SIGCONT);
2035 }
2036 sigexit(SIGHUP);
2037 }
2038#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002039#if ENABLE_HUSH_FAST
2040 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002041 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002042 G.count_SIGCHLD++;
2043//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2044 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002045 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002046 * This simplifies wait builtin a bit.
2047 */
2048 break;
2049#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002050 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002051 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002052 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002053 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002054 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002055 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002056 * in interactive shell, because TERM is ignored.
2057 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058 break;
2059 }
2060 }
2061 return last_sig;
2062}
2063
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002064
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002065static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002066{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002067 if (force || G.cwd == NULL) {
2068 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2069 * we must not try to free(bb_msg_unknown) */
2070 if (G.cwd == bb_msg_unknown)
2071 G.cwd = NULL;
2072 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2073 if (!G.cwd)
2074 G.cwd = bb_msg_unknown;
2075 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002076 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002077}
2078
Denis Vlasenko83506862007-11-23 13:11:42 +00002079
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002080/*
2081 * Shell and environment variable support
2082 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002083static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002084{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002085 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002086 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002087
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002088 pp = &G.top_var;
2089 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002090 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002091 return pp;
2092 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002093 }
2094 return NULL;
2095}
2096
Denys Vlasenko03dad222010-01-12 23:29:57 +01002097static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002098{
Denys Vlasenko29082232010-07-16 13:52:32 +02002099 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002100 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002101
2102 if (G.expanded_assignments) {
2103 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002104 while (*cpp) {
2105 char *cp = *cpp;
2106 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2107 return cp + len + 1;
2108 cpp++;
2109 }
2110 }
2111
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002112 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002113 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002114 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002115
Denys Vlasenkodea47882009-10-09 15:40:49 +02002116 if (strcmp(name, "PPID") == 0)
2117 return utoa(G.root_ppid);
2118 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002119#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002120 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002121 return utoa(next_random(&G.random_gen));
2122#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123 return NULL;
2124}
2125
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002126static void handle_changed_special_names(const char *name, unsigned name_len)
2127{
2128 if (name_len == 3 && name[0] == 'P' && name[1] == 'S') {
2129 cmdedit_update_prompt();
2130 return;
2131 }
2132
2133 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2134 && name_len == 6
2135 ) {
2136#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002137 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002138 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002139 return;
2140 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002141#endif
2142#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002143 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002144 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002145 return;
2146 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002147#endif
2148 }
2149}
2150
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002151/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002152 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002153 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002154#define SETFLAG_EXPORT (1 << 0)
2155#define SETFLAG_UNEXPORT (1 << 1)
2156#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002157#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002158static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159{
Denys Vlasenko61407802018-04-04 21:14:28 +02002160 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002161 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002162 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002163 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002164 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002165 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002166
Denis Vlasenko950bd722009-04-21 11:23:56 +00002167 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002168 if (HUSH_DEBUG && !eq_sign)
2169 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002170
Denis Vlasenko950bd722009-04-21 11:23:56 +00002171 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002172 cur_pp = &G.top_var;
2173 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002174 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002175 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002176 continue;
2177 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002178
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002179 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002180 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002181 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002182 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002183//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2184//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002185 return -1;
2186 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002187 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002188 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2189 *eq_sign = '\0';
2190 unsetenv(str);
2191 *eq_sign = '=';
2192 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002193 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002194 /* bash 3.2.33(1) and exported vars:
2195 * # export z=z
2196 * # f() { local z=a; env | grep ^z; }
2197 * # f
2198 * z=a
2199 * # env | grep ^z
2200 * z=z
2201 */
2202 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002203 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002204 /* New variable is local ("local VAR=VAL" or
2205 * "VAR=VAL cmd")
2206 * and existing one is global, or local
2207 * on a lower level that new one.
2208 * Remove it from global variable list:
2209 */
2210 *cur_pp = cur->next;
2211 if (G.shadowed_vars_pp) {
2212 /* Save in "shadowed" list */
2213 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2214 cur->flg_export ? "exported " : "",
2215 cur->varstr, cur->var_nest_level, str, local_lvl
2216 );
2217 cur->next = *G.shadowed_vars_pp;
2218 *G.shadowed_vars_pp = cur;
2219 } else {
2220 /* Came from pseudo_exec_argv(), no need to save: delete it */
2221 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2222 cur->flg_export ? "exported " : "",
2223 cur->varstr, cur->var_nest_level, str, local_lvl
2224 );
2225 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2226 free_me = cur->varstr; /* then free it later */
2227 free(cur);
2228 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002229 break;
2230 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002231
Denis Vlasenko950bd722009-04-21 11:23:56 +00002232 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002233 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002234 free_and_exp:
2235 free(str);
2236 goto exp;
2237 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002238
2239 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002240 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002241 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002242 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002243 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002244 strcpy(cur->varstr, str);
2245 goto free_and_exp;
2246 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002247 /* Can't reuse */
2248 cur->max_len = 0;
2249 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002250 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002251 /* max_len == 0 signifies "malloced" var, which we can
2252 * (and have to) free. But we can't free(cur->varstr) here:
2253 * if cur->flg_export is 1, it is in the environment.
2254 * We should either unsetenv+free, or wait until putenv,
2255 * then putenv(new)+free(old).
2256 */
2257 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002258 goto set_str_and_exp;
2259 }
2260
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002261 /* Not found or shadowed - create new variable struct */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002262 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002263 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002264 cur->next = *cur_pp;
2265 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266
2267 set_str_and_exp:
2268 cur->varstr = str;
2269 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002270#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002271 if (flags & SETFLAG_MAKE_RO) {
2272 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002273 }
2274#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002275 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002276 cur->flg_export = 1;
2277 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002278 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002279 cur->flg_export = 0;
2280 /* unsetenv was already done */
2281 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002282 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002283 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002284 i = putenv(cur->varstr);
2285 /* only now we can free old exported malloced string */
2286 free(free_me);
2287 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002288 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002290 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002291
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002292 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002293
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002294 return 0;
2295}
2296
Denys Vlasenko6db47842009-09-05 20:15:17 +02002297/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002298static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002299{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002300 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002301}
2302
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002303static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002304{
2305 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002306 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002307
2308 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002309 return EXIT_SUCCESS;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002310
Denys Vlasenko61407802018-04-04 21:14:28 +02002311 cur_pp = &G.top_var;
2312 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002313 if (strncmp(cur->varstr, name, name_len) == 0
2314 && cur->varstr[name_len] == '='
2315 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002316 if (cur->flg_read_only) {
2317 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002318 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002319 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002320
Denys Vlasenko61407802018-04-04 21:14:28 +02002321 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2323 bb_unsetenv(cur->varstr);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002324
2325 handle_changed_special_names(name, name_len);
2326
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327 if (!cur->max_len)
2328 free(cur->varstr);
2329 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002330
Mike Frysingerd690f682009-03-30 06:50:54 +00002331 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002332 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002333 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002334 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002335 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336}
2337
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002338#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002339static int unset_local_var(const char *name)
2340{
2341 return unset_local_var_len(name, strlen(name));
2342}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002343#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002344
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002345#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002346static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002347{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002348 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002349 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002350}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002351#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002352
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002353
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002354/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002355 * Helpers for "var1=val1 var2=val2 cmd" feature
2356 */
2357static void add_vars(struct variable *var)
2358{
2359 struct variable *next;
2360
2361 while (var) {
2362 next = var->next;
2363 var->next = G.top_var;
2364 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002365 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002366 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002367 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002368 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002369 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002370 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002371 var = next;
2372 }
2373}
2374
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002375/* We put strings[i] into variable table and possibly putenv them.
2376 * If variable is read only, we can free the strings[i]
2377 * which attempts to overwrite it.
2378 * The strings[] vector itself is freed.
2379 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002380static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002381{
2382 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002383
2384 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002385 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002386
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002387 s = strings;
2388 while (*s) {
2389 struct variable *var_p;
2390 struct variable **var_pp;
2391 char *eq;
2392
2393 eq = strchr(*s, '=');
2394 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002395 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002396 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002397 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002398 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002399 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002400 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002401 /*
2402 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2403 * If VAR is readonly, leaving it in the list
2404 * after asssignment error (msg above)
2405 * causes doubled error message later, on unset.
2406 */
2407 debug_printf_env("removing/freeing '%s' element\n", *s);
2408 free(*s);
2409 p = s;
2410 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002411 goto next;
2412 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002413 /* below, set_local_var() with nest level will
2414 * "shadow" (remove) this variable from
2415 * global linked list.
2416 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002417 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002418 //bb_error_msg("G.var_nest_level:%d", G.var_nest_level);
2419 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2420 } else if (HUSH_DEBUG) {
2421 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002422 }
2423 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002424 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002425 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002426 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002427}
2428
2429
2430/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002431 * Unicode helper
2432 */
2433static void reinit_unicode_for_hush(void)
2434{
2435 /* Unicode support should be activated even if LANG is set
2436 * _during_ shell execution, not only if it was set when
2437 * shell was started. Therefore, re-check LANG every time:
2438 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002439 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2440 || ENABLE_UNICODE_USING_LOCALE
2441 ) {
2442 const char *s = get_local_var_value("LC_ALL");
2443 if (!s) s = get_local_var_value("LC_CTYPE");
2444 if (!s) s = get_local_var_value("LANG");
2445 reinit_unicode(s);
2446 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002447}
2448
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002449/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002450 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002452
2453#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002454/* To test correct lineedit/interactive behavior, type from command line:
2455 * echo $P\
2456 * \
2457 * AT\
2458 * H\
2459 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002460 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002461 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002462static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002464 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002465 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002466 if (G.PS1 == NULL)
2467 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002468 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002469 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002470 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002471 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002472 if (G.PS2 == NULL)
2473 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002474}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002475static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002476{
2477 const char *prompt_str;
2478 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002479 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2480 /* Set up the prompt */
2481 if (promptmode == 0) { /* PS1 */
2482 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002483 /* bash uses $PWD value, even if it is set by user.
2484 * It uses current dir only if PWD is unset.
2485 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002486 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002487 prompt_str = G.PS1;
2488 } else
2489 prompt_str = G.PS2;
2490 } else
2491 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002492 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002493 return prompt_str;
2494}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002495static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002496{
2497 int r;
2498 const char *prompt_str;
2499
2500 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002501# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002502 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002503 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002504 if (G.flag_SIGINT) {
2505 /* There was ^C'ed, make it look prettier: */
2506 bb_putchar('\n');
2507 G.flag_SIGINT = 0;
2508 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002509 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002510 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002511 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002512 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002513 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002514 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002515 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002516 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002517 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002518 if (r != 0 && !G.flag_SIGINT)
2519 break;
2520 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002521 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2522 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002523 G.last_exitcode = 128 + SIGINT;
2524 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002525 if (r < 0) {
2526 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002527 i->p = NULL;
2528 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002529 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002530 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002531 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002532 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002533# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002534 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002535 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002536 if (i->last_char == '\0' || i->last_char == '\n') {
2537 /* Why check_and_run_traps here? Try this interactively:
2538 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2539 * $ <[enter], repeatedly...>
2540 * Without check_and_run_traps, handler never runs.
2541 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002542 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002543 fputs(prompt_str, stdout);
2544 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002545 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002546//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002547 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002548 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2549 * no ^C masking happens during fgetc, no special code for ^C:
2550 * it generates SIGINT as usual.
2551 */
2552 check_and_run_traps();
2553 if (G.flag_SIGINT)
2554 G.last_exitcode = 128 + SIGINT;
2555 if (r != '\0')
2556 break;
2557 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002558 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002559# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002560}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561/* This is the magic location that prints prompts
2562 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002563static int fgetc_interactive(struct in_str *i)
2564{
2565 int ch;
2566 /* If it's interactive stdin, get new line. */
2567 if (G_interactive_fd && i->file == stdin) {
2568 /* Returns first char (or EOF), the rest is in i->p[] */
2569 ch = get_user_input(i);
2570 i->promptmode = 1; /* PS2 */
2571 } else {
2572 /* Not stdin: script file, sourced file, etc */
2573 do ch = fgetc(i->file); while (ch == '\0');
2574 }
2575 return ch;
2576}
2577#else
2578static inline int fgetc_interactive(struct in_str *i)
2579{
2580 int ch;
2581 do ch = fgetc(i->file); while (ch == '\0');
2582 return ch;
2583}
2584#endif /* INTERACTIVE */
2585
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002586static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002587{
2588 int ch;
2589
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002590 if (!i->file) {
2591 /* string-based in_str */
2592 ch = (unsigned char)*i->p;
2593 if (ch != '\0') {
2594 i->p++;
2595 i->last_char = ch;
2596 return ch;
2597 }
2598 return EOF;
2599 }
2600
2601 /* FILE-based in_str */
2602
Denys Vlasenko4074d492016-09-30 01:49:53 +02002603#if ENABLE_FEATURE_EDITING
2604 /* This can be stdin, check line editing char[] buffer */
2605 if (i->p && *i->p != '\0') {
2606 ch = (unsigned char)*i->p++;
2607 goto out;
2608 }
2609#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002610 /* peek_buf[] is an int array, not char. Can contain EOF. */
2611 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002612 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002613 int ch2 = i->peek_buf[1];
2614 i->peek_buf[0] = ch2;
2615 if (ch2 == 0) /* very likely, avoid redundant write */
2616 goto out;
2617 i->peek_buf[1] = 0;
2618 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002620
Denys Vlasenko4074d492016-09-30 01:49:53 +02002621 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002622 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002623 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002624 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002625#if ENABLE_HUSH_LINENO_VAR
2626 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002627 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002628 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2629 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002630#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002631 return ch;
2632}
2633
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002634static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002635{
2636 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002637
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002638 if (!i->file) {
2639 /* string-based in_str */
2640 /* Doesn't report EOF on NUL. None of the callers care. */
2641 return (unsigned char)*i->p;
2642 }
2643
2644 /* FILE-based in_str */
2645
Denys Vlasenko4074d492016-09-30 01:49:53 +02002646#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002647 /* This can be stdin, check line editing char[] buffer */
2648 if (i->p && *i->p != '\0')
2649 return (unsigned char)*i->p;
2650#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002651 /* peek_buf[] is an int array, not char. Can contain EOF. */
2652 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002653 if (ch != 0)
2654 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002655
Denys Vlasenko4074d492016-09-30 01:49:53 +02002656 /* Need to get a new char */
2657 ch = fgetc_interactive(i);
2658 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2659
2660 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2661#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2662 if (i->p) {
2663 i->p -= 1;
2664 return ch;
2665 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002666#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002667 i->peek_buf[0] = ch;
2668 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002669 return ch;
2670}
2671
Denys Vlasenko4074d492016-09-30 01:49:53 +02002672/* Only ever called if i_peek() was called, and did not return EOF.
2673 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2674 * not end-of-line. Therefore we never need to read a new editing line here.
2675 */
2676static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002677{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002678 int ch;
2679
2680 /* There are two cases when i->p[] buffer exists.
2681 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002682 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002683 * In both cases, we know that i->p[0] exists and not NUL, and
2684 * the peek2 result is in i->p[1].
2685 */
2686 if (i->p)
2687 return (unsigned char)i->p[1];
2688
2689 /* Now we know it is a file-based in_str. */
2690
2691 /* peek_buf[] is an int array, not char. Can contain EOF. */
2692 /* Is there 2nd char? */
2693 ch = i->peek_buf[1];
2694 if (ch == 0) {
2695 /* We did not read it yet, get it now */
2696 do ch = fgetc(i->file); while (ch == '\0');
2697 i->peek_buf[1] = ch;
2698 }
2699
2700 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2701 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002702}
2703
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002704static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2705{
2706 for (;;) {
2707 int ch, ch2;
2708
2709 ch = i_getch(input);
2710 if (ch != '\\')
2711 return ch;
2712 ch2 = i_peek(input);
2713 if (ch2 != '\n')
2714 return ch;
2715 /* backslash+newline, skip it */
2716 i_getch(input);
2717 }
2718}
2719
2720/* Note: this function _eats_ \<newline> pairs, safe to use plain
2721 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2722 */
2723static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2724{
2725 for (;;) {
2726 int ch, ch2;
2727
2728 ch = i_peek(input);
2729 if (ch != '\\')
2730 return ch;
2731 ch2 = i_peek2(input);
2732 if (ch2 != '\n')
2733 return ch;
2734 /* backslash+newline, skip it */
2735 i_getch(input);
2736 i_getch(input);
2737 }
2738}
2739
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002740static void setup_file_in_str(struct in_str *i, FILE *f)
2741{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002742 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002743 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002744 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002745 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002746}
2747
2748static void setup_string_in_str(struct in_str *i, const char *s)
2749{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002750 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002751 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002752 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002753 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002754}
2755
2756
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002757/*
2758 * o_string support
2759 */
2760#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002761
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002762static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002763{
2764 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002765 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002766 if (o->data)
2767 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002768}
2769
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002770static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002771{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002772 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002773 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002774}
2775
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002776static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2777{
2778 free(o->data);
2779}
2780
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002781static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002782{
2783 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002784 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002785 o->data = xrealloc(o->data, 1 + o->maxlen);
2786 }
2787}
2788
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002789static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002790{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002791 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002792 if (o->length < o->maxlen) {
2793 /* likely. avoid o_grow_by() call */
2794 add:
2795 o->data[o->length] = ch;
2796 o->length++;
2797 o->data[o->length] = '\0';
2798 return;
2799 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002800 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002801 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002802}
2803
Denys Vlasenko657086a2016-09-29 18:07:42 +02002804#if 0
2805/* Valid only if we know o_string is not empty */
2806static void o_delchr(o_string *o)
2807{
2808 o->length--;
2809 o->data[o->length] = '\0';
2810}
2811#endif
2812
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002813static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002814{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002815 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002816 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002817 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002818}
2819
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002820static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002821{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002822 o_addblock(o, str, strlen(str));
2823}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002824
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002825#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002826static void nommu_addchr(o_string *o, int ch)
2827{
2828 if (o)
2829 o_addchr(o, ch);
2830}
2831#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002832# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002833#endif
2834
2835static void o_addstr_with_NUL(o_string *o, const char *str)
2836{
2837 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002838}
2839
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002840/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002841 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002842 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2843 * Apparently, on unquoted $v bash still does globbing
2844 * ("v='*.txt'; echo $v" prints all .txt files),
2845 * but NOT brace expansion! Thus, there should be TWO independent
2846 * quoting mechanisms on $v expansion side: one protects
2847 * $v from brace expansion, and other additionally protects "$v" against globbing.
2848 * We have only second one.
2849 */
2850
Denys Vlasenko9e800222010-10-03 14:28:04 +02002851#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002852# define MAYBE_BRACES "{}"
2853#else
2854# define MAYBE_BRACES ""
2855#endif
2856
Eric Andersen25f27032001-04-26 23:22:31 +00002857/* My analysis of quoting semantics tells me that state information
2858 * is associated with a destination, not a source.
2859 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002860static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002861{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002862 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002863 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002864 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002865 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002866 o_grow_by(o, sz);
2867 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002868 o->data[o->length] = '\\';
2869 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002870 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002871 o->data[o->length] = ch;
2872 o->length++;
2873 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002874}
2875
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002876static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002877{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002878 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002879 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2880 && strchr("*?[\\" MAYBE_BRACES, ch)
2881 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002882 sz++;
2883 o->data[o->length] = '\\';
2884 o->length++;
2885 }
2886 o_grow_by(o, sz);
2887 o->data[o->length] = ch;
2888 o->length++;
2889 o->data[o->length] = '\0';
2890}
2891
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002892static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002893{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002894 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002895 char ch;
2896 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002897 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002898 if (ordinary_cnt > len) /* paranoia */
2899 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002900 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002901 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002902 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002903 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002904 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002905
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002906 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002907 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002908 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002909 sz++;
2910 o->data[o->length] = '\\';
2911 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002912 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 o_grow_by(o, sz);
2914 o->data[o->length] = ch;
2915 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002916 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002917 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002918}
2919
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002920static void o_addQblock(o_string *o, const char *str, int len)
2921{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002922 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002923 o_addblock(o, str, len);
2924 return;
2925 }
2926 o_addqblock(o, str, len);
2927}
2928
Denys Vlasenko38292b62010-09-05 14:49:40 +02002929static void o_addQstr(o_string *o, const char *str)
2930{
2931 o_addQblock(o, str, strlen(str));
2932}
2933
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002934/* A special kind of o_string for $VAR and `cmd` expansion.
2935 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002936 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002937 * list[i] contains an INDEX (int!) into this string data.
2938 * It means that if list[] needs to grow, data needs to be moved higher up
2939 * but list[i]'s need not be modified.
2940 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002941 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002942 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2943 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002944#if DEBUG_EXPAND || DEBUG_GLOB
2945static void debug_print_list(const char *prefix, o_string *o, int n)
2946{
2947 char **list = (char**)o->data;
2948 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2949 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002950
2951 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002952 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 +02002953 prefix, list, n, string_start, o->length, o->maxlen,
2954 !!(o->o_expflags & EXP_FLAG_GLOB),
2955 o->has_quoted_part,
2956 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002957 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002958 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002959 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2960 o->data + (int)(uintptr_t)list[i] + string_start,
2961 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002962 i++;
2963 }
2964 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002965 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002966 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002967 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002968 }
2969}
2970#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002971# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002972#endif
2973
2974/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2975 * in list[n] so that it points past last stored byte so far.
2976 * It returns n+1. */
2977static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002978{
2979 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002980 int string_start;
2981 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002982
2983 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002984 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2985 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002986 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002987 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002988 /* list[n] points to string_start, make space for 16 more pointers */
2989 o->maxlen += 0x10 * sizeof(list[0]);
2990 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002991 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002992 memmove(list + n + 0x10, list + n, string_len);
2993 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002994 } else {
2995 debug_printf_list("list[%d]=%d string_start=%d\n",
2996 n, string_len, string_start);
2997 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002998 } else {
2999 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003000 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3001 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003002 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3003 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003004 o->has_empty_slot = 0;
3005 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003006 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003007 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003008 return n + 1;
3009}
3010
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003011/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003012static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003013{
3014 char **list = (char**)o->data;
3015 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3016
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003017 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003018}
3019
Denys Vlasenko9e800222010-10-03 14:28:04 +02003020#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003021/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3022 * first, it processes even {a} (no commas), second,
3023 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003024 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003025 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003026
3027/* Helper */
3028static int glob_needed(const char *s)
3029{
3030 while (*s) {
3031 if (*s == '\\') {
3032 if (!s[1])
3033 return 0;
3034 s += 2;
3035 continue;
3036 }
3037 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3038 return 1;
3039 s++;
3040 }
3041 return 0;
3042}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003043/* Return pointer to next closing brace or to comma */
3044static const char *next_brace_sub(const char *cp)
3045{
3046 unsigned depth = 0;
3047 cp++;
3048 while (*cp != '\0') {
3049 if (*cp == '\\') {
3050 if (*++cp == '\0')
3051 break;
3052 cp++;
3053 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003054 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003055 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003056 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003057 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003058 depth++;
3059 }
3060
3061 return *cp != '\0' ? cp : NULL;
3062}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003063/* Recursive brace globber. Note: may garble pattern[]. */
3064static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003065{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003066 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003067 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003068 const char *next;
3069 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003070 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003071 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003072
3073 debug_printf_glob("glob_brace('%s')\n", pattern);
3074
3075 begin = pattern;
3076 while (1) {
3077 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003078 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003079 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003080 /* Find the first sub-pattern and at the same time
3081 * find the rest after the closing brace */
3082 next = next_brace_sub(begin);
3083 if (next == NULL) {
3084 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003085 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003086 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003087 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003088 /* "{abc}" with no commas - illegal
3089 * brace expr, disregard and skip it */
3090 begin = next + 1;
3091 continue;
3092 }
3093 break;
3094 }
3095 if (*begin == '\\' && begin[1] != '\0')
3096 begin++;
3097 begin++;
3098 }
3099 debug_printf_glob("begin:%s\n", begin);
3100 debug_printf_glob("next:%s\n", next);
3101
3102 /* Now find the end of the whole brace expression */
3103 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003104 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003105 rest = next_brace_sub(rest);
3106 if (rest == NULL) {
3107 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003108 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003109 }
3110 debug_printf_glob("rest:%s\n", rest);
3111 }
3112 rest_len = strlen(++rest) + 1;
3113
3114 /* We are sure the brace expression is well-formed */
3115
3116 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003117 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003118
3119 /* We have a brace expression. BEGIN points to the opening {,
3120 * NEXT points past the terminator of the first element, and REST
3121 * points past the final }. We will accumulate result names from
3122 * recursive runs for each brace alternative in the buffer using
3123 * GLOB_APPEND. */
3124
3125 p = begin + 1;
3126 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003127 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003128 memcpy(
3129 mempcpy(
3130 mempcpy(new_pattern_buf,
3131 /* We know the prefix for all sub-patterns */
3132 pattern, begin - pattern),
3133 p, next - p),
3134 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003135
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003136 /* Note: glob_brace() may garble new_pattern_buf[].
3137 * That's why we re-copy prefix every time (1st memcpy above).
3138 */
3139 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003140 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003141 /* We saw the last entry */
3142 break;
3143 }
3144 p = next + 1;
3145 next = next_brace_sub(next);
3146 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003147 free(new_pattern_buf);
3148 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003149
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003150 simple_glob:
3151 {
3152 int gr;
3153 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003154
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003155 memset(&globdata, 0, sizeof(globdata));
3156 gr = glob(pattern, 0, NULL, &globdata);
3157 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3158 if (gr != 0) {
3159 if (gr == GLOB_NOMATCH) {
3160 globfree(&globdata);
3161 /* NB: garbles parameter */
3162 unbackslash(pattern);
3163 o_addstr_with_NUL(o, pattern);
3164 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3165 return o_save_ptr_helper(o, n);
3166 }
3167 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003168 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003169 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3170 * but we didn't specify it. Paranoia again. */
3171 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3172 }
3173 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3174 char **argv = globdata.gl_pathv;
3175 while (1) {
3176 o_addstr_with_NUL(o, *argv);
3177 n = o_save_ptr_helper(o, n);
3178 argv++;
3179 if (!*argv)
3180 break;
3181 }
3182 }
3183 globfree(&globdata);
3184 }
3185 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003186}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003187/* Performs globbing on last list[],
3188 * saving each result as a new list[].
3189 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003190static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003191{
3192 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003193
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003194 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003195 if (!o->data)
3196 return o_save_ptr_helper(o, n);
3197 pattern = o->data + o_get_last_ptr(o, n);
3198 debug_printf_glob("glob pattern '%s'\n", pattern);
3199 if (!glob_needed(pattern)) {
3200 /* unbackslash last string in o in place, fix length */
3201 o->length = unbackslash(pattern) - o->data;
3202 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3203 return o_save_ptr_helper(o, n);
3204 }
3205
3206 copy = xstrdup(pattern);
3207 /* "forget" pattern in o */
3208 o->length = pattern - o->data;
3209 n = glob_brace(copy, o, n);
3210 free(copy);
3211 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003212 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003213 return n;
3214}
3215
Denys Vlasenko238081f2010-10-03 14:26:26 +02003216#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003217
3218/* Helper */
3219static int glob_needed(const char *s)
3220{
3221 while (*s) {
3222 if (*s == '\\') {
3223 if (!s[1])
3224 return 0;
3225 s += 2;
3226 continue;
3227 }
3228 if (*s == '*' || *s == '[' || *s == '?')
3229 return 1;
3230 s++;
3231 }
3232 return 0;
3233}
3234/* Performs globbing on last list[],
3235 * saving each result as a new list[].
3236 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003237static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003238{
3239 glob_t globdata;
3240 int gr;
3241 char *pattern;
3242
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003243 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003244 if (!o->data)
3245 return o_save_ptr_helper(o, n);
3246 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003247 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003248 if (!glob_needed(pattern)) {
3249 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003250 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003251 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003252 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003253 return o_save_ptr_helper(o, n);
3254 }
3255
3256 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003257 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3258 * If we glob "*.\*" and don't find anything, we need
3259 * to fall back to using literal "*.*", but GLOB_NOCHECK
3260 * will return "*.\*"!
3261 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003262 gr = glob(pattern, 0, NULL, &globdata);
3263 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003264 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003265 if (gr == GLOB_NOMATCH) {
3266 globfree(&globdata);
3267 goto literal;
3268 }
3269 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003270 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003271 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3272 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003273 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003274 }
3275 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3276 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003277 /* "forget" pattern in o */
3278 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003279 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003280 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003281 n = o_save_ptr_helper(o, n);
3282 argv++;
3283 if (!*argv)
3284 break;
3285 }
3286 }
3287 globfree(&globdata);
3288 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003289 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003290 return n;
3291}
3292
Denys Vlasenko238081f2010-10-03 14:26:26 +02003293#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003294
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003295/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003296 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003297static int o_save_ptr(o_string *o, int n)
3298{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003299 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003300 /* If o->has_empty_slot, list[n] was already globbed
3301 * (if it was requested back then when it was filled)
3302 * so don't do that again! */
3303 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003304 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003305 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003306 return o_save_ptr_helper(o, n);
3307}
3308
3309/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003310static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003311{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003312 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003313 int string_start;
3314
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003315 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3316 if (DEBUG_EXPAND)
3317 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003318 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003319 list = (char**)o->data;
3320 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3321 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003322 while (n) {
3323 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003324 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003325 }
3326 return list;
3327}
3328
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003329static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003330
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003331/* Returns pi->next - next pipe in the list */
3332static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003333{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003334 struct pipe *next;
3335 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003336
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003337 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003338 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003339 struct command *command;
3340 struct redir_struct *r, *rnext;
3341
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003342 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003343 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003344 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003345 if (DEBUG_CLEAN) {
3346 int a;
3347 char **p;
3348 for (a = 0, p = command->argv; *p; a++, p++) {
3349 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3350 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003351 }
3352 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003353 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003354 }
3355 /* not "else if": on syntax error, we may have both! */
3356 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003357 debug_printf_clean(" begin group (cmd_type:%d)\n",
3358 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003359 free_pipe_list(command->group);
3360 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003361 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003362 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003363 /* else is crucial here.
3364 * If group != NULL, child_func is meaningless */
3365#if ENABLE_HUSH_FUNCTIONS
3366 else if (command->child_func) {
3367 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3368 command->child_func->parent_cmd = NULL;
3369 }
3370#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003371#if !BB_MMU
3372 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003373 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003374#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003375 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003376 debug_printf_clean(" redirect %d%s",
3377 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003378 /* guard against the case >$FOO, where foo is unset or blank */
3379 if (r->rd_filename) {
3380 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3381 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003382 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003383 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003384 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003385 rnext = r->next;
3386 free(r);
3387 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003388 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003389 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003390 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003391 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003392#if ENABLE_HUSH_JOB
3393 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003394 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003395#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003396
3397 next = pi->next;
3398 free(pi);
3399 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003400}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003401
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003402static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003403{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003404 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003405#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003406 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003407#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003408 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003409 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003410 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003411}
3412
3413
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003414/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003415
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003416#ifndef debug_print_tree
3417static void debug_print_tree(struct pipe *pi, int lvl)
3418{
3419 static const char *const PIPE[] = {
3420 [PIPE_SEQ] = "SEQ",
3421 [PIPE_AND] = "AND",
3422 [PIPE_OR ] = "OR" ,
3423 [PIPE_BG ] = "BG" ,
3424 };
3425 static const char *RES[] = {
3426 [RES_NONE ] = "NONE" ,
3427# if ENABLE_HUSH_IF
3428 [RES_IF ] = "IF" ,
3429 [RES_THEN ] = "THEN" ,
3430 [RES_ELIF ] = "ELIF" ,
3431 [RES_ELSE ] = "ELSE" ,
3432 [RES_FI ] = "FI" ,
3433# endif
3434# if ENABLE_HUSH_LOOPS
3435 [RES_FOR ] = "FOR" ,
3436 [RES_WHILE] = "WHILE",
3437 [RES_UNTIL] = "UNTIL",
3438 [RES_DO ] = "DO" ,
3439 [RES_DONE ] = "DONE" ,
3440# endif
3441# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3442 [RES_IN ] = "IN" ,
3443# endif
3444# if ENABLE_HUSH_CASE
3445 [RES_CASE ] = "CASE" ,
3446 [RES_CASE_IN ] = "CASE_IN" ,
3447 [RES_MATCH] = "MATCH",
3448 [RES_CASE_BODY] = "CASE_BODY",
3449 [RES_ESAC ] = "ESAC" ,
3450# endif
3451 [RES_XXXX ] = "XXXX" ,
3452 [RES_SNTX ] = "SNTX" ,
3453 };
3454 static const char *const CMDTYPE[] = {
3455 "{}",
3456 "()",
3457 "[noglob]",
3458# if ENABLE_HUSH_FUNCTIONS
3459 "func()",
3460# endif
3461 };
3462
3463 int pin, prn;
3464
3465 pin = 0;
3466 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003467 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3468 lvl*2, "",
3469 pin,
3470 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3471 RES[pi->res_word],
3472 pi->followup, PIPE[pi->followup]
3473 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003474 prn = 0;
3475 while (prn < pi->num_cmds) {
3476 struct command *command = &pi->cmds[prn];
3477 char **argv = command->argv;
3478
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003479 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003480 lvl*2, "", prn,
3481 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003482#if ENABLE_HUSH_LINENO_VAR
3483 fdprintf(2, " LINENO:%u", command->lineno);
3484#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003485 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003486 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003487 CMDTYPE[command->cmd_type],
3488 argv
3489# if !BB_MMU
3490 , " group_as_string:", command->group_as_string
3491# else
3492 , "", ""
3493# endif
3494 );
3495 debug_print_tree(command->group, lvl+1);
3496 prn++;
3497 continue;
3498 }
3499 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003500 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003501 argv++;
3502 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003503 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003504 prn++;
3505 }
3506 pi = pi->next;
3507 pin++;
3508 }
3509}
3510#endif /* debug_print_tree */
3511
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003512static struct pipe *new_pipe(void)
3513{
Eric Andersen25f27032001-04-26 23:22:31 +00003514 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003515 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003516 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003517 return pi;
3518}
3519
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003520/* Command (member of a pipe) is complete, or we start a new pipe
3521 * if ctx->command is NULL.
3522 * No errors possible here.
3523 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003524static int done_command(struct parse_context *ctx)
3525{
3526 /* The command is really already in the pipe structure, so
3527 * advance the pipe counter and make a new, null command. */
3528 struct pipe *pi = ctx->pipe;
3529 struct command *command = ctx->command;
3530
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003531#if 0 /* Instead we emit error message at run time */
3532 if (ctx->pending_redirect) {
3533 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003534 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003535 ctx->pending_redirect = NULL;
3536 }
3537#endif
3538
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003539 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003540 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003541 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003542 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003543 }
3544 pi->num_cmds++;
3545 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003546 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003547 } else {
3548 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3549 }
3550
3551 /* Only real trickiness here is that the uncommitted
3552 * command structure is not counted in pi->num_cmds. */
3553 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003554 ctx->command = command = &pi->cmds[pi->num_cmds];
3555 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003556 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003557#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003558 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003559 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003560#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003561 return pi->num_cmds; /* used only for 0/nonzero check */
3562}
3563
3564static void done_pipe(struct parse_context *ctx, pipe_style type)
3565{
3566 int not_null;
3567
3568 debug_printf_parse("done_pipe entered, followup %d\n", type);
3569 /* Close previous command */
3570 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003571#if HAS_KEYWORDS
3572 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3573 ctx->ctx_inverted = 0;
3574 ctx->pipe->res_word = ctx->ctx_res_w;
3575#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003576 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3577 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003578 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3579 * in a backgrounded subshell.
3580 */
3581 struct pipe *pi;
3582 struct command *command;
3583
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003584 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003585 pi = ctx->list_head;
3586 while (pi != ctx->pipe) {
3587 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3588 goto no_conv;
3589 pi = pi->next;
3590 }
3591
3592 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3593 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3594 pi = xzalloc(sizeof(*pi));
3595 pi->followup = PIPE_BG;
3596 pi->num_cmds = 1;
3597 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3598 command = &pi->cmds[0];
3599 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3600 command->cmd_type = CMD_NORMAL;
3601 command->group = ctx->list_head;
3602#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003603 command->group_as_string = xstrndup(
3604 ctx->as_string.data,
3605 ctx->as_string.length - 1 /* do not copy last char, "&" */
3606 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003607#endif
3608 /* Replace all pipes in ctx with one newly created */
3609 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003610 } else {
3611 no_conv:
3612 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003613 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003614
3615 /* Without this check, even just <enter> on command line generates
3616 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003617 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003618 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003619#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003620 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003621#endif
3622#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003623 || ctx->ctx_res_w == RES_DONE
3624 || ctx->ctx_res_w == RES_FOR
3625 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003626#endif
3627#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003628 || ctx->ctx_res_w == RES_ESAC
3629#endif
3630 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003631 struct pipe *new_p;
3632 debug_printf_parse("done_pipe: adding new pipe: "
3633 "not_null:%d ctx->ctx_res_w:%d\n",
3634 not_null, ctx->ctx_res_w);
3635 new_p = new_pipe();
3636 ctx->pipe->next = new_p;
3637 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003638 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003639 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003640 * This is used to control execution.
3641 * RES_FOR and RES_IN are NOT sticky (needed to support
3642 * cases where variable or value happens to match a keyword):
3643 */
3644#if ENABLE_HUSH_LOOPS
3645 if (ctx->ctx_res_w == RES_FOR
3646 || ctx->ctx_res_w == RES_IN)
3647 ctx->ctx_res_w = RES_NONE;
3648#endif
3649#if ENABLE_HUSH_CASE
3650 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003651 ctx->ctx_res_w = RES_CASE_BODY;
3652 if (ctx->ctx_res_w == RES_CASE)
3653 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003654#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003655 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003656 /* Create the memory for command, roughly:
3657 * ctx->pipe->cmds = new struct command;
3658 * ctx->command = &ctx->pipe->cmds[0];
3659 */
3660 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003661 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003662 }
3663 debug_printf_parse("done_pipe return\n");
3664}
3665
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003666static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003667{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003668 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003669 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003670 /* Create the memory for command, roughly:
3671 * ctx->pipe->cmds = new struct command;
3672 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003673 */
3674 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003675}
3676
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003677/* If a reserved word is found and processed, parse context is modified
3678 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003679 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003680#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003681struct reserved_combo {
3682 char literal[6];
3683 unsigned char res;
3684 unsigned char assignment_flag;
3685 int flag;
3686};
3687enum {
3688 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003689# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003690 FLAG_IF = (1 << RES_IF ),
3691 FLAG_THEN = (1 << RES_THEN ),
3692 FLAG_ELIF = (1 << RES_ELIF ),
3693 FLAG_ELSE = (1 << RES_ELSE ),
3694 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003695# endif
3696# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003697 FLAG_FOR = (1 << RES_FOR ),
3698 FLAG_WHILE = (1 << RES_WHILE),
3699 FLAG_UNTIL = (1 << RES_UNTIL),
3700 FLAG_DO = (1 << RES_DO ),
3701 FLAG_DONE = (1 << RES_DONE ),
3702 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003703# endif
3704# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003705 FLAG_MATCH = (1 << RES_MATCH),
3706 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003707# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003708 FLAG_START = (1 << RES_XXXX ),
3709};
3710
3711static const struct reserved_combo* match_reserved_word(o_string *word)
3712{
Eric Andersen25f27032001-04-26 23:22:31 +00003713 /* Mostly a list of accepted follow-up reserved words.
3714 * FLAG_END means we are done with the sequence, and are ready
3715 * to turn the compound list into a command.
3716 * FLAG_START means the word must start a new compound list.
3717 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003718 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003719# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003720 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3721 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3722 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3723 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3724 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3725 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003726# endif
3727# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003728 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3729 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3730 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3731 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3732 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3733 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003734# endif
3735# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003736 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3737 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003738# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003739 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003740 const struct reserved_combo *r;
3741
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003742 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003743 if (strcmp(word->data, r->literal) == 0)
3744 return r;
3745 }
3746 return NULL;
3747}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003748/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003749 */
Denys Vlasenko5807e182018-02-08 19:19:04 +01003750static const struct reserved_combo* reserved_word(o_string *word, struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003751{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003752# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003753 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003754 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003755 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003756# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003757 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003758
Denys Vlasenko38292b62010-09-05 14:49:40 +02003759 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003760 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003761 r = match_reserved_word(word);
3762 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003763 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003764
3765 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003766# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003767 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3768 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003769 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003770 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003771# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003772 if (r->flag == 0) { /* '!' */
3773 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003774 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003775 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003776 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003777 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003778 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003779 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003780 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003781 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003782
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003783 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003784 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003785 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003786 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003787 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003788 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003789 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003790 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003791 } else {
3792 /* "{...} fi" is ok. "{...} if" is not
3793 * Example:
3794 * if { echo foo; } then { echo bar; } fi */
3795 if (ctx->command->group)
3796 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003797 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003798
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003799 ctx->ctx_res_w = r->res;
3800 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003801 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003802 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003803
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003804 if (ctx->old_flag & FLAG_END) {
3805 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003806
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003807 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003808 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003809 old = ctx->stack;
3810 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003811 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003812# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003813 /* At this point, the compound command's string is in
3814 * ctx->as_string... except for the leading keyword!
3815 * Consider this example: "echo a | if true; then echo a; fi"
3816 * ctx->as_string will contain "true; then echo a; fi",
3817 * with "if " remaining in old->as_string!
3818 */
3819 {
3820 char *str;
3821 int len = old->as_string.length;
3822 /* Concatenate halves */
3823 o_addstr(&old->as_string, ctx->as_string.data);
3824 o_free_unsafe(&ctx->as_string);
3825 /* Find where leading keyword starts in first half */
3826 str = old->as_string.data + len;
3827 if (str > old->as_string.data)
3828 str--; /* skip whitespace after keyword */
3829 while (str > old->as_string.data && isalpha(str[-1]))
3830 str--;
3831 /* Ugh, we're done with this horrid hack */
3832 old->command->group_as_string = xstrdup(str);
3833 debug_printf_parse("pop, remembering as:'%s'\n",
3834 old->command->group_as_string);
3835 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003836# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003837 *ctx = *old; /* physical copy */
3838 free(old);
3839 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003840 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003841}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003842#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003843
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003844/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003845 * Normal return is 0. Syntax errors return 1.
3846 * Note: on return, word is reset, but not o_free'd!
3847 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003848static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003849{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003850 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003851
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003852 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003853 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003854 debug_printf_parse("done_word return 0: true null, ignored\n");
3855 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003856 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003857
Eric Andersen25f27032001-04-26 23:22:31 +00003858 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003859 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3860 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003861 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003862 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003863 * If the redirection operator is "<<" or "<<-", the word
3864 * that follows the redirection operator shall be
3865 * subjected to quote removal; it is unspecified whether
3866 * any of the other expansions occur. For the other
3867 * redirection operators, the word that follows the
3868 * redirection operator shall be subjected to tilde
3869 * expansion, parameter expansion, command substitution,
3870 * arithmetic expansion, and quote removal.
3871 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003872 * on the word by a non-interactive shell; an interactive
3873 * shell may perform it, but shall do so only when
3874 * the expansion would result in one word."
3875 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003876//bash does not do parameter/command substitution or arithmetic expansion
3877//for _heredoc_ redirection word: these constructs look for exact eof marker
3878// as written:
3879// <<EOF$t
3880// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003881// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3882
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003883 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003884 /* Cater for >\file case:
3885 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3886 * Same with heredocs:
3887 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3888 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003889 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3890 unbackslash(ctx->pending_redirect->rd_filename);
3891 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003892 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003893 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3894 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003895 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003896 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003897 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003898 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003899#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003900# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003901 if (ctx->ctx_dsemicolon
3902 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3903 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003904 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003905 /* ctx->ctx_res_w = RES_MATCH; */
3906 ctx->ctx_dsemicolon = 0;
3907 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003908# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003909 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003910# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003911 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3912 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003913# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003914# if ENABLE_HUSH_CASE
3915 && ctx->ctx_res_w != RES_CASE
3916# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003917 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003918 const struct reserved_combo *reserved;
3919 reserved = reserved_word(word, ctx);
3920 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003921 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003922# if ENABLE_HUSH_LINENO_VAR
3923/* Case:
3924 * "while ...; do
3925 * cmd ..."
3926 * If we don't close the pipe _now_, immediately after "do", lineno logic
3927 * sees "cmd" as starting at "do" - i.e., at the previous line.
3928 */
3929 if (0
3930 IF_HUSH_IF(|| reserved->res == RES_THEN)
3931 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3932 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3933 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3934 ) {
3935 done_pipe(ctx, PIPE_SEQ);
3936 }
3937# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003938 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003939 debug_printf_parse("done_word return %d\n",
3940 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003941 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003942 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003943# if defined(CMD_SINGLEWORD_NOGLOB)
3944 if (0
3945# if BASH_TEST2
3946 || strcmp(word->data, "[[") == 0
3947# endif
3948 /* In bash, local/export/readonly are special, args
3949 * are assignments and therefore expansion of them
3950 * should be "one-word" expansion:
3951 * $ export i=`echo 'a b'` # one arg: "i=a b"
3952 * compare with:
3953 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3954 * ls: cannot access i=a: No such file or directory
3955 * ls: cannot access b: No such file or directory
3956 * Note: bash 3.2.33(1) does this only if export word
3957 * itself is not quoted:
3958 * $ export i=`echo 'aaa bbb'`; echo "$i"
3959 * aaa bbb
3960 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3961 * aaa
3962 */
3963 IF_HUSH_LOCAL( || strcmp(word->data, "local") == 0)
3964 IF_HUSH_EXPORT( || strcmp(word->data, "export") == 0)
3965 IF_HUSH_READONLY( || strcmp(word->data, "readonly") == 0)
3966 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003967 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3968 }
3969 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003970# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003971 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003972#endif /* HAS_KEYWORDS */
3973
Denis Vlasenkobb929512009-04-16 10:59:40 +00003974 if (command->group) {
3975 /* "{ echo foo; } echo bar" - bad */
3976 syntax_error_at(word->data);
3977 debug_printf_parse("done_word return 1: syntax error, "
3978 "groups and arglists don't mix\n");
3979 return 1;
3980 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003981
3982 /* If this word wasn't an assignment, next ones definitely
3983 * can't be assignments. Even if they look like ones. */
3984 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3985 && word->o_assignment != WORD_IS_KEYWORD
3986 ) {
3987 word->o_assignment = NOT_ASSIGNMENT;
3988 } else {
3989 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3990 command->assignment_cnt++;
3991 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3992 }
3993 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3994 word->o_assignment = MAYBE_ASSIGNMENT;
3995 }
3996 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003997 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003998 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003999 }
Eric Andersen25f27032001-04-26 23:22:31 +00004000
Denis Vlasenko06810332007-05-21 23:30:54 +00004001#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004002 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02004003 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004004 || !is_well_formed_var_name(command->argv[0], '\0')
4005 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004006 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004007 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004008 return 1;
4009 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004010 /* Force FOR to have just one word (variable name) */
4011 /* NB: basically, this makes hush see "for v in ..."
4012 * syntax as if it is "for v; in ...". FOR and IN become
4013 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004014 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004015 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004016#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004017#if ENABLE_HUSH_CASE
4018 /* Force CASE to have just one word */
4019 if (ctx->ctx_res_w == RES_CASE) {
4020 done_pipe(ctx, PIPE_SEQ);
4021 }
4022#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004023
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004024 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004025
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004026 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004027 return 0;
4028}
4029
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004030
4031/* Peek ahead in the input to find out if we have a "&n" construct,
4032 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004033 * Return:
4034 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4035 * REDIRFD_SYNTAX_ERR if syntax error,
4036 * REDIRFD_TO_FILE if no & was seen,
4037 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004038 */
4039#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004040#define parse_redir_right_fd(as_string, input) \
4041 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004042#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004043static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004044{
4045 int ch, d, ok;
4046
4047 ch = i_peek(input);
4048 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004049 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004050
4051 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004052 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004053 ch = i_peek(input);
4054 if (ch == '-') {
4055 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004056 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004057 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004058 }
4059 d = 0;
4060 ok = 0;
4061 while (ch != EOF && isdigit(ch)) {
4062 d = d*10 + (ch-'0');
4063 ok = 1;
4064 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004065 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004066 ch = i_peek(input);
4067 }
4068 if (ok) return d;
4069
4070//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4071
4072 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004073 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004074}
4075
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004076/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004077 */
4078static int parse_redirect(struct parse_context *ctx,
4079 int fd,
4080 redir_type style,
4081 struct in_str *input)
4082{
4083 struct command *command = ctx->command;
4084 struct redir_struct *redir;
4085 struct redir_struct **redirp;
4086 int dup_num;
4087
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004088 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004089 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004090 /* Check for a '>&1' type redirect */
4091 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4092 if (dup_num == REDIRFD_SYNTAX_ERR)
4093 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004094 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004095 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004096 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004097 if (dup_num) { /* <<-... */
4098 ch = i_getch(input);
4099 nommu_addchr(&ctx->as_string, ch);
4100 ch = i_peek(input);
4101 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004102 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004103
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004104 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004105 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004106 if (ch == '|') {
4107 /* >|FILE redirect ("clobbering" >).
4108 * Since we do not support "set -o noclobber" yet,
4109 * >| and > are the same for now. Just eat |.
4110 */
4111 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004112 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004113 }
4114 }
4115
4116 /* Create a new redir_struct and append it to the linked list */
4117 redirp = &command->redirects;
4118 while ((redir = *redirp) != NULL) {
4119 redirp = &(redir->next);
4120 }
4121 *redirp = redir = xzalloc(sizeof(*redir));
4122 /* redir->next = NULL; */
4123 /* redir->rd_filename = NULL; */
4124 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004125 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004126
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004127 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4128 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004129
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004130 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004131 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004132 /* Erik had a check here that the file descriptor in question
4133 * is legit; I postpone that to "run time"
4134 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004135 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4136 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004137 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004138#if 0 /* Instead we emit error message at run time */
4139 if (ctx->pending_redirect) {
4140 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004141 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004142 }
4143#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 /* Set ctx->pending_redirect, so we know what to do at the
4145 * end of the next parsed word. */
4146 ctx->pending_redirect = redir;
4147 }
4148 return 0;
4149}
4150
Eric Andersen25f27032001-04-26 23:22:31 +00004151/* If a redirect is immediately preceded by a number, that number is
4152 * supposed to tell which file descriptor to redirect. This routine
4153 * looks for such preceding numbers. In an ideal world this routine
4154 * needs to handle all the following classes of redirects...
4155 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4156 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4157 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4158 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004159 *
4160 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4161 * "2.7 Redirection
4162 * ... If n is quoted, the number shall not be recognized as part of
4163 * the redirection expression. For example:
4164 * echo \2>a
4165 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004166 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167 *
4168 * A -1 return means no valid number was found,
4169 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004170 */
4171static int redirect_opt_num(o_string *o)
4172{
4173 int num;
4174
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004176 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004177 num = bb_strtou(o->data, NULL, 10);
4178 if (errno || num < 0)
4179 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004180 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004181 return num;
4182}
4183
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004184#if BB_MMU
4185#define fetch_till_str(as_string, input, word, skip_tabs) \
4186 fetch_till_str(input, word, skip_tabs)
4187#endif
4188static char *fetch_till_str(o_string *as_string,
4189 struct in_str *input,
4190 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004191 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004192{
4193 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004194 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004195 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004196 int ch;
4197
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004198 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004199
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200 while (1) {
4201 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004202 if (ch != EOF)
4203 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004204 if (ch == '\n' || ch == EOF) {
4205 check_heredoc_end:
4206 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4207 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4208 heredoc.data[past_EOL] = '\0';
4209 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4210 return heredoc.data;
4211 }
4212 if (ch == '\n') {
4213 /* This is a new line.
4214 * Remember position and backslash-escaping status.
4215 */
4216 o_addchr(&heredoc, ch);
4217 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004218 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004219 past_EOL = heredoc.length;
4220 /* Get 1st char of next line, possibly skipping leading tabs */
4221 do {
4222 ch = i_getch(input);
4223 if (ch != EOF)
4224 nommu_addchr(as_string, ch);
4225 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4226 /* If this immediately ended the line,
4227 * go back to end-of-line checks.
4228 */
4229 if (ch == '\n')
4230 goto check_heredoc_end;
4231 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004232 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004233 }
4234 if (ch == EOF) {
4235 o_free_unsafe(&heredoc);
4236 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004237 }
4238 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004239 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004240 if (prev == '\\' && ch == '\\')
4241 /* Correctly handle foo\\<eol> (not a line cont.) */
4242 prev = 0; /* not \ */
4243 else
4244 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004245 }
4246}
4247
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004248/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4249 * and load them all. There should be exactly heredoc_cnt of them.
4250 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004251static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4252{
4253 struct pipe *pi = ctx->list_head;
4254
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004255 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004256 int i;
4257 struct command *cmd = pi->cmds;
4258
4259 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4260 pi->num_cmds,
4261 cmd->argv ? cmd->argv[0] : "NONE");
4262 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004263 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004264
4265 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4266 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004267 while (redir) {
4268 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004269 char *p;
4270
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004271 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004272 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004273 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004274 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004275 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004276 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004277 return 1;
4278 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004279 free(redir->rd_filename);
4280 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004281 heredoc_cnt--;
4282 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004283 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004284 }
4285 cmd++;
4286 }
4287 pi = pi->next;
4288 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004289#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004290 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004291 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004292 bb_error_msg_and_die("heredoc BUG 2");
4293#endif
4294 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004295}
4296
4297
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004298static int run_list(struct pipe *pi);
4299#if BB_MMU
4300#define parse_stream(pstring, input, end_trigger) \
4301 parse_stream(input, end_trigger)
4302#endif
4303static struct pipe *parse_stream(char **pstring,
4304 struct in_str *input,
4305 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004306
Eric Andersen25f27032001-04-26 23:22:31 +00004307
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004308#if !ENABLE_HUSH_FUNCTIONS
4309#define parse_group(dest, ctx, input, ch) \
4310 parse_group(ctx, input, ch)
4311#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004312static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004313 struct in_str *input, int ch)
4314{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004315 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004316 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004317 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004318#if BB_MMU
4319# define as_string NULL
4320#else
4321 char *as_string = NULL;
4322#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004323 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004324 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004325 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004326
4327 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004328#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004329 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004330 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004331 if (done_word(dest, ctx))
4332 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004333 if (!command->argv)
4334 goto skip; /* (... */
4335 if (command->argv[1]) { /* word word ... (... */
4336 syntax_error_unexpected_ch('(');
4337 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004338 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004339 /* it is "word(..." or "word (..." */
4340 do
4341 ch = i_getch(input);
4342 while (ch == ' ' || ch == '\t');
4343 if (ch != ')') {
4344 syntax_error_unexpected_ch(ch);
4345 return 1;
4346 }
4347 nommu_addchr(&ctx->as_string, ch);
4348 do
4349 ch = i_getch(input);
4350 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004351 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004352 syntax_error_unexpected_ch(ch);
4353 return 1;
4354 }
4355 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004356 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004357 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004358 }
4359#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004360
4361#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004362 if (command->argv /* word [word]{... */
4363 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004364 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004365 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004366 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004367 debug_printf_parse("parse_group return 1: "
4368 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004369 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004370 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004371#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004372
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004373 IF_HUSH_FUNCTIONS(skip:)
4374
Denis Vlasenko240c2552009-04-03 03:45:05 +00004375 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004376 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004377 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004378 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4379 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004380 } else {
4381 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004382 ch = i_peek(input);
4383 if (ch != ' ' && ch != '\t' && ch != '\n'
4384 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4385 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004386 syntax_error_unexpected_ch(ch);
4387 return 1;
4388 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004389 if (ch != '(') {
4390 ch = i_getch(input);
4391 nommu_addchr(&ctx->as_string, ch);
4392 }
Eric Andersen25f27032001-04-26 23:22:31 +00004393 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004394
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004395 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004396#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004397 if (as_string)
4398 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004399#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004400
4401 /* empty ()/{} or parse error? */
4402 if (!pipe_list || pipe_list == ERR_PTR) {
4403 /* parse_stream already emitted error msg */
4404 if (!BB_MMU)
4405 free(as_string);
4406 debug_printf_parse("parse_group return 1: "
4407 "parse_stream returned %p\n", pipe_list);
4408 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004409 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004410#if !BB_MMU
4411 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4412 command->group_as_string = as_string;
4413 debug_printf_parse("end of group, remembering as:'%s'\n",
4414 command->group_as_string);
4415#endif
4416
4417#if ENABLE_HUSH_FUNCTIONS
4418 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4419 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4420 struct command *cmd2;
4421
4422 cmd2 = xzalloc(sizeof(*cmd2));
4423 cmd2->cmd_type = CMD_SUBSHELL;
4424 cmd2->group = pipe_list;
4425# if !BB_MMU
4426//UNTESTED!
4427 cmd2->group_as_string = command->group_as_string;
4428 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4429# endif
4430
4431 pipe_list = new_pipe();
4432 pipe_list->cmds = cmd2;
4433 pipe_list->num_cmds = 1;
4434 }
4435#endif
4436
4437 command->group = pipe_list;
4438
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004439 debug_printf_parse("parse_group return 0\n");
4440 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004441 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004442#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004443}
4444
Denys Vlasenko0b883582016-12-23 16:49:07 +01004445#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004446/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004447static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004448/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004449static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004450{
4451 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004452 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004453 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004454 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004455 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004456 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004457 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004458 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004459 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004460 }
4461}
4462/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004463static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004464{
4465 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004466 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004467 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004468 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004469 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004470 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004471 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004472 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004473 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004474 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004475 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004476 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004477 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004478 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004479 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4480 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004481 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004482 continue;
4483 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004484 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004485 }
4486}
4487/* Process `cmd` - copy contents until "`" is seen. Complicated by
4488 * \` quoting.
4489 * "Within the backquoted style of command substitution, backslash
4490 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4491 * The search for the matching backquote shall be satisfied by the first
4492 * backquote found without a preceding backslash; during this search,
4493 * if a non-escaped backquote is encountered within a shell comment,
4494 * a here-document, an embedded command substitution of the $(command)
4495 * form, or a quoted string, undefined results occur. A single-quoted
4496 * or double-quoted string that begins, but does not end, within the
4497 * "`...`" sequence produces undefined results."
4498 * Example Output
4499 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4500 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004501static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004502{
4503 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004504 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004505 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004506 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004507 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004508 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4509 ch = i_getch(input);
4510 if (ch != '`'
4511 && ch != '$'
4512 && ch != '\\'
4513 && (!in_dquote || ch != '"')
4514 ) {
4515 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004516 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004517 }
4518 if (ch == EOF) {
4519 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004520 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004521 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004522 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004523 }
4524}
4525/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4526 * quoting and nested ()s.
4527 * "With the $(command) style of command substitution, all characters
4528 * following the open parenthesis to the matching closing parenthesis
4529 * constitute the command. Any valid shell script can be used for command,
4530 * except a script consisting solely of redirections which produces
4531 * unspecified results."
4532 * Example Output
4533 * echo $(echo '(TEST)' BEST) (TEST) BEST
4534 * echo $(echo 'TEST)' BEST) TEST) BEST
4535 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004536 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004537 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004538 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004539 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4540 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004541 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004542#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004543static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004544{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004545 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004546 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004547# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004548 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004549# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004550 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4551
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004552 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004553 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004554 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004555 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004556 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004557 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004558 if (ch == end_ch
4559# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004560 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004561# endif
4562 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004563 if (!dbl)
4564 break;
4565 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004566 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004567 i_getch(input); /* eat second ')' */
4568 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004569 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004570 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004571 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004572 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004573 if (ch == '(' || ch == '{') {
4574 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004575 if (!add_till_closing_bracket(dest, input, ch))
4576 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004577 o_addchr(dest, ch);
4578 continue;
4579 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004580 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004581 if (!add_till_single_quote(dest, input))
4582 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004583 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004584 continue;
4585 }
4586 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004587 if (!add_till_double_quote(dest, input))
4588 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004589 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004590 continue;
4591 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004592 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004593 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4594 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004595 o_addchr(dest, ch);
4596 continue;
4597 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004598 if (ch == '\\') {
4599 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004600 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004601 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004602 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004603 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004604 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004605#if 0
4606 if (ch == '\n') {
4607 /* "backslash+newline", ignore both */
4608 o_delchr(dest); /* undo insertion of '\' */
4609 continue;
4610 }
4611#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004612 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004613 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004614 continue;
4615 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004616 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004617 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004618}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004619#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004620
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004621/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004622#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004623#define parse_dollar(as_string, dest, input, quote_mask) \
4624 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004625#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004626#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004627static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004628 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004629 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004630{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004631 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004632
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004633 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004634 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004635 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004636 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004637 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004638 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004639 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004640 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004641 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004642 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004643 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004644 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004645 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004646 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004647 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004648 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004649 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004650 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004651 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004652 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004653 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004654 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004655 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004656 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004657 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004658 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004659 o_addchr(dest, ch | quote_mask);
4660 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004661 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004662 case '$': /* pid */
4663 case '!': /* last bg pid */
4664 case '?': /* last exit code */
4665 case '#': /* number of args */
4666 case '*': /* args */
4667 case '@': /* args */
4668 goto make_one_char_var;
4669 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004670 char len_single_ch;
4671
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4673
Denys Vlasenko74369502010-05-21 19:52:01 +02004674 ch = i_getch(input); /* eat '{' */
4675 nommu_addchr(as_string, ch);
4676
Denys Vlasenko46e64982016-09-29 19:50:55 +02004677 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004678 /* It should be ${?}, or ${#var},
4679 * or even ${?+subst} - operator acting on a special variable,
4680 * or the beginning of variable name.
4681 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004682 if (ch == EOF
4683 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4684 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004685 bad_dollar_syntax:
4686 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004687 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4688 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004689 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004690 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004691 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004692 ch |= quote_mask;
4693
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004694 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004695 * However, this regresses some of our testsuite cases
4696 * which check invalid constructs like ${%}.
4697 * Oh well... let's check that the var name part is fine... */
4698
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004699 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004700 unsigned pos;
4701
Denys Vlasenko74369502010-05-21 19:52:01 +02004702 o_addchr(dest, ch);
4703 debug_printf_parse(": '%c'\n", ch);
4704
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004705 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004706 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004707 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004708 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004709
Denys Vlasenko74369502010-05-21 19:52:01 +02004710 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004711 unsigned end_ch;
4712 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004713 /* handle parameter expansions
4714 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4715 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004716 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4717 if (len_single_ch != '#'
4718 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4719 || i_peek(input) != '}'
4720 ) {
4721 goto bad_dollar_syntax;
4722 }
4723 /* else: it's "length of C" ${#C} op,
4724 * where C is a single char
4725 * special var name, e.g. ${#!}.
4726 */
4727 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004728 /* Eat everything until closing '}' (or ':') */
4729 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004730 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004731 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004732 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004733 ) {
4734 /* It's ${var:N[:M]} thing */
4735 end_ch = '}' * 0x100 + ':';
4736 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004737 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004738 && ch == '/'
4739 ) {
4740 /* It's ${var/[/]pattern[/repl]} thing */
4741 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4742 i_getch(input);
4743 nommu_addchr(as_string, '/');
4744 ch = '\\';
4745 }
4746 end_ch = '}' * 0x100 + '/';
4747 }
4748 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004749 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004750 if (!BB_MMU)
4751 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004752#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004753 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004754 if (last_ch == 0) /* error? */
4755 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004756#else
4757#error Simple code to only allow ${var} is not implemented
4758#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004759 if (as_string) {
4760 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004761 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004762 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004763
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004764 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4765 && (end_ch & 0xff00)
4766 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004767 /* close the first block: */
4768 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004769 /* while parsing N from ${var:N[:M]}
4770 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004771 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004772 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004773 end_ch = '}';
4774 goto again;
4775 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004776 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004777 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004778 /* it's ${var:N} - emulate :999999999 */
4779 o_addstr(dest, "999999999");
4780 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004781 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004782 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004783 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004784 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004785 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004786 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4787 break;
4788 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004789#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004790 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004791 unsigned pos;
4792
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004793 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004794 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004795# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004796 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004797 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004798 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4800 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004801 if (!BB_MMU)
4802 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004803 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4804 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004805 if (as_string) {
4806 o_addstr(as_string, dest->data + pos);
4807 o_addchr(as_string, ')');
4808 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004809 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004810 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004811 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004812 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004813# endif
4814# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004815 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4816 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004817 if (!BB_MMU)
4818 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004819 if (!add_till_closing_bracket(dest, input, ')'))
4820 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004821 if (as_string) {
4822 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004823 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004824 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004825 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004826# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004827 break;
4828 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004829#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004830 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004831 goto make_var;
4832#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004833 /* TODO: $_ and $-: */
4834 /* $_ Shell or shell script name; or last argument of last command
4835 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4836 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004837 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004838 ch = i_getch(input);
4839 nommu_addchr(as_string, ch);
4840 ch = i_peek_and_eat_bkslash_nl(input);
4841 if (isalnum(ch)) { /* it's $_name or $_123 */
4842 ch = '_';
4843 goto make_var1;
4844 }
4845 /* else: it's $_ */
4846#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004847 default:
4848 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004849 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004850 debug_printf_parse("parse_dollar return 1 (ok)\n");
4851 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004852#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004853}
4854
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004855#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004856# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004857#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4858 encode_string(dest, input, dquote_end, process_bkslash)
4859# else
4860/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4861#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4862 encode_string(dest, input, dquote_end)
4863# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004864#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004865
4866#else /* !MMU */
4867
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004868# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004869/* all parameters are needed, no macro tricks */
4870# else
4871#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4872 encode_string(as_string, dest, input, dquote_end)
4873# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004874#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004875static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004876 o_string *dest,
4877 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004878 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004879 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004880{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004881#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004882 const int process_bkslash = 1;
4883#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004884 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004885 int next;
4886
4887 again:
4888 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004889 if (ch != EOF)
4890 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004891 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004892 debug_printf_parse("encode_string return 1 (ok)\n");
4893 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004894 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004895 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004896 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004897 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004898 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004899 }
4900 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004901 if (ch != '\n') {
4902 next = i_peek(input);
4903 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004904 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004905 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004906 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004907 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004908 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004909 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004910 }
4911 /* bash:
4912 * "The backslash retains its special meaning [in "..."]
4913 * only when followed by one of the following characters:
4914 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004915 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004916 * NB: in (unquoted) heredoc, above does not apply to ",
4917 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004918 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004919 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004920 ch = i_getch(input); /* eat next */
4921 if (ch == '\n')
4922 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004923 } /* else: ch remains == '\\', and we double it below: */
4924 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004925 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004926 goto again;
4927 }
4928 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004929 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4930 debug_printf_parse("encode_string return 0: "
4931 "parse_dollar returned 0 (error)\n");
4932 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004933 }
4934 goto again;
4935 }
4936#if ENABLE_HUSH_TICK
4937 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004938 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004939 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4940 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004941 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4942 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004943 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4944 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004945 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004946 }
4947#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004948 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004949 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004950#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004951}
4952
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004953/*
4954 * Scan input until EOF or end_trigger char.
4955 * Return a list of pipes to execute, or NULL on EOF
4956 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004957 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004958 * reset parsing machinery and start parsing anew,
4959 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004960 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004961static struct pipe *parse_stream(char **pstring,
4962 struct in_str *input,
4963 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004964{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004965 struct parse_context ctx;
4966 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004967 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004968
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004969 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004970 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004971 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004972 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004973 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004974 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004975
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004976 /* If very first arg is "" or '', dest.data may end up NULL.
4977 * Preventing this: */
4978 o_addchr(&dest, '\0');
4979 dest.length = 0;
4980
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004981 /* We used to separate words on $IFS here. This was wrong.
4982 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004983 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004984 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004985
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004986 if (MAYBE_ASSIGNMENT != 0)
4987 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004988 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004989 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004990 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004991 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004992 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004993 int ch;
4994 int next;
4995 int redir_fd;
4996 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004997
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004998 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004999 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005000 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005001 if (ch == EOF) {
5002 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005003
5004 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005005 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005006 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005007 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005008 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005009 syntax_error_unterm_ch('(');
5010 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005011 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005012 if (end_trigger == '}') {
5013 syntax_error_unterm_ch('{');
5014 goto parse_error;
5015 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005016
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005017 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005018 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005019 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005020 o_free(&dest);
5021 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005022 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005023 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005024 /* (this makes bare "&" cmd a no-op.
5025 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005026 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005027 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005028 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005029 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005030 pi = NULL;
5031 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005032#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005033 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005034 if (pstring)
5035 *pstring = ctx.as_string.data;
5036 else
5037 o_free_unsafe(&ctx.as_string);
5038#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005039 debug_leave();
5040 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005041 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005042 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005043 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005044
5045 next = '\0';
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005046 if (ch != '\n') {
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005047 next = i_peek(input);
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005048 /* Can't use i_peek_and_eat_bkslash_nl(input) here:
5049 * echo '\
5050 * '
5051 * will break.
5052 */
5053 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005054
5055 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005056 "\\$\"" IF_HUSH_TICK("`") /* always special */
5057 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005058 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005059 if (ctx.command->argv /* word [word]{... - non-special */
5060 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005061 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005062 || (next != ';' /* }; - special */
5063 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005064 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005065 && next != '&' /* }& and }&& ... - special */
5066 && next != '|' /* }|| ... - special */
5067 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005068 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005069 ) {
5070 /* They are not special, skip "{}" */
5071 is_special += 2;
5072 }
5073 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005074 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005075
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005076 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005077 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005078 o_addQchr(&dest, ch);
5079 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5080 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005081 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005082 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005083 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005084 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005085 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005086 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005087 continue;
5088 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005089
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005090 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005091#if ENABLE_HUSH_LINENO_VAR
5092/* Case:
5093 * "while ...; do<whitespace><newline>
5094 * cmd ..."
5095 * would think that "cmd" starts in <whitespace> -
5096 * i.e., at the previous line.
5097 * We need to skip all whitespace before newlines.
5098 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005099 while (ch != '\n') {
5100 next = i_peek(input);
5101 if (next != ' ' && next != '\t' && next != '\n')
5102 break; /* next char is not ws */
5103 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005104 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005105 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005106#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005107 if (done_word(&dest, &ctx)) {
5108 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005109 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005110 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005111 /* Is this a case when newline is simply ignored?
5112 * Some examples:
5113 * "cmd | <newline> cmd ..."
5114 * "case ... in <newline> word) ..."
5115 */
5116 if (IS_NULL_CMD(ctx.command)
5117 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005118 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005119 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005120 * Without check #1, interactive shell
5121 * ignores even bare <newline>,
5122 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005123 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005124 * ps2> _ <=== wrong, should be ps1
5125 * Without check #2, "cmd & <newline>"
5126 * is similarly mistreated.
5127 * (BTW, this makes "cmd & cmd"
5128 * and "cmd && cmd" non-orthogonal.
5129 * Really, ask yourself, why
5130 * "cmd && <newline>" doesn't start
5131 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005132 * The only reason is that it might be
5133 * a "cmd1 && <nl> cmd2 &" construct,
5134 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005135 */
5136 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005137 if (pi->num_cmds != 0 /* check #1 */
5138 && pi->followup != PIPE_BG /* check #2 */
5139 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005140 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005141 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005142 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005143 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005144 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005145 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5146 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005147 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005148 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005149 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005150 heredoc_cnt = 0;
5151 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005152 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005153 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005154 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005155 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005156 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005157 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005158 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005159
5160 /* "cmd}" or "cmd }..." without semicolon or &:
5161 * } is an ordinary char in this case, even inside { cmd; }
5162 * Pathological example: { ""}; } should exec "}" cmd
5163 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005164 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005165 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005166 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005167 ) {
5168 goto ordinary_char;
5169 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005170 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5171 /* Generally, there should be semicolon: "cmd; }"
5172 * However, bash allows to omit it if "cmd" is
5173 * a group. Examples:
5174 * { { echo 1; } }
5175 * {(echo 1)}
5176 * { echo 0 >&2 | { echo 1; } }
5177 * { while false; do :; done }
5178 * { case a in b) ;; esac }
5179 */
5180 if (ctx.command->group)
5181 goto term_group;
5182 goto ordinary_char;
5183 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005184 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005185 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005186 goto skip_end_trigger;
5187 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005188 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005189 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005190 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005191 && (ch != ';' || heredoc_cnt == 0)
5192#if ENABLE_HUSH_CASE
5193 && (ch != ')'
5194 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005195 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005196 )
5197#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005198 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005199 if (heredoc_cnt) {
5200 /* This is technically valid:
5201 * { cat <<HERE; }; echo Ok
5202 * heredoc
5203 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005204 * HERE
5205 * but we don't support this.
5206 * We require heredoc to be in enclosing {}/(),
5207 * if any.
5208 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005209 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005210 goto parse_error;
5211 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005212 if (done_word(&dest, &ctx)) {
5213 goto parse_error;
5214 }
5215 done_pipe(&ctx, PIPE_SEQ);
5216 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005217 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005218 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005219 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005220 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005221 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005222 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005223#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005224 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005225 if (pstring)
5226 *pstring = ctx.as_string.data;
5227 else
5228 o_free_unsafe(&ctx.as_string);
5229#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005230 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5231 /* Example: bare "{ }", "()" */
5232 G.last_exitcode = 2; /* bash compat */
5233 syntax_error_unexpected_ch(ch);
5234 goto parse_error2;
5235 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005236 debug_printf_parse("parse_stream return %p: "
5237 "end_trigger char found\n",
5238 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005239 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005240 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005241 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005242 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005243 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005244 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005245 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005246
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005247 /* Catch <, > before deciding whether this word is
5248 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5249 switch (ch) {
5250 case '>':
5251 redir_fd = redirect_opt_num(&dest);
5252 if (done_word(&dest, &ctx)) {
5253 goto parse_error;
5254 }
5255 redir_style = REDIRECT_OVERWRITE;
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02005256 if (next == '\\')
5257 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005258 if (next == '>') {
5259 redir_style = REDIRECT_APPEND;
5260 ch = i_getch(input);
5261 nommu_addchr(&ctx.as_string, ch);
5262 }
5263#if 0
5264 else if (next == '(') {
5265 syntax_error(">(process) not supported");
5266 goto parse_error;
5267 }
5268#endif
5269 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5270 goto parse_error;
5271 continue; /* back to top of while (1) */
5272 case '<':
5273 redir_fd = redirect_opt_num(&dest);
5274 if (done_word(&dest, &ctx)) {
5275 goto parse_error;
5276 }
5277 redir_style = REDIRECT_INPUT;
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02005278 if (next == '\\')
5279 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005280 if (next == '<') {
5281 redir_style = REDIRECT_HEREDOC;
5282 heredoc_cnt++;
5283 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5284 ch = i_getch(input);
5285 nommu_addchr(&ctx.as_string, ch);
5286 } else if (next == '>') {
5287 redir_style = REDIRECT_IO;
5288 ch = i_getch(input);
5289 nommu_addchr(&ctx.as_string, ch);
5290 }
5291#if 0
5292 else if (next == '(') {
5293 syntax_error("<(process) not supported");
5294 goto parse_error;
5295 }
5296#endif
5297 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5298 goto parse_error;
5299 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005300 case '#':
5301 if (dest.length == 0 && !dest.has_quoted_part) {
5302 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005303 /* note: we do not add it to &ctx.as_string */
5304/* TODO: in bash:
5305 * comment inside $() goes to the next \n, even inside quoted string (!):
5306 * cmd "$(cmd2 #comment)" - syntax error
5307 * cmd "`cmd2 #comment`" - ok
5308 * We accept both (comment ends where command subst ends, in both cases).
5309 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005310 while (1) {
5311 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005312 if (ch == '\n') {
5313 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005314 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005315 }
5316 ch = i_getch(input);
5317 if (ch == EOF)
5318 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005319 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005320 continue; /* back to top of while (1) */
5321 }
5322 break;
5323 case '\\':
5324 if (next == '\n') {
5325 /* It's "\<newline>" */
5326#if !BB_MMU
5327 /* Remove trailing '\' from ctx.as_string */
5328 ctx.as_string.data[--ctx.as_string.length] = '\0';
5329#endif
5330 ch = i_getch(input); /* eat it */
5331 continue; /* back to top of while (1) */
5332 }
5333 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005334 }
5335
5336 if (dest.o_assignment == MAYBE_ASSIGNMENT
5337 /* check that we are not in word in "a=1 2>word b=1": */
5338 && !ctx.pending_redirect
5339 ) {
5340 /* ch is a special char and thus this word
5341 * cannot be an assignment */
5342 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005343 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005344 }
5345
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005346 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5347
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005348 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005349 case SPECIAL_VAR_SYMBOL:
5350 /* Convert raw ^C to corresponding special variable reference */
5351 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5352 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5353 /* fall through */
5354 case '#':
5355 /* non-comment #: "echo a#b" etc */
5356 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005357 break;
5358 case '\\':
5359 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005360 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005361 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005362 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005363 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005364 /* note: ch != '\n' (that case does not reach this place) */
5365 o_addchr(&dest, '\\');
5366 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5367 o_addchr(&dest, ch);
5368 nommu_addchr(&ctx.as_string, ch);
5369 /* Example: echo Hello \2>file
5370 * we need to know that word 2 is quoted */
5371 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005372 break;
5373 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005374 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005375 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005376 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005377 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005378 }
Eric Andersen25f27032001-04-26 23:22:31 +00005379 break;
5380 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005381 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005382 if (next == '\'' && !ctx.pending_redirect) {
5383 insert_empty_quoted_str_marker:
5384 nommu_addchr(&ctx.as_string, next);
5385 i_getch(input); /* eat second ' */
5386 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5387 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5388 } else {
5389 while (1) {
5390 ch = i_getch(input);
5391 if (ch == EOF) {
5392 syntax_error_unterm_ch('\'');
5393 goto parse_error;
5394 }
5395 nommu_addchr(&ctx.as_string, ch);
5396 if (ch == '\'')
5397 break;
Denys Vlasenko9809a822018-01-13 19:14:27 +01005398 if (ch == SPECIAL_VAR_SYMBOL) {
5399 /* Convert raw ^C to corresponding special variable reference */
5400 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5401 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5402 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005403 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005404 }
Eric Andersen25f27032001-04-26 23:22:31 +00005405 }
Eric Andersen25f27032001-04-26 23:22:31 +00005406 break;
5407 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005408 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005409 if (next == '"' && !ctx.pending_redirect)
5410 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005411 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005412 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005413 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005414 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005415 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005416 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005417#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005418 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005419 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005420
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005421 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5422 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005423 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005424 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5425 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005426# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005427 o_addstr(&ctx.as_string, dest.data + pos);
5428 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005429# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005430 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5431 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005432 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005433 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005434#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005435 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005436#if ENABLE_HUSH_CASE
5437 case_semi:
5438#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005439 if (done_word(&dest, &ctx)) {
5440 goto parse_error;
5441 }
5442 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005443#if ENABLE_HUSH_CASE
5444 /* Eat multiple semicolons, detect
5445 * whether it means something special */
5446 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005447 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005448 if (ch != ';')
5449 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005450 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005451 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005452 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005453 ctx.ctx_dsemicolon = 1;
5454 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005455 break;
5456 }
5457 }
5458#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005459 new_cmd:
5460 /* We just finished a cmd. New one may start
5461 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005462 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005463 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005464 break;
5465 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005466 if (done_word(&dest, &ctx)) {
5467 goto parse_error;
5468 }
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005469 if (next == '\\')
5470 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005471 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005472 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005473 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005474 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005475 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005476 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005477 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005478 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005479 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005480 if (done_word(&dest, &ctx)) {
5481 goto parse_error;
5482 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005483#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005484 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005485 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005486#endif
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005487 if (next == '\\')
5488 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005489 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005490 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005491 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005492 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005493 } else {
5494 /* we could pick up a file descriptor choice here
5495 * with redirect_opt_num(), but bash doesn't do it.
5496 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005497 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005498 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005499 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005500 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005501#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005502 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005503 if (ctx.ctx_res_w == RES_MATCH
5504 && ctx.command->argv == NULL /* not (word|(... */
5505 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005506 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005507 ) {
5508 continue;
5509 }
5510#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005511 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005512 if (parse_group(&dest, &ctx, input, ch) != 0) {
5513 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005514 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005515 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005516 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005517#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005518 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005519 goto case_semi;
5520#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005521 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005522 /* proper use of this character is caught by end_trigger:
5523 * if we see {, we call parse_group(..., end_trigger='}')
5524 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005525 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005526 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005527 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005528 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005529 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005530 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005531 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005532 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005533
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005534 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005535 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005536 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005537 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005538 struct parse_context *pctx;
5539 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005540
5541 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005542 * Sample for finding leaks on syntax error recovery path.
5543 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005544 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005545 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005546 * while if (true | { true;}); then echo ok; fi; do break; done
5547 * 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 +00005548 */
5549 pctx = &ctx;
5550 do {
5551 /* Update pipe/command counts,
5552 * otherwise freeing may miss some */
5553 done_pipe(pctx, PIPE_SEQ);
5554 debug_printf_clean("freeing list %p from ctx %p\n",
5555 pctx->list_head, pctx);
5556 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005557 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005558 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005559#if !BB_MMU
5560 o_free_unsafe(&pctx->as_string);
5561#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005562 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005563 if (pctx != &ctx) {
5564 free(pctx);
5565 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005566 IF_HAS_KEYWORDS(pctx = p2;)
5567 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005568
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005569 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005570#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005571 if (pstring)
5572 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005573#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005574 debug_leave();
5575 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005576 }
Eric Andersen25f27032001-04-26 23:22:31 +00005577}
5578
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005579
5580/*** Execution routines ***/
5581
5582/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005583#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005584/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5585#define expand_string_to_string(str, do_unbackslash) \
5586 expand_string_to_string(str)
5587#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005588static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005589#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005591#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005592
5593/* expand_strvec_to_strvec() takes a list of strings, expands
5594 * all variable references within and returns a pointer to
5595 * a list of expanded strings, possibly with larger number
5596 * of strings. (Think VAR="a b"; echo $VAR).
5597 * This new list is allocated as a single malloc block.
5598 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005599 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600 * Caller can deallocate entire list by single free(list). */
5601
Denys Vlasenko238081f2010-10-03 14:26:26 +02005602/* A horde of its helpers come first: */
5603
5604static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5605{
5606 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005607 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005608
Denys Vlasenko9e800222010-10-03 14:28:04 +02005609#if ENABLE_HUSH_BRACE_EXPANSION
5610 if (c == '{' || c == '}') {
5611 /* { -> \{, } -> \} */
5612 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005613 /* And now we want to add { or } and continue:
5614 * o_addchr(o, c);
5615 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005616 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005617 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005618 }
5619#endif
5620 o_addchr(o, c);
5621 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005622 /* \z -> \\\z; \<eol> -> \\<eol> */
5623 o_addchr(o, '\\');
5624 if (len) {
5625 len--;
5626 o_addchr(o, '\\');
5627 o_addchr(o, *str++);
5628 }
5629 }
5630 }
5631}
5632
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005633/* Store given string, finalizing the word and starting new one whenever
5634 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005635 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5636 * Return in *ended_with_ifs:
5637 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5638 */
5639static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005640{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005641 int last_is_ifs = 0;
5642
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005643 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005644 int word_len;
5645
5646 if (!*str) /* EOL - do not finalize word */
5647 break;
5648 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005649 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005650 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005651 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005652 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005653 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005654 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005655 * Example: "v='\*'; echo b$v" prints "b\*"
5656 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005657 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005658 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005659 /*/ Why can't we do it easier? */
5660 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5661 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5662 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005663 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005664 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005665 if (!*str) /* EOL - do not finalize word */
5666 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005667 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005668
5669 /* We know str here points to at least one IFS char */
5670 last_is_ifs = 1;
5671 str += strspn(str, G.ifs); /* skip IFS chars */
5672 if (!*str) /* EOL - do not finalize word */
5673 break;
5674
5675 /* Start new word... but not always! */
5676 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005677 if (output->has_quoted_part
5678 /* Case "v=' a'; echo $v":
5679 * here nothing precedes the space in $v expansion,
5680 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005681 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005682 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005683 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005684 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005685 o_addchr(output, '\0');
5686 debug_print_list("expand_on_ifs", output, n);
5687 n = o_save_ptr(output, n);
5688 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005689 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005690
5691 if (ended_with_ifs)
5692 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005693 debug_print_list("expand_on_ifs[1]", output, n);
5694 return n;
5695}
5696
5697/* Helper to expand $((...)) and heredoc body. These act as if
5698 * they are in double quotes, with the exception that they are not :).
5699 * Just the rules are similar: "expand only $var and `cmd`"
5700 *
5701 * Returns malloced string.
5702 * As an optimization, we return NULL if expansion is not needed.
5703 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005704#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005705/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5706#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5707 encode_then_expand_string(str)
5708#endif
5709static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005711#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005712 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005713#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005714 char *exp_str;
5715 struct in_str input;
5716 o_string dest = NULL_O_STRING;
5717
5718 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005719 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005720#if ENABLE_HUSH_TICK
5721 && !strchr(str, '`')
5722#endif
5723 ) {
5724 return NULL;
5725 }
5726
5727 /* We need to expand. Example:
5728 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5729 */
5730 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005731 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005732//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005733 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005734 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005735 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5736 o_free_unsafe(&dest);
5737 return exp_str;
5738}
5739
Denys Vlasenko0b883582016-12-23 16:49:07 +01005740#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005741static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005742{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005743 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005744 arith_t res;
5745 char *exp_str;
5746
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005747 math_state.lookupvar = get_local_var_value;
5748 math_state.setvar = set_local_var_from_halves;
5749 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005750 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005751 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005752 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005753 if (errmsg_p)
5754 *errmsg_p = math_state.errmsg;
5755 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005756 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005757 return res;
5758}
5759#endif
5760
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005761#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005762/* ${var/[/]pattern[/repl]} helpers */
5763static char *strstr_pattern(char *val, const char *pattern, int *size)
5764{
5765 while (1) {
5766 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5767 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5768 if (end) {
5769 *size = end - val;
5770 return val;
5771 }
5772 if (*val == '\0')
5773 return NULL;
5774 /* Optimization: if "*pat" did not match the start of "string",
5775 * we know that "tring", "ring" etc will not match too:
5776 */
5777 if (pattern[0] == '*')
5778 return NULL;
5779 val++;
5780 }
5781}
5782static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5783{
5784 char *result = NULL;
5785 unsigned res_len = 0;
5786 unsigned repl_len = strlen(repl);
5787
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005788 /* Null pattern never matches, including if "var" is empty */
5789 if (!pattern[0])
5790 return result; /* NULL, no replaces happened */
5791
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005792 while (1) {
5793 int size;
5794 char *s = strstr_pattern(val, pattern, &size);
5795 if (!s)
5796 break;
5797
5798 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005799 strcpy(mempcpy(result + res_len, val, s - val), repl);
5800 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005801 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5802
5803 val = s + size;
5804 if (exp_op == '/')
5805 break;
5806 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005807 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808 result = xrealloc(result, res_len + strlen(val) + 1);
5809 strcpy(result + res_len, val);
5810 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5811 }
5812 debug_printf_varexp("result:'%s'\n", result);
5813 return result;
5814}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005815#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005816
5817/* Helper:
5818 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5819 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005820static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005821{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005822 const char *val;
5823 char *to_be_freed;
5824 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005825 char *var;
5826 char first_char;
5827 char exp_op;
5828 char exp_save = exp_save; /* for compiler */
5829 char *exp_saveptr; /* points to expansion operator */
5830 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005831 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005832
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005833 val = NULL;
5834 to_be_freed = NULL;
5835 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005836 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005837 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005838 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005839 arg0 = arg[0];
5840 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005841 exp_op = 0;
5842
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005843 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5844 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5845 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5846 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005847 ) {
5848 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005849 var++;
5850 exp_op = 'L';
5851 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005852 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005853 if (exp_saveptr /* if 2nd char is one of expansion operators */
5854 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5855 ) {
5856 /* ${?:0}, ${#[:]%0} etc */
5857 exp_saveptr = var + 1;
5858 } else {
5859 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5860 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5861 }
5862 exp_op = exp_save = *exp_saveptr;
5863 if (exp_op) {
5864 exp_word = exp_saveptr + 1;
5865 if (exp_op == ':') {
5866 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005867//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005868 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005869 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005870 ) {
5871 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5872 exp_op = ':';
5873 exp_word--;
5874 }
5875 }
5876 *exp_saveptr = '\0';
5877 } /* else: it's not an expansion op, but bare ${var} */
5878 }
5879
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005880 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005881 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005882 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005883 int n = xatoi_positive(var);
5884 if (n < G.global_argc)
5885 val = G.global_argv[n];
5886 /* else val remains NULL: $N with too big N */
5887 } else {
5888 switch (var[0]) {
5889 case '$': /* pid */
5890 val = utoa(G.root_pid);
5891 break;
5892 case '!': /* bg pid */
5893 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5894 break;
5895 case '?': /* exitcode */
5896 val = utoa(G.last_exitcode);
5897 break;
5898 case '#': /* argc */
5899 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5900 break;
5901 default:
5902 val = get_local_var_value(var);
5903 }
5904 }
5905
5906 /* Handle any expansions */
5907 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005908 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005909 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005910 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005911 debug_printf_expand("%s\n", val);
5912 } else if (exp_op) {
5913 if (exp_op == '%' || exp_op == '#') {
5914 /* Standard-mandated substring removal ops:
5915 * ${parameter%word} - remove smallest suffix pattern
5916 * ${parameter%%word} - remove largest suffix pattern
5917 * ${parameter#word} - remove smallest prefix pattern
5918 * ${parameter##word} - remove largest prefix pattern
5919 *
5920 * Word is expanded to produce a glob pattern.
5921 * Then var's value is matched to it and matching part removed.
5922 */
5923 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005924 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005925 char *exp_exp_word;
5926 char *loc;
5927 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005928 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005929 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005930 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005931 /*
5932 * process_bkslash:1 unbackslash:1 breaks this:
5933 * a='a\\'; echo ${a%\\\\} # correct output is: a
5934 * process_bkslash:1 unbackslash:0 breaks this:
5935 * a='a}'; echo ${a%\}} # correct output is: a
5936 */
5937 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005938 if (exp_exp_word)
5939 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005940 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005941 /* HACK ALERT. We depend here on the fact that
5942 * G.global_argv and results of utoa and get_local_var_value
5943 * are actually in writable memory:
5944 * scan_and_match momentarily stores NULs there. */
5945 t = (char*)val;
5946 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005947 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 +02005948 free(exp_exp_word);
5949 if (loc) { /* match was found */
5950 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005951 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005953 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005954 }
5955 }
5956 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005957#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005958 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005959 /* It's ${var/[/]pattern[/repl]} thing.
5960 * Note that in encoded form it has TWO parts:
5961 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005962 * and if // is used, it is encoded as \:
5963 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005964 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005965 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005966 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005967 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005968 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02005969 * >az >bz
5970 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
5971 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
5972 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
5973 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005974 * (note that a*z _pattern_ is never globbed!)
5975 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005976 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005977 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005978 if (!pattern)
5979 pattern = xstrdup(exp_word);
5980 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5981 *p++ = SPECIAL_VAR_SYMBOL;
5982 exp_word = p;
5983 p = strchr(p, SPECIAL_VAR_SYMBOL);
5984 *p = '\0';
Denys Vlasenkode026252018-04-05 17:04:53 +02005985 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005986 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5987 /* HACK ALERT. We depend here on the fact that
5988 * G.global_argv and results of utoa and get_local_var_value
5989 * are actually in writable memory:
5990 * replace_pattern momentarily stores NULs there. */
5991 t = (char*)val;
5992 to_be_freed = replace_pattern(t,
5993 pattern,
5994 (repl ? repl : exp_word),
5995 exp_op);
5996 if (to_be_freed) /* at least one replace happened */
5997 val = to_be_freed;
5998 free(pattern);
5999 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006000 } else {
6001 /* Empty variable always gives nothing */
6002 // "v=''; echo ${v/*/w}" prints "", not "w"
6003 /* Just skip "replace" part */
6004 *p++ = SPECIAL_VAR_SYMBOL;
6005 p = strchr(p, SPECIAL_VAR_SYMBOL);
6006 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006007 }
6008 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006009#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006010 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006011#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006012 /* It's ${var:N[:M]} bashism.
6013 * Note that in encoded form it has TWO parts:
6014 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6015 */
6016 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006017 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006018
Denys Vlasenko063847d2010-09-15 13:33:02 +02006019 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6020 if (errmsg)
6021 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006022 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6023 *p++ = SPECIAL_VAR_SYMBOL;
6024 exp_word = p;
6025 p = strchr(p, SPECIAL_VAR_SYMBOL);
6026 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006027 len = expand_and_evaluate_arith(exp_word, &errmsg);
6028 if (errmsg)
6029 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006030 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006031 if (beg < 0) {
6032 /* negative beg counts from the end */
6033 beg = (arith_t)strlen(val) + beg;
6034 if (beg < 0) /* ${v: -999999} is "" */
6035 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006036 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006037 debug_printf_varexp("from val:'%s'\n", val);
6038 if (len < 0) {
6039 /* in bash, len=-n means strlen()-n */
6040 len = (arith_t)strlen(val) - beg + len;
6041 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006042 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006043 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006044 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006045 arith_err:
6046 val = NULL;
6047 } else {
6048 /* Paranoia. What if user entered 9999999999999
6049 * which fits in arith_t but not int? */
6050 if (len >= INT_MAX)
6051 len = INT_MAX;
6052 val = to_be_freed = xstrndup(val + beg, len);
6053 }
6054 debug_printf_varexp("val:'%s'\n", val);
6055#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006056 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006057 val = NULL;
6058#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006059 } else { /* one of "-=+?" */
6060 /* Standard-mandated substitution ops:
6061 * ${var?word} - indicate error if unset
6062 * If var is unset, word (or a message indicating it is unset
6063 * if word is null) is written to standard error
6064 * and the shell exits with a non-zero exit status.
6065 * Otherwise, the value of var is substituted.
6066 * ${var-word} - use default value
6067 * If var is unset, word is substituted.
6068 * ${var=word} - assign and use default value
6069 * If var is unset, word is assigned to var.
6070 * In all cases, final value of var is substituted.
6071 * ${var+word} - use alternative value
6072 * If var is unset, null is substituted.
6073 * Otherwise, word is substituted.
6074 *
6075 * Word is subjected to tilde expansion, parameter expansion,
6076 * command substitution, and arithmetic expansion.
6077 * If word is not needed, it is not expanded.
6078 *
6079 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6080 * but also treat null var as if it is unset.
6081 */
6082 int use_word = (!val || ((exp_save == ':') && !val[0]));
6083 if (exp_op == '+')
6084 use_word = !use_word;
6085 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6086 (exp_save == ':') ? "true" : "false", use_word);
6087 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006088 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006089 if (to_be_freed)
6090 exp_word = to_be_freed;
6091 if (exp_op == '?') {
6092 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006093 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006094 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006095 exp_word[0]
6096 ? exp_word
6097 : "parameter null or not set"
6098 /* ash has more specific messages, a-la: */
6099 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006100 );
6101//TODO: how interactive bash aborts expansion mid-command?
6102 } else {
6103 val = exp_word;
6104 }
6105
6106 if (exp_op == '=') {
6107 /* ${var=[word]} or ${var:=[word]} */
6108 if (isdigit(var[0]) || var[0] == '#') {
6109 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006110 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006111 val = NULL;
6112 } else {
6113 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006114 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006115 }
6116 }
6117 }
6118 } /* one of "-=+?" */
6119
6120 *exp_saveptr = exp_save;
6121 } /* if (exp_op) */
6122
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006123 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006124
6125 *pp = p;
6126 *to_be_freed_pp = to_be_freed;
6127 return val;
6128}
6129
6130/* Expand all variable references in given string, adding words to list[]
6131 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6132 * to be filled). This routine is extremely tricky: has to deal with
6133 * variables/parameters with whitespace, $* and $@, and constructs like
6134 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006135static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006136{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006137 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006139 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006140 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006141 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006142 char *p;
6143
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006144 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6145 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006146 debug_print_list("expand_vars_to_list", output, n);
6147 n = o_save_ptr(output, n);
6148 debug_print_list("expand_vars_to_list[0]", output, n);
6149
6150 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6151 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006152 char *to_be_freed = NULL;
6153 const char *val = NULL;
6154#if ENABLE_HUSH_TICK
6155 o_string subst_result = NULL_O_STRING;
6156#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006157#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006158 char arith_buf[sizeof(arith_t)*3 + 2];
6159#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006160
6161 if (ended_in_ifs) {
6162 o_addchr(output, '\0');
6163 n = o_save_ptr(output, n);
6164 ended_in_ifs = 0;
6165 }
6166
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006167 o_addblock(output, arg, p - arg);
6168 debug_print_list("expand_vars_to_list[1]", output, n);
6169 arg = ++p;
6170 p = strchr(p, SPECIAL_VAR_SYMBOL);
6171
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006172 /* Fetch special var name (if it is indeed one of them)
6173 * and quote bit, force the bit on if singleword expansion -
6174 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006175 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006176
6177 /* Is this variable quoted and thus expansion can't be null?
6178 * "$@" is special. Even if quoted, it can still
6179 * expand to nothing (not even an empty string),
6180 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006181 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006182 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006183
6184 switch (first_ch & 0x7f) {
6185 /* Highest bit in first_ch indicates that var is double-quoted */
6186 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006187 case '@': {
6188 int i;
6189 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006190 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006191 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006192 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006193 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006194 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006195 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006196 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6197 if (G.global_argv[i++][0] && G.global_argv[i]) {
6198 /* this argv[] is not empty and not last:
6199 * put terminating NUL, start new word */
6200 o_addchr(output, '\0');
6201 debug_print_list("expand_vars_to_list[2]", output, n);
6202 n = o_save_ptr(output, n);
6203 debug_print_list("expand_vars_to_list[3]", output, n);
6204 }
6205 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006206 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006207 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006208 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006209 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006210 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006211 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006212 while (1) {
6213 o_addQstr(output, G.global_argv[i]);
6214 if (++i >= G.global_argc)
6215 break;
6216 o_addchr(output, '\0');
6217 debug_print_list("expand_vars_to_list[4]", output, n);
6218 n = o_save_ptr(output, n);
6219 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006220 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006221 while (1) {
6222 o_addQstr(output, G.global_argv[i]);
6223 if (!G.global_argv[++i])
6224 break;
6225 if (G.ifs[0])
6226 o_addchr(output, G.ifs[0]);
6227 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006228 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006229 }
6230 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006231 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006232 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6233 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006234 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006235 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006236 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006237 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006238 case SPECIAL_VAR_QUOTED_SVS:
6239 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6240 arg++;
6241 val = SPECIAL_VAR_SYMBOL_STR;
6242 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006243#if ENABLE_HUSH_TICK
6244 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006245 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006246 arg++;
6247 /* Can't just stuff it into output o_string,
6248 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006249 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006250 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6251 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006252 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006253 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6254 val = subst_result.data;
6255 goto store_val;
6256#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006257#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006258 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6259 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006260
6261 arg++; /* skip '+' */
6262 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6263 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006264 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006265 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6266 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267 val = arith_buf;
6268 break;
6269 }
6270#endif
6271 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006272 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006273 IF_HUSH_TICK(store_val:)
6274 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006275 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6276 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006277 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006278 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006280 }
6281 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006282 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006283 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6284 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006285 }
6286 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006287 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6288
6289 if (val && val[0]) {
6290 o_addQstr(output, val);
6291 }
6292 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006293
6294 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6295 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006296 if (*p != SPECIAL_VAR_SYMBOL)
6297 *p = SPECIAL_VAR_SYMBOL;
6298
6299#if ENABLE_HUSH_TICK
6300 o_free(&subst_result);
6301#endif
6302 arg = ++p;
6303 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6304
6305 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006306 if (ended_in_ifs) {
6307 o_addchr(output, '\0');
6308 n = o_save_ptr(output, n);
6309 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 debug_print_list("expand_vars_to_list[a]", output, n);
6311 /* this part is literal, and it was already pre-quoted
6312 * if needed (much earlier), do not use o_addQstr here! */
6313 o_addstr_with_NUL(output, arg);
6314 debug_print_list("expand_vars_to_list[b]", output, n);
6315 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006316 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006317 ) {
6318 n--;
6319 /* allow to reuse list[n] later without re-growth */
6320 output->has_empty_slot = 1;
6321 } else {
6322 o_addchr(output, '\0');
6323 }
6324
6325 return n;
6326}
6327
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006328static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006329{
6330 int n;
6331 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006332 o_string output = NULL_O_STRING;
6333
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006334 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006335
6336 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006337 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006338 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006339 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006340 }
6341 debug_print_list("expand_variables", &output, n);
6342
6343 /* output.data (malloced in one block) gets returned in "list" */
6344 list = o_finalize_list(&output, n);
6345 debug_print_strings("expand_variables[1]", list);
6346 return list;
6347}
6348
6349static char **expand_strvec_to_strvec(char **argv)
6350{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006351 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352}
6353
Denys Vlasenko11752d42018-04-03 08:20:58 +02006354#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6356{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006357 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006358}
6359#endif
6360
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006361/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006362 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006363 *
6364 * NB: should NOT do globbing!
6365 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6366 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006367static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006369#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006370 const int do_unbackslash = 1;
6371#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006372 char *argv[2], **list;
6373
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006374 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375 /* This is generally an optimization, but it also
6376 * handles "", which otherwise trips over !list[0] check below.
6377 * (is this ever happens that we actually get str="" here?)
6378 */
6379 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6380 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006381 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006382 return xstrdup(str);
6383 }
6384
6385 argv[0] = (char*)str;
6386 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006387 list = expand_variables(argv, do_unbackslash
6388 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6389 : EXP_FLAG_SINGLEWORD
6390 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006391 if (HUSH_DEBUG)
6392 if (!list[0] || list[1])
6393 bb_error_msg_and_die("BUG in varexp2");
6394 /* actually, just move string 2*sizeof(char*) bytes back */
6395 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006396 if (do_unbackslash)
6397 unbackslash((char*)list);
6398 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006399 return (char*)list;
6400}
6401
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006402#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403static char* expand_strvec_to_string(char **argv)
6404{
6405 char **list;
6406
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006407 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006408 /* Convert all NULs to spaces */
6409 if (list[0]) {
6410 int n = 1;
6411 while (list[n]) {
6412 if (HUSH_DEBUG)
6413 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6414 bb_error_msg_and_die("BUG in varexp3");
6415 /* bash uses ' ' regardless of $IFS contents */
6416 list[n][-1] = ' ';
6417 n++;
6418 }
6419 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006420 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006421 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6422 return (char*)list;
6423}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006424#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006425
6426static char **expand_assignments(char **argv, int count)
6427{
6428 int i;
6429 char **p;
6430
6431 G.expanded_assignments = p = NULL;
6432 /* Expand assignments into one string each */
6433 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006434 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006435 }
6436 G.expanded_assignments = NULL;
6437 return p;
6438}
6439
6440
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006441static void switch_off_special_sigs(unsigned mask)
6442{
6443 unsigned sig = 0;
6444 while ((mask >>= 1) != 0) {
6445 sig++;
6446 if (!(mask & 1))
6447 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006448#if ENABLE_HUSH_TRAP
6449 if (G_traps) {
6450 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006451 /* trap is '', has to remain SIG_IGN */
6452 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006453 free(G_traps[sig]);
6454 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006455 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006456#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006457 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006458 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006459 }
6460}
6461
Denys Vlasenkob347df92011-08-09 22:49:15 +02006462#if BB_MMU
6463/* never called */
6464void re_execute_shell(char ***to_free, const char *s,
6465 char *g_argv0, char **g_argv,
6466 char **builtin_argv) NORETURN;
6467
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006468static void reset_traps_to_defaults(void)
6469{
6470 /* This function is always called in a child shell
6471 * after fork (not vfork, NOMMU doesn't use this function).
6472 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006473 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006474 unsigned mask;
6475
6476 /* Child shells are not interactive.
6477 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6478 * Testcase: (while :; do :; done) + ^Z should background.
6479 * Same goes for SIGTERM, SIGHUP, SIGINT.
6480 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006481 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006482 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006483 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006484
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006485 /* Switch off special sigs */
6486 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006487# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006488 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006489# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006490 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006491 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6492 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006493
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006494# if ENABLE_HUSH_TRAP
6495 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006496 return;
6497
6498 /* Reset all sigs to default except ones with empty traps */
6499 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006500 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006501 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006502 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006503 continue; /* empty trap: has to remain SIG_IGN */
6504 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006505 free(G_traps[sig]);
6506 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006507 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006508 if (sig == 0)
6509 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006510 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006511 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006512# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006513}
6514
6515#else /* !BB_MMU */
6516
6517static void re_execute_shell(char ***to_free, const char *s,
6518 char *g_argv0, char **g_argv,
6519 char **builtin_argv) NORETURN;
6520static void re_execute_shell(char ***to_free, const char *s,
6521 char *g_argv0, char **g_argv,
6522 char **builtin_argv)
6523{
6524# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6525 /* delims + 2 * (number of bytes in printed hex numbers) */
6526 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6527 char *heredoc_argv[4];
6528 struct variable *cur;
6529# if ENABLE_HUSH_FUNCTIONS
6530 struct function *funcp;
6531# endif
6532 char **argv, **pp;
6533 unsigned cnt;
6534 unsigned long long empty_trap_mask;
6535
6536 if (!g_argv0) { /* heredoc */
6537 argv = heredoc_argv;
6538 argv[0] = (char *) G.argv0_for_re_execing;
6539 argv[1] = (char *) "-<";
6540 argv[2] = (char *) s;
6541 argv[3] = NULL;
6542 pp = &argv[3]; /* used as pointer to empty environment */
6543 goto do_exec;
6544 }
6545
6546 cnt = 0;
6547 pp = builtin_argv;
6548 if (pp) while (*pp++)
6549 cnt++;
6550
6551 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006552 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 int sig;
6554 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006555 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006556 empty_trap_mask |= 1LL << sig;
6557 }
6558 }
6559
6560 sprintf(param_buf, NOMMU_HACK_FMT
6561 , (unsigned) G.root_pid
6562 , (unsigned) G.root_ppid
6563 , (unsigned) G.last_bg_pid
6564 , (unsigned) G.last_exitcode
6565 , cnt
6566 , empty_trap_mask
6567 IF_HUSH_LOOPS(, G.depth_of_loop)
6568 );
6569# undef NOMMU_HACK_FMT
6570 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6571 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6572 */
6573 cnt += 6;
6574 for (cur = G.top_var; cur; cur = cur->next) {
6575 if (!cur->flg_export || cur->flg_read_only)
6576 cnt += 2;
6577 }
6578# if ENABLE_HUSH_FUNCTIONS
6579 for (funcp = G.top_func; funcp; funcp = funcp->next)
6580 cnt += 3;
6581# endif
6582 pp = g_argv;
6583 while (*pp++)
6584 cnt++;
6585 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6586 *pp++ = (char *) G.argv0_for_re_execing;
6587 *pp++ = param_buf;
6588 for (cur = G.top_var; cur; cur = cur->next) {
6589 if (strcmp(cur->varstr, hush_version_str) == 0)
6590 continue;
6591 if (cur->flg_read_only) {
6592 *pp++ = (char *) "-R";
6593 *pp++ = cur->varstr;
6594 } else if (!cur->flg_export) {
6595 *pp++ = (char *) "-V";
6596 *pp++ = cur->varstr;
6597 }
6598 }
6599# if ENABLE_HUSH_FUNCTIONS
6600 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6601 *pp++ = (char *) "-F";
6602 *pp++ = funcp->name;
6603 *pp++ = funcp->body_as_string;
6604 }
6605# endif
6606 /* We can pass activated traps here. Say, -Tnn:trap_string
6607 *
6608 * However, POSIX says that subshells reset signals with traps
6609 * to SIG_DFL.
6610 * I tested bash-3.2 and it not only does that with true subshells
6611 * of the form ( list ), but with any forked children shells.
6612 * I set trap "echo W" WINCH; and then tried:
6613 *
6614 * { echo 1; sleep 20; echo 2; } &
6615 * while true; do echo 1; sleep 20; echo 2; break; done &
6616 * true | { echo 1; sleep 20; echo 2; } | cat
6617 *
6618 * In all these cases sending SIGWINCH to the child shell
6619 * did not run the trap. If I add trap "echo V" WINCH;
6620 * _inside_ group (just before echo 1), it works.
6621 *
6622 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006623 */
6624 *pp++ = (char *) "-c";
6625 *pp++ = (char *) s;
6626 if (builtin_argv) {
6627 while (*++builtin_argv)
6628 *pp++ = *builtin_argv;
6629 *pp++ = (char *) "";
6630 }
6631 *pp++ = g_argv0;
6632 while (*g_argv)
6633 *pp++ = *g_argv++;
6634 /* *pp = NULL; - is already there */
6635 pp = environ;
6636
6637 do_exec:
6638 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006639 /* Don't propagate SIG_IGN to the child */
6640 if (SPECIAL_JOBSTOP_SIGS != 0)
6641 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006642 execve(bb_busybox_exec_path, argv, pp);
6643 /* Fallback. Useful for init=/bin/hush usage etc */
6644 if (argv[0][0] == '/')
6645 execve(argv[0], argv, pp);
6646 xfunc_error_retval = 127;
6647 bb_error_msg_and_die("can't re-execute the shell");
6648}
6649#endif /* !BB_MMU */
6650
6651
6652static int run_and_free_list(struct pipe *pi);
6653
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006654/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006655 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6656 * end_trigger controls how often we stop parsing
6657 * NUL: parse all, execute, return
6658 * ';': parse till ';' or newline, execute, repeat till EOF
6659 */
6660static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006661{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006662 /* Why we need empty flag?
6663 * An obscure corner case "false; ``; echo $?":
6664 * empty command in `` should still set $? to 0.
6665 * But we can't just set $? to 0 at the start,
6666 * this breaks "false; echo `echo $?`" case.
6667 */
6668 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006669 while (1) {
6670 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006671
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006672#if ENABLE_HUSH_INTERACTIVE
6673 if (end_trigger == ';')
6674 inp->promptmode = 0; /* PS1 */
6675#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006676 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006677 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6678 /* If we are in "big" script
6679 * (not in `cmd` or something similar)...
6680 */
6681 if (pipe_list == ERR_PTR && end_trigger == ';') {
6682 /* Discard cached input (rest of line) */
6683 int ch = inp->last_char;
6684 while (ch != EOF && ch != '\n') {
6685 //bb_error_msg("Discarded:'%c'", ch);
6686 ch = i_getch(inp);
6687 }
6688 /* Force prompt */
6689 inp->p = NULL;
6690 /* This stream isn't empty */
6691 empty = 0;
6692 continue;
6693 }
6694 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006695 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006696 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006697 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006698 debug_print_tree(pipe_list, 0);
6699 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6700 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006701 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006702 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006703 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006704 }
Eric Andersen25f27032001-04-26 23:22:31 +00006705}
6706
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006707static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006708{
6709 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006710 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6711
Eric Andersen25f27032001-04-26 23:22:31 +00006712 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006713 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006714 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006715}
6716
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006717static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006718{
Eric Andersen25f27032001-04-26 23:22:31 +00006719 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006720 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006721
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006722 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006723 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006724 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006725 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006726}
6727
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006728#if ENABLE_HUSH_TICK
6729static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6730{
6731 pid_t pid;
6732 int channel[2];
6733# if !BB_MMU
6734 char **to_free = NULL;
6735# endif
6736
6737 xpipe(channel);
6738 pid = BB_MMU ? xfork() : xvfork();
6739 if (pid == 0) { /* child */
6740 disable_restore_tty_pgrp_on_exit();
6741 /* Process substitution is not considered to be usual
6742 * 'command execution'.
6743 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6744 */
6745 bb_signals(0
6746 + (1 << SIGTSTP)
6747 + (1 << SIGTTIN)
6748 + (1 << SIGTTOU)
6749 , SIG_IGN);
6750 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6751 close(channel[0]); /* NB: close _first_, then move fd! */
6752 xmove_fd(channel[1], 1);
6753 /* Prevent it from trying to handle ctrl-z etc */
6754 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006755# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006756 /* Awful hack for `trap` or $(trap).
6757 *
6758 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6759 * contains an example where "trap" is executed in a subshell:
6760 *
6761 * save_traps=$(trap)
6762 * ...
6763 * eval "$save_traps"
6764 *
6765 * Standard does not say that "trap" in subshell shall print
6766 * parent shell's traps. It only says that its output
6767 * must have suitable form, but then, in the above example
6768 * (which is not supposed to be normative), it implies that.
6769 *
6770 * bash (and probably other shell) does implement it
6771 * (traps are reset to defaults, but "trap" still shows them),
6772 * but as a result, "trap" logic is hopelessly messed up:
6773 *
6774 * # trap
6775 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6776 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6777 * # true | trap <--- trap is in subshell - no output (ditto)
6778 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6779 * trap -- 'echo Ho' SIGWINCH
6780 * # echo `(trap)` <--- in subshell in subshell - output
6781 * trap -- 'echo Ho' SIGWINCH
6782 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6783 * trap -- 'echo Ho' SIGWINCH
6784 *
6785 * The rules when to forget and when to not forget traps
6786 * get really complex and nonsensical.
6787 *
6788 * Our solution: ONLY bare $(trap) or `trap` is special.
6789 */
6790 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006791 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792 && skip_whitespace(s + 4)[0] == '\0'
6793 ) {
6794 static const char *const argv[] = { NULL, NULL };
6795 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006796 fflush_all(); /* important */
6797 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006798 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006799# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006800# if BB_MMU
6801 reset_traps_to_defaults();
6802 parse_and_run_string(s);
6803 _exit(G.last_exitcode);
6804# else
6805 /* We re-execute after vfork on NOMMU. This makes this script safe:
6806 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6807 * huge=`cat BIG` # was blocking here forever
6808 * echo OK
6809 */
6810 re_execute_shell(&to_free,
6811 s,
6812 G.global_argv[0],
6813 G.global_argv + 1,
6814 NULL);
6815# endif
6816 }
6817
6818 /* parent */
6819 *pid_p = pid;
6820# if ENABLE_HUSH_FAST
6821 G.count_SIGCHLD++;
6822//bb_error_msg("[%d] fork in generate_stream_from_string:"
6823// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6824// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6825# endif
6826 enable_restore_tty_pgrp_on_exit();
6827# if !BB_MMU
6828 free(to_free);
6829# endif
6830 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006831 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006832}
6833
6834/* Return code is exit status of the process that is run. */
6835static int process_command_subs(o_string *dest, const char *s)
6836{
6837 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006838 pid_t pid;
6839 int status, ch, eol_cnt;
6840
6841 fp = generate_stream_from_string(s, &pid);
6842
6843 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006845 while ((ch = getc(fp)) != EOF) {
6846 if (ch == '\0')
6847 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006848 if (ch == '\n') {
6849 eol_cnt++;
6850 continue;
6851 }
6852 while (eol_cnt) {
6853 o_addchr(dest, '\n');
6854 eol_cnt--;
6855 }
6856 o_addQchr(dest, ch);
6857 }
6858
6859 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006860 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006861 /* We need to extract exitcode. Test case
6862 * "true; echo `sleep 1; false` $?"
6863 * should print 1 */
6864 safe_waitpid(pid, &status, 0);
6865 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6866 return WEXITSTATUS(status);
6867}
6868#endif /* ENABLE_HUSH_TICK */
6869
6870
6871static void setup_heredoc(struct redir_struct *redir)
6872{
6873 struct fd_pair pair;
6874 pid_t pid;
6875 int len, written;
6876 /* the _body_ of heredoc (misleading field name) */
6877 const char *heredoc = redir->rd_filename;
6878 char *expanded;
6879#if !BB_MMU
6880 char **to_free;
6881#endif
6882
6883 expanded = NULL;
6884 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006885 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006886 if (expanded)
6887 heredoc = expanded;
6888 }
6889 len = strlen(heredoc);
6890
6891 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6892 xpiped_pair(pair);
6893 xmove_fd(pair.rd, redir->rd_fd);
6894
6895 /* Try writing without forking. Newer kernels have
6896 * dynamically growing pipes. Must use non-blocking write! */
6897 ndelay_on(pair.wr);
6898 while (1) {
6899 written = write(pair.wr, heredoc, len);
6900 if (written <= 0)
6901 break;
6902 len -= written;
6903 if (len == 0) {
6904 close(pair.wr);
6905 free(expanded);
6906 return;
6907 }
6908 heredoc += written;
6909 }
6910 ndelay_off(pair.wr);
6911
6912 /* Okay, pipe buffer was not big enough */
6913 /* Note: we must not create a stray child (bastard? :)
6914 * for the unsuspecting parent process. Child creates a grandchild
6915 * and exits before parent execs the process which consumes heredoc
6916 * (that exec happens after we return from this function) */
6917#if !BB_MMU
6918 to_free = NULL;
6919#endif
6920 pid = xvfork();
6921 if (pid == 0) {
6922 /* child */
6923 disable_restore_tty_pgrp_on_exit();
6924 pid = BB_MMU ? xfork() : xvfork();
6925 if (pid != 0)
6926 _exit(0);
6927 /* grandchild */
6928 close(redir->rd_fd); /* read side of the pipe */
6929#if BB_MMU
6930 full_write(pair.wr, heredoc, len); /* may loop or block */
6931 _exit(0);
6932#else
6933 /* Delegate blocking writes to another process */
6934 xmove_fd(pair.wr, STDOUT_FILENO);
6935 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6936#endif
6937 }
6938 /* parent */
6939#if ENABLE_HUSH_FAST
6940 G.count_SIGCHLD++;
6941//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6942#endif
6943 enable_restore_tty_pgrp_on_exit();
6944#if !BB_MMU
6945 free(to_free);
6946#endif
6947 close(pair.wr);
6948 free(expanded);
6949 wait(NULL); /* wait till child has died */
6950}
6951
Denys Vlasenko2db74612017-07-07 22:07:28 +02006952struct squirrel {
6953 int orig_fd;
6954 int moved_to;
6955 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6956 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6957};
6958
Denys Vlasenko621fc502017-07-24 12:42:17 +02006959static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6960{
6961 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6962 sq[i].orig_fd = orig;
6963 sq[i].moved_to = moved;
6964 sq[i+1].orig_fd = -1; /* end marker */
6965 return sq;
6966}
6967
Denys Vlasenko2db74612017-07-07 22:07:28 +02006968static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6969{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006970 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006971 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006972
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006973 i = 0;
6974 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006975 /* If we collide with an already moved fd... */
6976 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006977 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006978 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6979 if (sq[i].moved_to < 0) /* what? */
6980 xfunc_die();
6981 return sq;
6982 }
6983 if (fd == sq[i].orig_fd) {
6984 /* Example: echo Hello >/dev/null 1>&2 */
6985 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6986 return sq;
6987 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006988 }
6989
Denys Vlasenko2db74612017-07-07 22:07:28 +02006990 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006991 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02006992 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6993 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006994 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006995 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006996}
6997
Denys Vlasenko657e9002017-07-30 23:34:04 +02006998static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6999{
7000 int i;
7001
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007002 i = 0;
7003 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007004 /* If we collide with an already moved fd... */
7005 if (fd == sq[i].orig_fd) {
7006 /* Examples:
7007 * "echo 3>FILE 3>&- 3>FILE"
7008 * "echo 3>&- 3>FILE"
7009 * No need for last redirect to insert
7010 * another "need to close 3" indicator.
7011 */
7012 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7013 return sq;
7014 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007015 }
7016
7017 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7018 return append_squirrel(sq, i, fd, -1);
7019}
7020
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007021/* fd: redirect wants this fd to be used (e.g. 3>file).
7022 * Move all conflicting internally used fds,
7023 * and remember them so that we can restore them later.
7024 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007025static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007026{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007027 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7028 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007029
7030#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007031 if (fd == G.interactive_fd) {
7032 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007033 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007034 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7035 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007036 }
7037#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007038 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7039 * (1) Redirect in a forked child. No need to save FILEs' fds,
7040 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007041 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7042 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007043 * "fileno(fd) = new_fd" can't be done.
7044 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007045 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007046 return 0;
7047
Denys Vlasenko2db74612017-07-07 22:07:28 +02007048 /* If this one of script's fds? */
7049 if (save_FILEs_on_redirect(fd, avoid_fd))
7050 return 1; /* yes. "we closed fd" */
7051
7052 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7053 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7054 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007055}
7056
Denys Vlasenko2db74612017-07-07 22:07:28 +02007057static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007058{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007059 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007060 int i;
7061 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007062 if (sq[i].moved_to >= 0) {
7063 /* We simply die on error */
7064 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7065 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7066 } else {
7067 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7068 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7069 close(sq[i].orig_fd);
7070 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007071 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007072 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007073 }
7074
Denys Vlasenko2db74612017-07-07 22:07:28 +02007075 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007076
7077 restore_redirected_FILEs();
7078}
7079
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007080#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007081static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007082{
7083 if (G_interactive_fd)
7084 close(G_interactive_fd);
7085 close_all_FILE_list();
7086}
7087#endif
7088
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007089static int internally_opened_fd(int fd, struct squirrel *sq)
7090{
7091 int i;
7092
7093#if ENABLE_HUSH_INTERACTIVE
7094 if (fd == G.interactive_fd)
7095 return 1;
7096#endif
7097 /* If this one of script's fds? */
7098 if (fd_in_FILEs(fd))
7099 return 1;
7100
7101 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7102 if (fd == sq[i].moved_to)
7103 return 1;
7104 }
7105 return 0;
7106}
7107
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007108/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7109 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007110static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007111{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007112 struct redir_struct *redir;
7113
7114 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007115 int newfd;
7116 int closed;
7117
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007118 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007119 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007120 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007121 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7122 * of the heredoc */
7123 debug_printf_parse("set heredoc '%s'\n",
7124 redir->rd_filename);
7125 setup_heredoc(redir);
7126 continue;
7127 }
7128
7129 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007130 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007131 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007132 int mode;
7133
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007134 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007135 /*
7136 * Examples:
7137 * "cmd >" (no filename)
7138 * "cmd > <file" (2nd redirect starts too early)
7139 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007140 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007141 continue;
7142 }
7143 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007144 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007145 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007146 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007147 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007148 /* Error message from open_or_warn can be lost
7149 * if stderr has been redirected, but bash
7150 * and ash both lose it as well
7151 * (though zsh doesn't!)
7152 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007153 return 1;
7154 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007155 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007156 /* open() gave us precisely the fd we wanted.
7157 * This means that this fd was not busy
7158 * (not opened to anywhere).
7159 * Remember to close it on restore:
7160 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007161 *sqp = add_squirrel_closed(*sqp, newfd);
7162 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007163 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007164 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007165 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7166 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007167 }
7168
Denys Vlasenko657e9002017-07-30 23:34:04 +02007169 if (newfd == redir->rd_fd)
7170 continue;
7171
7172 /* if "N>FILE": move newfd to redir->rd_fd */
7173 /* if "N>&M": dup newfd to redir->rd_fd */
7174 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7175
7176 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7177 if (newfd == REDIRFD_CLOSE) {
7178 /* "N>&-" means "close me" */
7179 if (!closed) {
7180 /* ^^^ optimization: saving may already
7181 * have closed it. If not... */
7182 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007183 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007184 /* Sometimes we do another close on restore, getting EBADF.
7185 * Consider "echo 3>FILE 3>&-"
7186 * first redirect remembers "need to close 3",
7187 * and second redirect closes 3! Restore code then closes 3 again.
7188 */
7189 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007190 /* if newfd is a script fd or saved fd, simulate EBADF */
7191 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7192 //errno = EBADF;
7193 //bb_perror_msg_and_die("can't duplicate file descriptor");
7194 newfd = -1; /* same effect as code above */
7195 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007196 xdup2(newfd, redir->rd_fd);
7197 if (redir->rd_dup == REDIRFD_TO_FILE)
7198 /* "rd_fd > FILE" */
7199 close(newfd);
7200 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007201 }
7202 }
7203 return 0;
7204}
7205
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007206static char *find_in_path(const char *arg)
7207{
7208 char *ret = NULL;
7209 const char *PATH = get_local_var_value("PATH");
7210
7211 if (!PATH)
7212 return NULL;
7213
7214 while (1) {
7215 const char *end = strchrnul(PATH, ':');
7216 int sz = end - PATH; /* must be int! */
7217
7218 free(ret);
7219 if (sz != 0) {
7220 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7221 } else {
7222 /* We have xxx::yyyy in $PATH,
7223 * it means "use current dir" */
7224 ret = xstrdup(arg);
7225 }
7226 if (access(ret, F_OK) == 0)
7227 break;
7228
7229 if (*end == '\0') {
7230 free(ret);
7231 return NULL;
7232 }
7233 PATH = end + 1;
7234 }
7235
7236 return ret;
7237}
7238
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007239static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007240 const struct built_in_command *x,
7241 const struct built_in_command *end)
7242{
7243 while (x != end) {
7244 if (strcmp(name, x->b_cmd) != 0) {
7245 x++;
7246 continue;
7247 }
7248 debug_printf_exec("found builtin '%s'\n", name);
7249 return x;
7250 }
7251 return NULL;
7252}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007253static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007254{
7255 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7256}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007257static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007258{
7259 const struct built_in_command *x = find_builtin1(name);
7260 if (x)
7261 return x;
7262 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7263}
7264
7265#if ENABLE_HUSH_FUNCTIONS
7266static struct function **find_function_slot(const char *name)
7267{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007268 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007269 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007270
7271 while ((funcp = *funcpp) != NULL) {
7272 if (strcmp(name, funcp->name) == 0) {
7273 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007274 break;
7275 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007276 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277 }
7278 return funcpp;
7279}
7280
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007281static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007282{
7283 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007284 return funcp;
7285}
7286
7287/* Note: takes ownership on name ptr */
7288static struct function *new_function(char *name)
7289{
7290 struct function **funcpp = find_function_slot(name);
7291 struct function *funcp = *funcpp;
7292
7293 if (funcp != NULL) {
7294 struct command *cmd = funcp->parent_cmd;
7295 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7296 if (!cmd) {
7297 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7298 free(funcp->name);
7299 /* Note: if !funcp->body, do not free body_as_string!
7300 * This is a special case of "-F name body" function:
7301 * body_as_string was not malloced! */
7302 if (funcp->body) {
7303 free_pipe_list(funcp->body);
7304# if !BB_MMU
7305 free(funcp->body_as_string);
7306# endif
7307 }
7308 } else {
7309 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7310 cmd->argv[0] = funcp->name;
7311 cmd->group = funcp->body;
7312# if !BB_MMU
7313 cmd->group_as_string = funcp->body_as_string;
7314# endif
7315 }
7316 } else {
7317 debug_printf_exec("remembering new function '%s'\n", name);
7318 funcp = *funcpp = xzalloc(sizeof(*funcp));
7319 /*funcp->next = NULL;*/
7320 }
7321
7322 funcp->name = name;
7323 return funcp;
7324}
7325
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007326# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007327static void unset_func(const char *name)
7328{
7329 struct function **funcpp = find_function_slot(name);
7330 struct function *funcp = *funcpp;
7331
7332 if (funcp != NULL) {
7333 debug_printf_exec("freeing function '%s'\n", funcp->name);
7334 *funcpp = funcp->next;
7335 /* funcp is unlinked now, deleting it.
7336 * Note: if !funcp->body, the function was created by
7337 * "-F name body", do not free ->body_as_string
7338 * and ->name as they were not malloced. */
7339 if (funcp->body) {
7340 free_pipe_list(funcp->body);
7341 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007342# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007343 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007344# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007345 }
7346 free(funcp);
7347 }
7348}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007349# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007350
7351# if BB_MMU
7352#define exec_function(to_free, funcp, argv) \
7353 exec_function(funcp, argv)
7354# endif
7355static void exec_function(char ***to_free,
7356 const struct function *funcp,
7357 char **argv) NORETURN;
7358static void exec_function(char ***to_free,
7359 const struct function *funcp,
7360 char **argv)
7361{
7362# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007363 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007364
7365 argv[0] = G.global_argv[0];
7366 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007367 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007368
7369// Example when we are here: "cmd | func"
7370// func will run with saved-redirect fds open.
7371// $ f() { echo /proc/self/fd/*; }
7372// $ true | f
7373// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7374// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7375// Same in script:
7376// $ . ./SCRIPT
7377// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7378// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7379// They are CLOEXEC so external programs won't see them, but
7380// for "more correctness" we might want to close those extra fds here:
7381//? close_saved_fds_and_FILE_fds();
7382
Denys Vlasenko332e4112018-04-04 22:32:59 +02007383 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007384 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007385 G.var_nest_level++;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007386 IF_HUSH_LOCAL(G.func_nest_level++;)
7387
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007388 /* On MMU, funcp->body is always non-NULL */
7389 n = run_list(funcp->body);
7390 fflush_all();
7391 _exit(n);
7392# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007393//? close_saved_fds_and_FILE_fds();
7394
7395//TODO: check whether "true | func_with_return" works
7396
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007397 re_execute_shell(to_free,
7398 funcp->body_as_string,
7399 G.global_argv[0],
7400 argv + 1,
7401 NULL);
7402# endif
7403}
7404
Denys Vlasenko332e4112018-04-04 22:32:59 +02007405static void enter_var_nest_level(void)
7406{
7407 G.var_nest_level++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007408 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007409
7410 /* Try: f() { echo -n .; f; }; f
7411 * struct variable::var_nest_level is uint16_t,
7412 * thus limiting recursion to < 2^16.
7413 * In any case, with 8 Mbyte stack SEGV happens
7414 * not too long after 2^16 recursions anyway.
7415 */
7416 if (G.var_nest_level > 0xff00)
7417 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7418}
7419
7420static void leave_var_nest_level(void)
7421{
7422 struct variable *cur;
7423 struct variable **cur_pp;
7424
7425 cur_pp = &G.top_var;
7426 while ((cur = *cur_pp) != NULL) {
7427 if (cur->var_nest_level < G.var_nest_level) {
7428 cur_pp = &cur->next;
7429 continue;
7430 }
7431 /* Unexport */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007432 if (cur->flg_export) {
7433 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007434 bb_unsetenv(cur->varstr);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007435 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02007436 /* Remove from global list */
7437 *cur_pp = cur->next;
7438 /* Free */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007439 if (!cur->max_len) {
7440 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007441 free(cur->varstr);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007442 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02007443 free(cur);
7444 }
7445
7446 G.var_nest_level--;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007447 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007448 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7449 bb_error_msg_and_die("BUG: nesting underflow");
7450}
7451
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007452static int run_function(const struct function *funcp, char **argv)
7453{
7454 int rc;
7455 save_arg_t sv;
7456 smallint sv_flg;
7457
7458 save_and_replace_G_args(&sv, argv);
7459
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007460 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007461 sv_flg = G_flag_return_in_progress;
7462 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007463
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007464 /* Make "local" variables properly shadow previous ones */
7465 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007466 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007467
7468 /* On MMU, funcp->body is always non-NULL */
7469# if !BB_MMU
7470 if (!funcp->body) {
7471 /* Function defined by -F */
7472 parse_and_run_string(funcp->body_as_string);
7473 rc = G.last_exitcode;
7474 } else
7475# endif
7476 {
7477 rc = run_list(funcp->body);
7478 }
7479
Denys Vlasenko332e4112018-04-04 22:32:59 +02007480 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007481 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007482
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007483 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007484
7485 restore_G_args(&sv, argv);
7486
7487 return rc;
7488}
7489#endif /* ENABLE_HUSH_FUNCTIONS */
7490
7491
7492#if BB_MMU
7493#define exec_builtin(to_free, x, argv) \
7494 exec_builtin(x, argv)
7495#else
7496#define exec_builtin(to_free, x, argv) \
7497 exec_builtin(to_free, argv)
7498#endif
7499static void exec_builtin(char ***to_free,
7500 const struct built_in_command *x,
7501 char **argv) NORETURN;
7502static void exec_builtin(char ***to_free,
7503 const struct built_in_command *x,
7504 char **argv)
7505{
7506#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007507 int rcode;
7508 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007509//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007510 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511 fflush_all();
7512 _exit(rcode);
7513#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007514 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007515 /* On NOMMU, we must never block!
7516 * Example: { sleep 99 | read line; } & echo Ok
7517 */
7518 re_execute_shell(to_free,
7519 argv[0],
7520 G.global_argv[0],
7521 G.global_argv + 1,
7522 argv);
7523#endif
7524}
7525
7526
7527static void execvp_or_die(char **argv) NORETURN;
7528static void execvp_or_die(char **argv)
7529{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007530 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007531 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007532 /* Don't propagate SIG_IGN to the child */
7533 if (SPECIAL_JOBSTOP_SIGS != 0)
7534 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007535 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007536 e = 2;
7537 if (errno == EACCES) e = 126;
7538 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007539 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007540 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007541}
7542
7543#if ENABLE_HUSH_MODE_X
7544static void dump_cmd_in_x_mode(char **argv)
7545{
7546 if (G_x_mode && argv) {
7547 /* We want to output the line in one write op */
7548 char *buf, *p;
7549 int len;
7550 int n;
7551
7552 len = 3;
7553 n = 0;
7554 while (argv[n])
7555 len += strlen(argv[n++]) + 1;
7556 buf = xmalloc(len);
7557 buf[0] = '+';
7558 p = buf + 1;
7559 n = 0;
7560 while (argv[n])
7561 p += sprintf(p, " %s", argv[n++]);
7562 *p++ = '\n';
7563 *p = '\0';
7564 fputs(buf, stderr);
7565 free(buf);
7566 }
7567}
7568#else
7569# define dump_cmd_in_x_mode(argv) ((void)0)
7570#endif
7571
Denys Vlasenko57000292018-01-12 14:41:45 +01007572#if ENABLE_HUSH_COMMAND
7573static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7574{
7575 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007576
Denys Vlasenko57000292018-01-12 14:41:45 +01007577 if (!opt_vV)
7578 return;
7579
7580 to_free = NULL;
7581 if (!explanation) {
7582 char *path = getenv("PATH");
7583 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007584 if (!explanation)
7585 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007586 if (opt_vV != 'V')
7587 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7588 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007589 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007590 free(to_free);
7591 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007592 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007593}
7594#else
7595# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7596#endif
7597
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007598#if BB_MMU
7599#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7600 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7601#define pseudo_exec(nommu_save, command, argv_expanded) \
7602 pseudo_exec(command, argv_expanded)
7603#endif
7604
7605/* Called after [v]fork() in run_pipe, or from builtin_exec.
7606 * Never returns.
7607 * Don't exit() here. If you don't exec, use _exit instead.
7608 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007609 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007610 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007611static void pseudo_exec_argv(nommu_save_t *nommu_save,
7612 char **argv, int assignment_cnt,
7613 char **argv_expanded) NORETURN;
7614static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7615 char **argv, int assignment_cnt,
7616 char **argv_expanded)
7617{
Denys Vlasenko57000292018-01-12 14:41:45 +01007618 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007619 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007620 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007621 IF_HUSH_COMMAND(char opt_vV = 0;)
7622 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007623
7624 new_env = expand_assignments(argv, assignment_cnt);
7625 dump_cmd_in_x_mode(new_env);
7626
7627 if (!argv[assignment_cnt]) {
7628 /* Case when we are here: ... | var=val | ...
7629 * (note that we do not exit early, i.e., do not optimize out
7630 * expand_assignments(): think about ... | var=`sleep 1` | ...
7631 */
7632 free_strings(new_env);
7633 _exit(EXIT_SUCCESS);
7634 }
7635
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007636 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007637#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007638 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007639#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007640 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007641#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007642 set_vars_and_save_old(new_env);
7643 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007644
7645 if (argv_expanded) {
7646 argv = argv_expanded;
7647 } else {
7648 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7649#if !BB_MMU
7650 nommu_save->argv = argv;
7651#endif
7652 }
7653 dump_cmd_in_x_mode(argv);
7654
7655#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7656 if (strchr(argv[0], '/') != NULL)
7657 goto skip;
7658#endif
7659
Denys Vlasenko75481d32017-07-31 05:27:09 +02007660#if ENABLE_HUSH_FUNCTIONS
7661 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007662 funcp = find_function(argv[0]);
7663 if (funcp)
7664 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007665#endif
7666
Denys Vlasenko57000292018-01-12 14:41:45 +01007667#if ENABLE_HUSH_COMMAND
7668 /* "command BAR": run BAR without looking it up among functions
7669 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7670 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7671 */
7672 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7673 char *p;
7674
7675 argv++;
7676 p = *argv;
7677 if (p[0] != '-' || !p[1])
7678 continue; /* bash allows "command command command [-OPT] BAR" */
7679
7680 for (;;) {
7681 p++;
7682 switch (*p) {
7683 case '\0':
7684 argv++;
7685 p = *argv;
7686 if (p[0] != '-' || !p[1])
7687 goto after_opts;
7688 continue; /* next arg is also -opts, process it too */
7689 case 'v':
7690 case 'V':
7691 opt_vV = *p;
7692 continue;
7693 default:
7694 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7695 }
7696 }
7697 }
7698 after_opts:
7699# if ENABLE_HUSH_FUNCTIONS
7700 if (opt_vV && find_function(argv[0]))
7701 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7702# endif
7703#endif
7704
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007705 /* Check if the command matches any of the builtins.
7706 * Depending on context, this might be redundant. But it's
7707 * easier to waste a few CPU cycles than it is to figure out
7708 * if this is one of those cases.
7709 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007710 /* Why "BB_MMU ? :" difference in logic? -
7711 * On NOMMU, it is more expensive to re-execute shell
7712 * just in order to run echo or test builtin.
7713 * It's better to skip it here and run corresponding
7714 * non-builtin later. */
7715 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7716 if (x) {
7717 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7718 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007719 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007720
7721#if ENABLE_FEATURE_SH_STANDALONE
7722 /* Check if the command matches any busybox applets */
7723 {
7724 int a = find_applet_by_name(argv[0]);
7725 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007726 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007727# if BB_MMU /* see above why on NOMMU it is not allowed */
7728 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007729 /* Do not leak open fds from opened script files etc.
7730 * Testcase: interactive "ls -l /proc/self/fd"
7731 * should not show tty fd open.
7732 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007733 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007734//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007735//This casuses test failures in
7736//redir_children_should_not_see_saved_fd_2.tests
7737//redir_children_should_not_see_saved_fd_3.tests
7738//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007739 /* Without this, "rm -i FILE" can't be ^C'ed: */
7740 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007741 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007742 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007743 }
7744# endif
7745 /* Re-exec ourselves */
7746 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007747 /* Don't propagate SIG_IGN to the child */
7748 if (SPECIAL_JOBSTOP_SIGS != 0)
7749 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007750 execv(bb_busybox_exec_path, argv);
7751 /* If they called chroot or otherwise made the binary no longer
7752 * executable, fall through */
7753 }
7754 }
7755#endif
7756
7757#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7758 skip:
7759#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007760 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007761 execvp_or_die(argv);
7762}
7763
7764/* Called after [v]fork() in run_pipe
7765 */
7766static void pseudo_exec(nommu_save_t *nommu_save,
7767 struct command *command,
7768 char **argv_expanded) NORETURN;
7769static void pseudo_exec(nommu_save_t *nommu_save,
7770 struct command *command,
7771 char **argv_expanded)
7772{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007773#if ENABLE_HUSH_FUNCTIONS
7774 if (command->cmd_type == CMD_FUNCDEF) {
7775 /* Ignore funcdefs in pipes:
7776 * true | f() { cmd }
7777 */
7778 _exit(0);
7779 }
7780#endif
7781
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007782 if (command->argv) {
7783 pseudo_exec_argv(nommu_save, command->argv,
7784 command->assignment_cnt, argv_expanded);
7785 }
7786
7787 if (command->group) {
7788 /* Cases when we are here:
7789 * ( list )
7790 * { list } &
7791 * ... | ( list ) | ...
7792 * ... | { list } | ...
7793 */
7794#if BB_MMU
7795 int rcode;
7796 debug_printf_exec("pseudo_exec: run_list\n");
7797 reset_traps_to_defaults();
7798 rcode = run_list(command->group);
7799 /* OK to leak memory by not calling free_pipe_list,
7800 * since this process is about to exit */
7801 _exit(rcode);
7802#else
7803 re_execute_shell(&nommu_save->argv_from_re_execing,
7804 command->group_as_string,
7805 G.global_argv[0],
7806 G.global_argv + 1,
7807 NULL);
7808#endif
7809 }
7810
7811 /* Case when we are here: ... | >file */
7812 debug_printf_exec("pseudo_exec'ed null command\n");
7813 _exit(EXIT_SUCCESS);
7814}
7815
7816#if ENABLE_HUSH_JOB
7817static const char *get_cmdtext(struct pipe *pi)
7818{
7819 char **argv;
7820 char *p;
7821 int len;
7822
7823 /* This is subtle. ->cmdtext is created only on first backgrounding.
7824 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7825 * On subsequent bg argv is trashed, but we won't use it */
7826 if (pi->cmdtext)
7827 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007828
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007829 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007830 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007831 pi->cmdtext = xzalloc(1);
7832 return pi->cmdtext;
7833 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007834 len = 0;
7835 do {
7836 len += strlen(*argv) + 1;
7837 } while (*++argv);
7838 p = xmalloc(len);
7839 pi->cmdtext = p;
7840 argv = pi->cmds[0].argv;
7841 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007842 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007843 *p++ = ' ';
7844 } while (*++argv);
7845 p[-1] = '\0';
7846 return pi->cmdtext;
7847}
7848
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007849static void remove_job_from_table(struct pipe *pi)
7850{
7851 struct pipe *prev_pipe;
7852
7853 if (pi == G.job_list) {
7854 G.job_list = pi->next;
7855 } else {
7856 prev_pipe = G.job_list;
7857 while (prev_pipe->next != pi)
7858 prev_pipe = prev_pipe->next;
7859 prev_pipe->next = pi->next;
7860 }
7861 G.last_jobid = 0;
7862 if (G.job_list)
7863 G.last_jobid = G.job_list->jobid;
7864}
7865
7866static void delete_finished_job(struct pipe *pi)
7867{
7868 remove_job_from_table(pi);
7869 free_pipe(pi);
7870}
7871
7872static void clean_up_last_dead_job(void)
7873{
7874 if (G.job_list && !G.job_list->alive_cmds)
7875 delete_finished_job(G.job_list);
7876}
7877
Denys Vlasenko16096292017-07-10 10:00:28 +02007878static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879{
7880 struct pipe *job, **jobp;
7881 int i;
7882
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007883 clean_up_last_dead_job();
7884
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007885 /* Find the end of the list, and find next job ID to use */
7886 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007887 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007888 while ((job = *jobp) != NULL) {
7889 if (job->jobid > i)
7890 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007891 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007892 }
7893 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007894
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007895 /* Create a new job struct at the end */
7896 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007897 job->next = NULL;
7898 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7899 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7900 for (i = 0; i < pi->num_cmds; i++) {
7901 job->cmds[i].pid = pi->cmds[i].pid;
7902 /* all other fields are not used and stay zero */
7903 }
7904 job->cmdtext = xstrdup(get_cmdtext(pi));
7905
7906 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007907 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007908 G.last_jobid = job->jobid;
7909}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007910#endif /* JOB */
7911
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007912static int job_exited_or_stopped(struct pipe *pi)
7913{
7914 int rcode, i;
7915
7916 if (pi->alive_cmds != pi->stopped_cmds)
7917 return -1;
7918
7919 /* All processes in fg pipe have exited or stopped */
7920 rcode = 0;
7921 i = pi->num_cmds;
7922 while (--i >= 0) {
7923 rcode = pi->cmds[i].cmd_exitcode;
7924 /* usually last process gives overall exitstatus,
7925 * but with "set -o pipefail", last *failed* process does */
7926 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7927 break;
7928 }
7929 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7930 return rcode;
7931}
7932
Denys Vlasenko7e675362016-10-28 21:57:31 +02007933static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007934{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007935#if ENABLE_HUSH_JOB
7936 struct pipe *pi;
7937#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007938 int i, dead;
7939
7940 dead = WIFEXITED(status) || WIFSIGNALED(status);
7941
7942#if DEBUG_JOBS
7943 if (WIFSTOPPED(status))
7944 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7945 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7946 if (WIFSIGNALED(status))
7947 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7948 childpid, WTERMSIG(status), WEXITSTATUS(status));
7949 if (WIFEXITED(status))
7950 debug_printf_jobs("pid %d exited, exitcode %d\n",
7951 childpid, WEXITSTATUS(status));
7952#endif
7953 /* Were we asked to wait for a fg pipe? */
7954 if (fg_pipe) {
7955 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007956
Denys Vlasenko7e675362016-10-28 21:57:31 +02007957 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007958 int rcode;
7959
Denys Vlasenko7e675362016-10-28 21:57:31 +02007960 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7961 if (fg_pipe->cmds[i].pid != childpid)
7962 continue;
7963 if (dead) {
7964 int ex;
7965 fg_pipe->cmds[i].pid = 0;
7966 fg_pipe->alive_cmds--;
7967 ex = WEXITSTATUS(status);
7968 /* bash prints killer signal's name for *last*
7969 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7970 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7971 */
7972 if (WIFSIGNALED(status)) {
7973 int sig = WTERMSIG(status);
7974 if (i == fg_pipe->num_cmds-1)
7975 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7976 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7977 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7978 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7979 * Maybe we need to use sig | 128? */
7980 ex = sig + 128;
7981 }
7982 fg_pipe->cmds[i].cmd_exitcode = ex;
7983 } else {
7984 fg_pipe->stopped_cmds++;
7985 }
7986 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7987 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007988 rcode = job_exited_or_stopped(fg_pipe);
7989 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007990/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7991 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7992 * and "killall -STOP cat" */
7993 if (G_interactive_fd) {
7994#if ENABLE_HUSH_JOB
7995 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007996 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007997#endif
7998 return rcode;
7999 }
8000 if (fg_pipe->alive_cmds == 0)
8001 return rcode;
8002 }
8003 /* There are still running processes in the fg_pipe */
8004 return -1;
8005 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008006 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008007 }
8008
8009#if ENABLE_HUSH_JOB
8010 /* We were asked to wait for bg or orphaned children */
8011 /* No need to remember exitcode in this case */
8012 for (pi = G.job_list; pi; pi = pi->next) {
8013 for (i = 0; i < pi->num_cmds; i++) {
8014 if (pi->cmds[i].pid == childpid)
8015 goto found_pi_and_prognum;
8016 }
8017 }
8018 /* Happens when shell is used as init process (init=/bin/sh) */
8019 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8020 return -1; /* this wasn't a process from fg_pipe */
8021
8022 found_pi_and_prognum:
8023 if (dead) {
8024 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008025 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008026 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008027 rcode = 128 + WTERMSIG(status);
8028 pi->cmds[i].cmd_exitcode = rcode;
8029 if (G.last_bg_pid == pi->cmds[i].pid)
8030 G.last_bg_pid_exitcode = rcode;
8031 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008032 pi->alive_cmds--;
8033 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008034 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008035 printf(JOB_STATUS_FORMAT, pi->jobid,
8036 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008037 delete_finished_job(pi);
8038 } else {
8039/*
8040 * bash deletes finished jobs from job table only in interactive mode,
8041 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8042 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8043 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8044 * We only retain one "dead" job, if it's the single job on the list.
8045 * This covers most of real-world scenarios where this is useful.
8046 */
8047 if (pi != G.job_list)
8048 delete_finished_job(pi);
8049 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008050 }
8051 } else {
8052 /* child stopped */
8053 pi->stopped_cmds++;
8054 }
8055#endif
8056 return -1; /* this wasn't a process from fg_pipe */
8057}
8058
8059/* Check to see if any processes have exited -- if they have,
8060 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008061 *
8062 * If non-NULL fg_pipe: wait for its completion or stop.
8063 * Return its exitcode or zero if stopped.
8064 *
8065 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8066 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8067 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8068 * or 0 if no children changed status.
8069 *
8070 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8071 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8072 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008073 */
8074static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8075{
8076 int attributes;
8077 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008078 int rcode = 0;
8079
8080 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8081
8082 attributes = WUNTRACED;
8083 if (fg_pipe == NULL)
8084 attributes |= WNOHANG;
8085
8086 errno = 0;
8087#if ENABLE_HUSH_FAST
8088 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8089//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8090//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8091 /* There was neither fork nor SIGCHLD since last waitpid */
8092 /* Avoid doing waitpid syscall if possible */
8093 if (!G.we_have_children) {
8094 errno = ECHILD;
8095 return -1;
8096 }
8097 if (fg_pipe == NULL) { /* is WNOHANG set? */
8098 /* We have children, but they did not exit
8099 * or stop yet (we saw no SIGCHLD) */
8100 return 0;
8101 }
8102 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8103 }
8104#endif
8105
8106/* Do we do this right?
8107 * bash-3.00# sleep 20 | false
8108 * <ctrl-Z pressed>
8109 * [3]+ Stopped sleep 20 | false
8110 * bash-3.00# echo $?
8111 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8112 * [hush 1.14.0: yes we do it right]
8113 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008114 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008115 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008116#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008117 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008118 i = G.count_SIGCHLD;
8119#endif
8120 childpid = waitpid(-1, &status, attributes);
8121 if (childpid <= 0) {
8122 if (childpid && errno != ECHILD)
8123 bb_perror_msg("waitpid");
8124#if ENABLE_HUSH_FAST
8125 else { /* Until next SIGCHLD, waitpid's are useless */
8126 G.we_have_children = (childpid == 0);
8127 G.handled_SIGCHLD = i;
8128//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8129 }
8130#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008131 /* ECHILD (no children), or 0 (no change in children status) */
8132 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008133 break;
8134 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008135 rcode = process_wait_result(fg_pipe, childpid, status);
8136 if (rcode >= 0) {
8137 /* fg_pipe exited or stopped */
8138 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008139 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008140 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008141 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008142 rcode = WEXITSTATUS(status);
8143 if (WIFSIGNALED(status))
8144 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008145 if (WIFSTOPPED(status))
8146 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8147 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008148 rcode++;
8149 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008150 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008151 /* This wasn't one of our processes, or */
8152 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008153 } /* while (waitpid succeeds)... */
8154
8155 return rcode;
8156}
8157
8158#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008159static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008160{
8161 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008162 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008163 if (G_saved_tty_pgrp) {
8164 /* Job finished, move the shell to the foreground */
8165 p = getpgrp(); /* our process group id */
8166 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8167 tcsetpgrp(G_interactive_fd, p);
8168 }
8169 return rcode;
8170}
8171#endif
8172
8173/* Start all the jobs, but don't wait for anything to finish.
8174 * See checkjobs().
8175 *
8176 * Return code is normally -1, when the caller has to wait for children
8177 * to finish to determine the exit status of the pipe. If the pipe
8178 * is a simple builtin command, however, the action is done by the
8179 * time run_pipe returns, and the exit code is provided as the
8180 * return value.
8181 *
8182 * Returns -1 only if started some children. IOW: we have to
8183 * mask out retvals of builtins etc with 0xff!
8184 *
8185 * The only case when we do not need to [v]fork is when the pipe
8186 * is single, non-backgrounded, non-subshell command. Examples:
8187 * cmd ; ... { list } ; ...
8188 * cmd && ... { list } && ...
8189 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008190 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008191 * or (if SH_STANDALONE) an applet, and we can run the { list }
8192 * with run_list. If it isn't one of these, we fork and exec cmd.
8193 *
8194 * Cases when we must fork:
8195 * non-single: cmd | cmd
8196 * backgrounded: cmd & { list } &
8197 * subshell: ( list ) [&]
8198 */
8199#if !ENABLE_HUSH_MODE_X
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008200#define redirect_and_varexp_helper(old_vars_p, command, squirrel, argv_expanded) \
8201 redirect_and_varexp_helper(old_vars_p, command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008202#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008203static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008204 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008205 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008206 char **argv_expanded)
8207{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008208 /* Assignments occur before redirects. Try:
8209 * a=`sleep 1` sleep 2 3>/qwe/rty
8210 */
8211
8212 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8213 dump_cmd_in_x_mode(new_env);
8214 dump_cmd_in_x_mode(argv_expanded);
8215 /* this takes ownership of new_env[i] elements, and frees new_env: */
8216 set_vars_and_save_old(new_env);
8217
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008218 /* setup_redirects acts on file descriptors, not FILEs.
8219 * This is perfect for work that comes after exec().
8220 * Is it really safe for inline use? Experimentally,
8221 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008222 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008223}
8224static NOINLINE int run_pipe(struct pipe *pi)
8225{
8226 static const char *const null_ptr = NULL;
8227
8228 int cmd_no;
8229 int next_infd;
8230 struct command *command;
8231 char **argv_expanded;
8232 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008233 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008234 int rcode;
8235
8236 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8237 debug_enter();
8238
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008239 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8240 * Result should be 3 lines: q w e, qwe, q w e
8241 */
8242 G.ifs = get_local_var_value("IFS");
8243 if (!G.ifs)
8244 G.ifs = defifs;
8245
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008246 IF_HUSH_JOB(pi->pgrp = -1;)
8247 pi->stopped_cmds = 0;
8248 command = &pi->cmds[0];
8249 argv_expanded = NULL;
8250
8251 if (pi->num_cmds != 1
8252 || pi->followup == PIPE_BG
8253 || command->cmd_type == CMD_SUBSHELL
8254 ) {
8255 goto must_fork;
8256 }
8257
8258 pi->alive_cmds = 1;
8259
8260 debug_printf_exec(": group:%p argv:'%s'\n",
8261 command->group, command->argv ? command->argv[0] : "NONE");
8262
8263 if (command->group) {
8264#if ENABLE_HUSH_FUNCTIONS
8265 if (command->cmd_type == CMD_FUNCDEF) {
8266 /* "executing" func () { list } */
8267 struct function *funcp;
8268
8269 funcp = new_function(command->argv[0]);
8270 /* funcp->name is already set to argv[0] */
8271 funcp->body = command->group;
8272# if !BB_MMU
8273 funcp->body_as_string = command->group_as_string;
8274 command->group_as_string = NULL;
8275# endif
8276 command->group = NULL;
8277 command->argv[0] = NULL;
8278 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8279 funcp->parent_cmd = command;
8280 command->child_func = funcp;
8281
8282 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8283 debug_leave();
8284 return EXIT_SUCCESS;
8285 }
8286#endif
8287 /* { list } */
8288 debug_printf("non-subshell group\n");
8289 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008290 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008291 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008292//FIXME: we need to pass squirrel down into run_list()
8293//for SH_STANDALONE case, or else this construct:
8294// { find /proc/self/fd; true; } >FILE; cmd2
8295//has no way of closing saved fd#1 for "find",
8296//and in SH_STANDALONE mode, "find" is not execed,
8297//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008298 rcode = run_list(command->group) & 0xff;
8299 }
8300 restore_redirects(squirrel);
8301 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8302 debug_leave();
8303 debug_printf_exec("run_pipe: return %d\n", rcode);
8304 return rcode;
8305 }
8306
8307 argv = command->argv ? command->argv : (char **) &null_ptr;
8308 {
8309 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008310 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8311 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008312 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008313 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008314
Denys Vlasenko5807e182018-02-08 19:19:04 +01008315#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008316 if (G.lineno_var)
8317 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8318#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008319
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008320 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008321 /* Assignments, but no command.
8322 * Ensure redirects take effect (that is, create files).
8323 * Try "a=t >file"
8324 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008325 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008326 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008327 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008328 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008329 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008330
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008331 /* Set shell variables */
8332 if (G_x_mode)
8333 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008334 i = 0;
8335 while (i < command->assignment_cnt) {
8336 char *p = expand_string_to_string(argv[i], /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008337 if (G_x_mode)
8338 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008339 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008340 if (set_local_var(p, /*flag:*/ 0)) {
8341 /* assignment to readonly var / putenv error? */
8342 rcode = 1;
8343 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008344 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008345 }
8346 if (G_x_mode)
8347 bb_putchar_stderr('\n');
8348 /* Redirect error sets $? to 1. Otherwise,
8349 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008350 * Else, clear $?:
8351 * false; q=`exit 2`; echo $? - should print 2
8352 * false; x=1; echo $? - should print 0
8353 * Because of the 2nd case, we can't just use G.last_exitcode.
8354 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008355 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008356 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008357 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8358 debug_leave();
8359 debug_printf_exec("run_pipe: return %d\n", rcode);
8360 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008361 }
8362
8363 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008364#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008365 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008366 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008367 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008368#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008369 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008370
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008371 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008372 if (!argv_expanded[0]) {
8373 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008374 /* `false` still has to set exitcode 1 */
8375 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008376 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008377 }
8378
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008379 old_vars = NULL;
8380 sv_shadowed = G.shadowed_vars_pp;
8381
Denys Vlasenko75481d32017-07-31 05:27:09 +02008382 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008383 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8384 IF_HUSH_FUNCTIONS(x = NULL;)
8385 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008386 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008387 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008388 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8389 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008390 /*
8391 * Variable assignments are executed, but then "forgotten":
8392 * a=`sleep 1;echo A` exec 3>&-; echo $a
8393 * sleeps, but prints nothing.
8394 */
8395 enter_var_nest_level();
8396 G.shadowed_vars_pp = &old_vars;
8397 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8398 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008399 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008400
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008401 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008402 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008403
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008404 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008405 * a=b true; env | grep ^a=
8406 */
8407 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008408 /* Collect all variables "shadowed" by helper
8409 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8410 * into old_vars list:
8411 */
8412 G.shadowed_vars_pp = &old_vars;
8413 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008414 if (rcode == 0) {
8415 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008416 /* Do not collect *to old_vars list* vars shadowed
8417 * by e.g. "local VAR" builtin (collect them
8418 * in the previously nested list instead):
8419 * don't want them to be restored immediately
8420 * after "local" completes.
8421 */
8422 G.shadowed_vars_pp = sv_shadowed;
8423
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008424 debug_printf_exec(": builtin '%s' '%s'...\n",
8425 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008426 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008427 rcode = x->b_function(argv_expanded) & 0xff;
8428 fflush_all();
8429 }
8430#if ENABLE_HUSH_FUNCTIONS
8431 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008432 debug_printf_exec(": function '%s' '%s'...\n",
8433 funcp->name, argv_expanded[1]);
8434 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008435 /*
8436 * But do collect *to old_vars list* vars shadowed
8437 * within function execution. To that end, restore
8438 * this pointer _after_ function run:
8439 */
8440 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008441 }
8442#endif
8443 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008444 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008445 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008446 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008447 if (n < 0 || !APPLET_IS_NOFORK(n))
8448 goto must_fork;
8449
8450 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008451 /* Collect all variables "shadowed" by helper into old_vars list */
8452 G.shadowed_vars_pp = &old_vars;
8453 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8454 G.shadowed_vars_pp = sv_shadowed;
8455
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008456 if (rcode == 0) {
8457 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8458 argv_expanded[0], argv_expanded[1]);
8459 /*
8460 * Note: signals (^C) can't interrupt here.
8461 * We remember them and they will be acted upon
8462 * after applet returns.
8463 * This makes applets which can run for a long time
8464 * and/or wait for user input ineligible for NOFORK:
8465 * for example, "yes" or "rm" (rm -i waits for input).
8466 */
8467 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008468 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008469 } else
8470 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008471
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008472 restore_redirects(squirrel);
8473 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008474 leave_var_nest_level();
8475 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008476
8477 /*
8478 * Try "usleep 99999999" + ^C + "echo $?"
8479 * with FEATURE_SH_NOFORK=y.
8480 */
8481 if (!funcp) {
8482 /* It was builtin or nofork.
8483 * if this would be a real fork/execed program,
8484 * it should have died if a fatal sig was received.
8485 * But OTOH, there was no separate process,
8486 * the sig was sent to _shell_, not to non-existing
8487 * child.
8488 * Let's just handle ^C only, this one is obvious:
8489 * we aren't ok with exitcode 0 when ^C was pressed
8490 * during builtin/nofork.
8491 */
8492 if (sigismember(&G.pending_set, SIGINT))
8493 rcode = 128 + SIGINT;
8494 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008495 free(argv_expanded);
8496 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8497 debug_leave();
8498 debug_printf_exec("run_pipe return %d\n", rcode);
8499 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008500 }
8501
8502 must_fork:
8503 /* NB: argv_expanded may already be created, and that
8504 * might include `cmd` runs! Do not rerun it! We *must*
8505 * use argv_expanded if it's non-NULL */
8506
8507 /* Going to fork a child per each pipe member */
8508 pi->alive_cmds = 0;
8509 next_infd = 0;
8510
8511 cmd_no = 0;
8512 while (cmd_no < pi->num_cmds) {
8513 struct fd_pair pipefds;
8514#if !BB_MMU
8515 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008516 nommu_save.old_vars = NULL;
8517 nommu_save.argv = NULL;
8518 nommu_save.argv_from_re_execing = NULL;
8519#endif
8520 command = &pi->cmds[cmd_no];
8521 cmd_no++;
8522 if (command->argv) {
8523 debug_printf_exec(": pipe member '%s' '%s'...\n",
8524 command->argv[0], command->argv[1]);
8525 } else {
8526 debug_printf_exec(": pipe member with no argv\n");
8527 }
8528
8529 /* pipes are inserted between pairs of commands */
8530 pipefds.rd = 0;
8531 pipefds.wr = 1;
8532 if (cmd_no < pi->num_cmds)
8533 xpiped_pair(pipefds);
8534
Denys Vlasenko5807e182018-02-08 19:19:04 +01008535#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008536 if (G.lineno_var)
8537 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8538#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008539
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008540 command->pid = BB_MMU ? fork() : vfork();
8541 if (!command->pid) { /* child */
8542#if ENABLE_HUSH_JOB
8543 disable_restore_tty_pgrp_on_exit();
8544 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8545
8546 /* Every child adds itself to new process group
8547 * with pgid == pid_of_first_child_in_pipe */
8548 if (G.run_list_level == 1 && G_interactive_fd) {
8549 pid_t pgrp;
8550 pgrp = pi->pgrp;
8551 if (pgrp < 0) /* true for 1st process only */
8552 pgrp = getpid();
8553 if (setpgid(0, pgrp) == 0
8554 && pi->followup != PIPE_BG
8555 && G_saved_tty_pgrp /* we have ctty */
8556 ) {
8557 /* We do it in *every* child, not just first,
8558 * to avoid races */
8559 tcsetpgrp(G_interactive_fd, pgrp);
8560 }
8561 }
8562#endif
8563 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8564 /* 1st cmd in backgrounded pipe
8565 * should have its stdin /dev/null'ed */
8566 close(0);
8567 if (open(bb_dev_null, O_RDONLY))
8568 xopen("/", O_RDONLY);
8569 } else {
8570 xmove_fd(next_infd, 0);
8571 }
8572 xmove_fd(pipefds.wr, 1);
8573 if (pipefds.rd > 1)
8574 close(pipefds.rd);
8575 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008576 * and the pipe fd (fd#1) is available for dup'ing:
8577 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8578 * of cmd1 goes into pipe.
8579 */
8580 if (setup_redirects(command, NULL)) {
8581 /* Happens when redir file can't be opened:
8582 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8583 * FOO
8584 * hush: can't open '/qwe/rty': No such file or directory
8585 * BAZ
8586 * (echo BAR is not executed, it hits _exit(1) below)
8587 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008588 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008589 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008590
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008591 /* Stores to nommu_save list of env vars putenv'ed
8592 * (NOMMU, on MMU we don't need that) */
8593 /* cast away volatility... */
8594 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8595 /* pseudo_exec() does not return */
8596 }
8597
8598 /* parent or error */
8599#if ENABLE_HUSH_FAST
8600 G.count_SIGCHLD++;
8601//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8602#endif
8603 enable_restore_tty_pgrp_on_exit();
8604#if !BB_MMU
8605 /* Clean up after vforked child */
8606 free(nommu_save.argv);
8607 free(nommu_save.argv_from_re_execing);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008608 add_vars(nommu_save.old_vars);
8609#endif
8610 free(argv_expanded);
8611 argv_expanded = NULL;
8612 if (command->pid < 0) { /* [v]fork failed */
8613 /* Clearly indicate, was it fork or vfork */
8614 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8615 } else {
8616 pi->alive_cmds++;
8617#if ENABLE_HUSH_JOB
8618 /* Second and next children need to know pid of first one */
8619 if (pi->pgrp < 0)
8620 pi->pgrp = command->pid;
8621#endif
8622 }
8623
8624 if (cmd_no > 1)
8625 close(next_infd);
8626 if (cmd_no < pi->num_cmds)
8627 close(pipefds.wr);
8628 /* Pass read (output) pipe end to next iteration */
8629 next_infd = pipefds.rd;
8630 }
8631
8632 if (!pi->alive_cmds) {
8633 debug_leave();
8634 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8635 return 1;
8636 }
8637
8638 debug_leave();
8639 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8640 return -1;
8641}
8642
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008643/* NB: called by pseudo_exec, and therefore must not modify any
8644 * global data until exec/_exit (we can be a child after vfork!) */
8645static int run_list(struct pipe *pi)
8646{
8647#if ENABLE_HUSH_CASE
8648 char *case_word = NULL;
8649#endif
8650#if ENABLE_HUSH_LOOPS
8651 struct pipe *loop_top = NULL;
8652 char **for_lcur = NULL;
8653 char **for_list = NULL;
8654#endif
8655 smallint last_followup;
8656 smalluint rcode;
8657#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8658 smalluint cond_code = 0;
8659#else
8660 enum { cond_code = 0 };
8661#endif
8662#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008663 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008664 smallint last_rword; /* ditto */
8665#endif
8666
8667 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8668 debug_enter();
8669
8670#if ENABLE_HUSH_LOOPS
8671 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008672 {
8673 struct pipe *cpipe;
8674 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8675 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8676 continue;
8677 /* current word is FOR or IN (BOLD in comments below) */
8678 if (cpipe->next == NULL) {
8679 syntax_error("malformed for");
8680 debug_leave();
8681 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8682 return 1;
8683 }
8684 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8685 if (cpipe->next->res_word == RES_DO)
8686 continue;
8687 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8688 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8689 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8690 ) {
8691 syntax_error("malformed for");
8692 debug_leave();
8693 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8694 return 1;
8695 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008696 }
8697 }
8698#endif
8699
8700 /* Past this point, all code paths should jump to ret: label
8701 * in order to return, no direct "return" statements please.
8702 * This helps to ensure that no memory is leaked. */
8703
8704#if ENABLE_HUSH_JOB
8705 G.run_list_level++;
8706#endif
8707
8708#if HAS_KEYWORDS
8709 rword = RES_NONE;
8710 last_rword = RES_XXXX;
8711#endif
8712 last_followup = PIPE_SEQ;
8713 rcode = G.last_exitcode;
8714
8715 /* Go through list of pipes, (maybe) executing them. */
8716 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008717 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008718 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008719
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008720 if (G.flag_SIGINT)
8721 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008722 if (G_flag_return_in_progress == 1)
8723 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008724
8725 IF_HAS_KEYWORDS(rword = pi->res_word;)
8726 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8727 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008728
8729 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008730 if (
8731#if ENABLE_HUSH_IF
8732 rword == RES_IF || rword == RES_ELIF ||
8733#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008734 pi->followup != PIPE_SEQ
8735 ) {
8736 G.errexit_depth++;
8737 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008738#if ENABLE_HUSH_LOOPS
8739 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8740 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8741 ) {
8742 /* start of a loop: remember where loop starts */
8743 loop_top = pi;
8744 G.depth_of_loop++;
8745 }
8746#endif
8747 /* Still in the same "if...", "then..." or "do..." branch? */
8748 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8749 if ((rcode == 0 && last_followup == PIPE_OR)
8750 || (rcode != 0 && last_followup == PIPE_AND)
8751 ) {
8752 /* It is "<true> || CMD" or "<false> && CMD"
8753 * and we should not execute CMD */
8754 debug_printf_exec("skipped cmd because of || or &&\n");
8755 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008756 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008757 }
8758 }
8759 last_followup = pi->followup;
8760 IF_HAS_KEYWORDS(last_rword = rword;)
8761#if ENABLE_HUSH_IF
8762 if (cond_code) {
8763 if (rword == RES_THEN) {
8764 /* if false; then ... fi has exitcode 0! */
8765 G.last_exitcode = rcode = EXIT_SUCCESS;
8766 /* "if <false> THEN cmd": skip cmd */
8767 continue;
8768 }
8769 } else {
8770 if (rword == RES_ELSE || rword == RES_ELIF) {
8771 /* "if <true> then ... ELSE/ELIF cmd":
8772 * skip cmd and all following ones */
8773 break;
8774 }
8775 }
8776#endif
8777#if ENABLE_HUSH_LOOPS
8778 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8779 if (!for_lcur) {
8780 /* first loop through for */
8781
8782 static const char encoded_dollar_at[] ALIGN1 = {
8783 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8784 }; /* encoded representation of "$@" */
8785 static const char *const encoded_dollar_at_argv[] = {
8786 encoded_dollar_at, NULL
8787 }; /* argv list with one element: "$@" */
8788 char **vals;
8789
8790 vals = (char**)encoded_dollar_at_argv;
8791 if (pi->next->res_word == RES_IN) {
8792 /* if no variable values after "in" we skip "for" */
8793 if (!pi->next->cmds[0].argv) {
8794 G.last_exitcode = rcode = EXIT_SUCCESS;
8795 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8796 break;
8797 }
8798 vals = pi->next->cmds[0].argv;
8799 } /* else: "for var; do..." -> assume "$@" list */
8800 /* create list of variable values */
8801 debug_print_strings("for_list made from", vals);
8802 for_list = expand_strvec_to_strvec(vals);
8803 for_lcur = for_list;
8804 debug_print_strings("for_list", for_list);
8805 }
8806 if (!*for_lcur) {
8807 /* "for" loop is over, clean up */
8808 free(for_list);
8809 for_list = NULL;
8810 for_lcur = NULL;
8811 break;
8812 }
8813 /* Insert next value from for_lcur */
8814 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008815 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008816 continue;
8817 }
8818 if (rword == RES_IN) {
8819 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8820 }
8821 if (rword == RES_DONE) {
8822 continue; /* "done" has no cmds too */
8823 }
8824#endif
8825#if ENABLE_HUSH_CASE
8826 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008827 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02008828 case_word = expand_string_to_string(pi->cmds->argv[0], 1);
8829 debug_printf_exec("CASE word1:'%s'\n", case_word);
8830 //unbackslash(case_word);
8831 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008832 continue;
8833 }
8834 if (rword == RES_MATCH) {
8835 char **argv;
8836
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008837 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008838 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8839 break;
8840 /* all prev words didn't match, does this one match? */
8841 argv = pi->cmds->argv;
8842 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008843 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008844 /* TODO: which FNM_xxx flags to use? */
8845 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008846 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008847 free(pattern);
8848 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008849 free(case_word);
8850 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008851 break;
8852 }
8853 argv++;
8854 }
8855 continue;
8856 }
8857 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008858 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008859 if (cond_code != 0)
8860 continue; /* not matched yet, skip this pipe */
8861 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008862 if (rword == RES_ESAC) {
8863 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8864 if (case_word) {
8865 /* "case" did not match anything: still set $? (to 0) */
8866 G.last_exitcode = rcode = EXIT_SUCCESS;
8867 }
8868 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008869#endif
8870 /* Just pressing <enter> in shell should check for jobs.
8871 * OTOH, in non-interactive shell this is useless
8872 * and only leads to extra job checks */
8873 if (pi->num_cmds == 0) {
8874 if (G_interactive_fd)
8875 goto check_jobs_and_continue;
8876 continue;
8877 }
8878
8879 /* After analyzing all keywords and conditions, we decided
8880 * to execute this pipe. NB: have to do checkjobs(NULL)
8881 * after run_pipe to collect any background children,
8882 * even if list execution is to be stopped. */
8883 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008884#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008885 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008886#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008887 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8888 if (r != -1) {
8889 /* We ran a builtin, function, or group.
8890 * rcode is already known
8891 * and we don't need to wait for anything. */
8892 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8893 G.last_exitcode = rcode;
8894 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008895#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008896 /* Was it "break" or "continue"? */
8897 if (G.flag_break_continue) {
8898 smallint fbc = G.flag_break_continue;
8899 /* We might fall into outer *loop*,
8900 * don't want to break it too */
8901 if (loop_top) {
8902 G.depth_break_continue--;
8903 if (G.depth_break_continue == 0)
8904 G.flag_break_continue = 0;
8905 /* else: e.g. "continue 2" should *break* once, *then* continue */
8906 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8907 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008908 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008909 break;
8910 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008911 /* "continue": simulate end of loop */
8912 rword = RES_DONE;
8913 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008914 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008915#endif
8916 if (G_flag_return_in_progress == 1) {
8917 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8918 break;
8919 }
8920 } else if (pi->followup == PIPE_BG) {
8921 /* What does bash do with attempts to background builtins? */
8922 /* even bash 3.2 doesn't do that well with nested bg:
8923 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8924 * I'm NOT treating inner &'s as jobs */
8925#if ENABLE_HUSH_JOB
8926 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008927 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008928#endif
8929 /* Last command's pid goes to $! */
8930 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008931 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008932 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008933/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008934 rcode = EXIT_SUCCESS;
8935 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008936 } else {
8937#if ENABLE_HUSH_JOB
8938 if (G.run_list_level == 1 && G_interactive_fd) {
8939 /* Waits for completion, then fg's main shell */
8940 rcode = checkjobs_and_fg_shell(pi);
8941 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008942 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008943 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008944#endif
8945 /* This one just waits for completion */
8946 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8947 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8948 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008949 G.last_exitcode = rcode;
8950 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008951 }
8952
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008953 /* Handle "set -e" */
8954 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8955 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8956 if (G.errexit_depth == 0)
8957 hush_exit(rcode);
8958 }
8959 G.errexit_depth = sv_errexit_depth;
8960
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008961 /* Analyze how result affects subsequent commands */
8962#if ENABLE_HUSH_IF
8963 if (rword == RES_IF || rword == RES_ELIF)
8964 cond_code = rcode;
8965#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008966 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008967 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008968 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008969#if ENABLE_HUSH_LOOPS
8970 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008971 if (pi->next
8972 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008973 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008974 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008975 if (rword == RES_WHILE) {
8976 if (rcode) {
8977 /* "while false; do...done" - exitcode 0 */
8978 G.last_exitcode = rcode = EXIT_SUCCESS;
8979 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008980 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008981 }
8982 }
8983 if (rword == RES_UNTIL) {
8984 if (!rcode) {
8985 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008986 break;
8987 }
8988 }
8989 }
8990#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008991 } /* for (pi) */
8992
8993#if ENABLE_HUSH_JOB
8994 G.run_list_level--;
8995#endif
8996#if ENABLE_HUSH_LOOPS
8997 if (loop_top)
8998 G.depth_of_loop--;
8999 free(for_list);
9000#endif
9001#if ENABLE_HUSH_CASE
9002 free(case_word);
9003#endif
9004 debug_leave();
9005 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9006 return rcode;
9007}
9008
9009/* Select which version we will use */
9010static int run_and_free_list(struct pipe *pi)
9011{
9012 int rcode = 0;
9013 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009014 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009015 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9016 rcode = run_list(pi);
9017 }
9018 /* free_pipe_list has the side effect of clearing memory.
9019 * In the long run that function can be merged with run_list,
9020 * but doing that now would hobble the debugging effort. */
9021 free_pipe_list(pi);
9022 debug_printf_exec("run_and_free_list return %d\n", rcode);
9023 return rcode;
9024}
9025
9026
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009027static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009028{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009029 sighandler_t old_handler;
9030 unsigned sig = 0;
9031 while ((mask >>= 1) != 0) {
9032 sig++;
9033 if (!(mask & 1))
9034 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009035 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009036 /* POSIX allows shell to re-enable SIGCHLD
9037 * even if it was SIG_IGN on entry.
9038 * Therefore we skip IGN check for it:
9039 */
9040 if (sig == SIGCHLD)
9041 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009042 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9043 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9044 */
9045 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009046 if (old_handler == SIG_IGN) {
9047 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009048 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009049#if ENABLE_HUSH_TRAP
9050 if (!G_traps)
9051 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9052 free(G_traps[sig]);
9053 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9054#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009055 }
9056 }
9057}
9058
9059/* Called a few times only (or even once if "sh -c") */
9060static void install_special_sighandlers(void)
9061{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009062 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009063
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009064 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009065 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009066 if (G_interactive_fd) {
9067 mask |= SPECIAL_INTERACTIVE_SIGS;
9068 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009069 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009070 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009071 /* Careful, do not re-install handlers we already installed */
9072 if (G.special_sig_mask != mask) {
9073 unsigned diff = mask & ~G.special_sig_mask;
9074 G.special_sig_mask = mask;
9075 install_sighandlers(diff);
9076 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009077}
9078
9079#if ENABLE_HUSH_JOB
9080/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009081/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009082static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009083{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009084 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009085
9086 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009087 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009088 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9089 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009090 + (1 << SIGBUS ) * HUSH_DEBUG
9091 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009092 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009093 + (1 << SIGABRT)
9094 /* bash 3.2 seems to handle these just like 'fatal' ones */
9095 + (1 << SIGPIPE)
9096 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009097 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009098 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009099 * we never want to restore pgrp on exit, and this fn is not called
9100 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009101 /*+ (1 << SIGHUP )*/
9102 /*+ (1 << SIGTERM)*/
9103 /*+ (1 << SIGINT )*/
9104 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009105 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009106
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009107 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009108}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009109#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009110
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009111static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009112{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009113 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009114 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009115 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009116 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009117 break;
9118 case 'x':
9119 IF_HUSH_MODE_X(G_x_mode = state;)
9120 break;
9121 case 'o':
9122 if (!o_opt) {
9123 /* "set -+o" without parameter.
9124 * in bash, set -o produces this output:
9125 * pipefail off
9126 * and set +o:
9127 * set +o pipefail
9128 * We always use the second form.
9129 */
9130 const char *p = o_opt_strings;
9131 idx = 0;
9132 while (*p) {
9133 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9134 idx++;
9135 p += strlen(p) + 1;
9136 }
9137 break;
9138 }
9139 idx = index_in_strings(o_opt_strings, o_opt);
9140 if (idx >= 0) {
9141 G.o_opt[idx] = state;
9142 break;
9143 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009144 case 'e':
9145 G.o_opt[OPT_O_ERREXIT] = state;
9146 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009147 default:
9148 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009149 }
9150 return EXIT_SUCCESS;
9151}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009152
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009153int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009154int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009155{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009156 enum {
9157 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009158 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009159 };
9160 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009161 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009162 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009163 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009164 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009165
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009166 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009167 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009168 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009169
Denys Vlasenko10c01312011-05-11 11:49:21 +02009170#if ENABLE_HUSH_FAST
9171 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9172#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009173#if !BB_MMU
9174 G.argv0_for_re_execing = argv[0];
9175#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009176
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009177 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009178 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9179 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009180 shell_ver = xzalloc(sizeof(*shell_ver));
9181 shell_ver->flg_export = 1;
9182 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009183 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009184 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009185 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009186
Denys Vlasenko605067b2010-09-06 12:10:51 +02009187 /* Create shell local variables from the values
9188 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009189 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009190 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009191 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009192 if (e) while (*e) {
9193 char *value = strchr(*e, '=');
9194 if (value) { /* paranoia */
9195 cur_var->next = xzalloc(sizeof(*cur_var));
9196 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009197 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009198 cur_var->max_len = strlen(*e);
9199 cur_var->flg_export = 1;
9200 }
9201 e++;
9202 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009203 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009204 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9205 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009206
9207 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009208 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009209
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009210#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009211 /* Set (but not export) HOSTNAME unless already set */
9212 if (!get_local_var_value("HOSTNAME")) {
9213 struct utsname uts;
9214 uname(&uts);
9215 set_local_var_from_halves("HOSTNAME", uts.nodename);
9216 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009217 /* bash also exports SHLVL and _,
9218 * and sets (but doesn't export) the following variables:
9219 * BASH=/bin/bash
9220 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9221 * BASH_VERSION='3.2.0(1)-release'
9222 * HOSTTYPE=i386
9223 * MACHTYPE=i386-pc-linux-gnu
9224 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009225 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009226 * EUID=<NNNNN>
9227 * UID=<NNNNN>
9228 * GROUPS=()
9229 * LINES=<NNN>
9230 * COLUMNS=<NNN>
9231 * BASH_ARGC=()
9232 * BASH_ARGV=()
9233 * BASH_LINENO=()
9234 * BASH_SOURCE=()
9235 * DIRSTACK=()
9236 * PIPESTATUS=([0]="0")
9237 * HISTFILE=/<xxx>/.bash_history
9238 * HISTFILESIZE=500
9239 * HISTSIZE=500
9240 * MAILCHECK=60
9241 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9242 * SHELL=/bin/bash
9243 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9244 * TERM=dumb
9245 * OPTERR=1
9246 * OPTIND=1
9247 * IFS=$' \t\n'
9248 * PS1='\s-\v\$ '
9249 * PS2='> '
9250 * PS4='+ '
9251 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009252#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009253
Denys Vlasenko5807e182018-02-08 19:19:04 +01009254#if ENABLE_HUSH_LINENO_VAR
9255 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009256 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9257 set_local_var(p, /*flags*/ 0);
9258 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9259 }
9260#endif
9261
Denis Vlasenko38f63192007-01-22 09:03:07 +00009262#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009263 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009264#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009265
Eric Andersen94ac2442001-05-22 19:05:18 +00009266 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009267 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009268
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009269 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009270
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009271 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009272 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009273 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009274 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009275 * in order to intercept (more) signals.
9276 */
9277
9278 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009279 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009280 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009281 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009282 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009283 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009284#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009285 "<:$:R:V:"
9286# if ENABLE_HUSH_FUNCTIONS
9287 "F:"
9288# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009289#endif
9290 );
9291 if (opt <= 0)
9292 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009293 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009294 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009295 /* Possibilities:
9296 * sh ... -c 'script'
9297 * sh ... -c 'script' ARG0 [ARG1...]
9298 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009299 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009300 * "" needs to be replaced with NULL
9301 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009302 * Note: the form without ARG0 never happens:
9303 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009304 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009305 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009306 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009307 G.root_ppid = getppid();
9308 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009309 G.global_argv = argv + optind;
9310 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009311 if (builtin_argc) {
9312 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9313 const struct built_in_command *x;
9314
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009315 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009316 x = find_builtin(optarg);
9317 if (x) { /* paranoia */
9318 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9319 G.global_argv += builtin_argc;
9320 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009321 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009322 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009323 }
9324 goto final_return;
9325 }
9326 if (!G.global_argv[0]) {
9327 /* -c 'script' (no params): prevent empty $0 */
9328 G.global_argv--; /* points to argv[i] of 'script' */
9329 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009330 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009331 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009332 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009333 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009334 goto final_return;
9335 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009336 /* Well, we cannot just declare interactiveness,
9337 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009338 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009339 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009340 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009341 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009342 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009343 case 'l':
9344 flags |= OPT_login;
9345 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009346#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009347 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009348 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009349 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009350 case '$': {
9351 unsigned long long empty_trap_mask;
9352
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009353 G.root_pid = bb_strtou(optarg, &optarg, 16);
9354 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009355 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9356 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009357 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9358 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009359 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009360 optarg++;
9361 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009362 optarg++;
9363 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9364 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009365 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009366 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009367# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009368 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009369 for (sig = 1; sig < NSIG; sig++) {
9370 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009371 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009372 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009373 }
9374 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009375# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009376 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009377# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009378 optarg++;
9379 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009380# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009381 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009382 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009383 case 'R':
9384 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009385 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009386 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009387# if ENABLE_HUSH_FUNCTIONS
9388 case 'F': {
9389 struct function *funcp = new_function(optarg);
9390 /* funcp->name is already set to optarg */
9391 /* funcp->body is set to NULL. It's a special case. */
9392 funcp->body_as_string = argv[optind];
9393 optind++;
9394 break;
9395 }
9396# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009397#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009398 case 'n':
9399 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009400 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009401 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009402 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009403 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009404#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009405 fprintf(stderr, "Usage: sh [FILE]...\n"
9406 " or: sh -c command [args]...\n\n");
9407 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009408#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009409 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009410#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009411 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009412 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009413
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009414 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9415 G.global_argc = argc - (optind - 1);
9416 G.global_argv = argv + (optind - 1);
9417 G.global_argv[0] = argv[0];
9418
Denys Vlasenkodea47882009-10-09 15:40:49 +02009419 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009420 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009421 G.root_ppid = getppid();
9422 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009423
9424 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009425 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009426 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009427 debug_printf("sourcing /etc/profile\n");
9428 input = fopen_for_read("/etc/profile");
9429 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009430 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009431 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009432 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009433 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009434 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009435 /* bash: after sourcing /etc/profile,
9436 * tries to source (in the given order):
9437 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009438 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009439 * bash also sources ~/.bash_logout on exit.
9440 * If called as sh, skips .bash_XXX files.
9441 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009442 }
9443
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009444 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9445 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009446 FILE *input;
9447 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009448 * "bash <script>" (which is never interactive (unless -i?))
9449 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009450 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009451 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009452 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009453 G.global_argc--;
9454 G.global_argv++;
9455 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009456 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009457 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009458 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009459 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009460 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009461 parse_and_run_file(input);
9462#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009463 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009464#endif
9465 goto final_return;
9466 }
9467
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009468 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009469 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009470 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009471
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009472 /* A shell is interactive if the '-i' flag was given,
9473 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009474 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009475 * no arguments remaining or the -s flag given
9476 * standard input is a terminal
9477 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009478 * Refer to Posix.2, the description of the 'sh' utility.
9479 */
9480#if ENABLE_HUSH_JOB
9481 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009482 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9483 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9484 if (G_saved_tty_pgrp < 0)
9485 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009486
9487 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009488 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009489 if (G_interactive_fd < 0) {
9490 /* try to dup to any fd */
9491 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009492 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009493 /* give up */
9494 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009495 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009496 }
9497 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009498// TODO: track & disallow any attempts of user
9499// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009500 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009501 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009502 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009503 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009504
Mike Frysinger38478a62009-05-20 04:48:06 -04009505 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009506 /* If we were run as 'hush &', sleep until we are
9507 * in the foreground (tty pgrp == our pgrp).
9508 * If we get started under a job aware app (like bash),
9509 * make sure we are now in charge so we don't fight over
9510 * who gets the foreground */
9511 while (1) {
9512 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009513 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9514 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009515 break;
9516 /* send TTIN to ourself (should stop us) */
9517 kill(- shell_pgrp, SIGTTIN);
9518 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009519 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009520
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009521 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009522 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009523
Mike Frysinger38478a62009-05-20 04:48:06 -04009524 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009525 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009526 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009527 /* Put ourselves in our own process group
9528 * (bash, too, does this only if ctty is available) */
9529 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9530 /* Grab control of the terminal */
9531 tcsetpgrp(G_interactive_fd, getpid());
9532 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009533 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009534
9535# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9536 {
9537 const char *hp = get_local_var_value("HISTFILE");
9538 if (!hp) {
9539 hp = get_local_var_value("HOME");
9540 if (hp)
9541 hp = concat_path_file(hp, ".hush_history");
9542 } else {
9543 hp = xstrdup(hp);
9544 }
9545 if (hp) {
9546 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009547 //set_local_var(xasprintf("HISTFILE=%s", ...));
9548 }
9549# if ENABLE_FEATURE_SH_HISTFILESIZE
9550 hp = get_local_var_value("HISTFILESIZE");
9551 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9552# endif
9553 }
9554# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009555 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009556 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009557 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009558#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009559 /* No job control compiled in, only prompt/line editing */
9560 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009561 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009562 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009563 /* try to dup to any fd */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009564 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009565 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009566 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009567 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009568 }
9569 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009570 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009571 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009572 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009573 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009574#else
9575 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009576 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009577#endif
9578 /* bash:
9579 * if interactive but not a login shell, sources ~/.bashrc
9580 * (--norc turns this off, --rcfile <file> overrides)
9581 */
9582
9583 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009584 /* note: ash and hush share this string */
9585 printf("\n\n%s %s\n"
9586 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9587 "\n",
9588 bb_banner,
9589 "hush - the humble shell"
9590 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009591 }
9592
Denis Vlasenkof9375282009-04-05 19:13:39 +00009593 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009594
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009595 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009596 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009597}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009598
9599
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009600/*
9601 * Built-ins
9602 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009603static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009604{
9605 return 0;
9606}
9607
Denys Vlasenko265062d2017-01-10 15:13:30 +01009608#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009609static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009610{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009611 int argc = string_array_len(argv);
9612 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009613}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009614#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009615#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009616static int FAST_FUNC builtin_test(char **argv)
9617{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009618 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009619}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009620#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009621#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009622static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009623{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009624 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009625}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009626#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009627#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009628static int FAST_FUNC builtin_printf(char **argv)
9629{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009630 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009631}
9632#endif
9633
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009634#if ENABLE_HUSH_HELP
9635static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9636{
9637 const struct built_in_command *x;
9638
9639 printf(
9640 "Built-in commands:\n"
9641 "------------------\n");
9642 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9643 if (x->b_descr)
9644 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9645 }
9646 return EXIT_SUCCESS;
9647}
9648#endif
9649
9650#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9651static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9652{
9653 show_history(G.line_input_state);
9654 return EXIT_SUCCESS;
9655}
9656#endif
9657
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009658static char **skip_dash_dash(char **argv)
9659{
9660 argv++;
9661 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9662 argv++;
9663 return argv;
9664}
9665
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009666static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009667{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009668 const char *newdir;
9669
9670 argv = skip_dash_dash(argv);
9671 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009672 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009673 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009674 * bash says "bash: cd: HOME not set" and does nothing
9675 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009676 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009677 const char *home = get_local_var_value("HOME");
9678 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009679 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009680 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009681 /* Mimic bash message exactly */
9682 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009683 return EXIT_FAILURE;
9684 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009685 /* Read current dir (get_cwd(1) is inside) and set PWD.
9686 * Note: do not enforce exporting. If PWD was unset or unexported,
9687 * set it again, but do not export. bash does the same.
9688 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009689 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009690 return EXIT_SUCCESS;
9691}
9692
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009693static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9694{
9695 puts(get_cwd(0));
9696 return EXIT_SUCCESS;
9697}
9698
9699static int FAST_FUNC builtin_eval(char **argv)
9700{
9701 int rcode = EXIT_SUCCESS;
9702
9703 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009704 if (argv[0]) {
9705 char *str = NULL;
9706
9707 if (argv[1]) {
9708 /* "The eval utility shall construct a command by
9709 * concatenating arguments together, separating
9710 * each with a <space> character."
9711 */
9712 char *p;
9713 unsigned len = 0;
9714 char **pp = argv;
9715 do
9716 len += strlen(*pp) + 1;
9717 while (*++pp);
9718 str = p = xmalloc(len);
9719 pp = argv;
9720 do {
9721 p = stpcpy(p, *pp);
9722 *p++ = ' ';
9723 } while (*++pp);
9724 p[-1] = '\0';
9725 }
9726
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009727 /* bash:
9728 * eval "echo Hi; done" ("done" is syntax error):
9729 * "echo Hi" will not execute too.
9730 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009731 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009732 free(str);
9733 rcode = G.last_exitcode;
9734 }
9735 return rcode;
9736}
9737
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009738static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009739{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009740 argv = skip_dash_dash(argv);
9741 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009742 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009743
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009744 /* Careful: we can end up here after [v]fork. Do not restore
9745 * tty pgrp then, only top-level shell process does that */
9746 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9747 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9748
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009749 /* Saved-redirect fds, script fds and G_interactive_fd are still
9750 * open here. However, they are all CLOEXEC, and execv below
9751 * closes them. Try interactive "exec ls -l /proc/self/fd",
9752 * it should show no extra open fds in the "ls" process.
9753 * If we'd try to run builtins/NOEXECs, this would need improving.
9754 */
9755 //close_saved_fds_and_FILE_fds();
9756
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009757 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009758 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009759 * and tcsetpgrp, and this is inherently racy.
9760 */
9761 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009762}
9763
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009764static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009765{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009766 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009767
9768 /* interactive bash:
9769 * # trap "echo EEE" EXIT
9770 * # exit
9771 * exit
9772 * There are stopped jobs.
9773 * (if there are _stopped_ jobs, running ones don't count)
9774 * # exit
9775 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009776 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009777 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009778 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009779 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009780
9781 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009782 argv = skip_dash_dash(argv);
9783 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009784 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009785 /* mimic bash: exit 123abc == exit 255 + error msg */
9786 xfunc_error_retval = 255;
9787 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009788 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009789}
9790
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009791#if ENABLE_HUSH_TYPE
9792/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9793static int FAST_FUNC builtin_type(char **argv)
9794{
9795 int ret = EXIT_SUCCESS;
9796
9797 while (*++argv) {
9798 const char *type;
9799 char *path = NULL;
9800
9801 if (0) {} /* make conditional compile easier below */
9802 /*else if (find_alias(*argv))
9803 type = "an alias";*/
9804#if ENABLE_HUSH_FUNCTIONS
9805 else if (find_function(*argv))
9806 type = "a function";
9807#endif
9808 else if (find_builtin(*argv))
9809 type = "a shell builtin";
9810 else if ((path = find_in_path(*argv)) != NULL)
9811 type = path;
9812 else {
9813 bb_error_msg("type: %s: not found", *argv);
9814 ret = EXIT_FAILURE;
9815 continue;
9816 }
9817
9818 printf("%s is %s\n", *argv, type);
9819 free(path);
9820 }
9821
9822 return ret;
9823}
9824#endif
9825
9826#if ENABLE_HUSH_READ
9827/* Interruptibility of read builtin in bash
9828 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9829 *
9830 * Empty trap makes read ignore corresponding signal, for any signal.
9831 *
9832 * SIGINT:
9833 * - terminates non-interactive shell;
9834 * - interrupts read in interactive shell;
9835 * if it has non-empty trap:
9836 * - executes trap and returns to command prompt in interactive shell;
9837 * - executes trap and returns to read in non-interactive shell;
9838 * SIGTERM:
9839 * - is ignored (does not interrupt) read in interactive shell;
9840 * - terminates non-interactive shell;
9841 * if it has non-empty trap:
9842 * - executes trap and returns to read;
9843 * SIGHUP:
9844 * - terminates shell (regardless of interactivity);
9845 * if it has non-empty trap:
9846 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009847 * SIGCHLD from children:
9848 * - does not interrupt read regardless of interactivity:
9849 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009850 */
9851static int FAST_FUNC builtin_read(char **argv)
9852{
9853 const char *r;
9854 char *opt_n = NULL;
9855 char *opt_p = NULL;
9856 char *opt_t = NULL;
9857 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009858 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009859 const char *ifs;
9860 int read_flags;
9861
9862 /* "!": do not abort on errors.
9863 * Option string must start with "sr" to match BUILTIN_READ_xxx
9864 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009865 read_flags = getopt32(argv,
9866#if BASH_READ_D
9867 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9868#else
9869 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9870#endif
9871 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009872 if (read_flags == (uint32_t)-1)
9873 return EXIT_FAILURE;
9874 argv += optind;
9875 ifs = get_local_var_value("IFS"); /* can be NULL */
9876
9877 again:
9878 r = shell_builtin_read(set_local_var_from_halves,
9879 argv,
9880 ifs,
9881 read_flags,
9882 opt_n,
9883 opt_p,
9884 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009885 opt_u,
9886 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009887 );
9888
9889 if ((uintptr_t)r == 1 && errno == EINTR) {
9890 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009891 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009892 goto again;
9893 }
9894
9895 if ((uintptr_t)r > 1) {
9896 bb_error_msg("%s", r);
9897 r = (char*)(uintptr_t)1;
9898 }
9899
9900 return (uintptr_t)r;
9901}
9902#endif
9903
9904#if ENABLE_HUSH_UMASK
9905static int FAST_FUNC builtin_umask(char **argv)
9906{
9907 int rc;
9908 mode_t mask;
9909
9910 rc = 1;
9911 mask = umask(0);
9912 argv = skip_dash_dash(argv);
9913 if (argv[0]) {
9914 mode_t old_mask = mask;
9915
9916 /* numeric umasks are taken as-is */
9917 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9918 if (!isdigit(argv[0][0]))
9919 mask ^= 0777;
9920 mask = bb_parse_mode(argv[0], mask);
9921 if (!isdigit(argv[0][0]))
9922 mask ^= 0777;
9923 if ((unsigned)mask > 0777) {
9924 mask = old_mask;
9925 /* bash messages:
9926 * bash: umask: 'q': invalid symbolic mode operator
9927 * bash: umask: 999: octal number out of range
9928 */
9929 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9930 rc = 0;
9931 }
9932 } else {
9933 /* Mimic bash */
9934 printf("%04o\n", (unsigned) mask);
9935 /* fall through and restore mask which we set to 0 */
9936 }
9937 umask(mask);
9938
9939 return !rc; /* rc != 0 - success */
9940}
9941#endif
9942
Denys Vlasenko41ade052017-01-08 18:56:24 +01009943#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009944static void print_escaped(const char *s)
9945{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009946 if (*s == '\'')
9947 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009948 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009949 const char *p = strchrnul(s, '\'');
9950 /* print 'xxxx', possibly just '' */
9951 printf("'%.*s'", (int)(p - s), s);
9952 if (*p == '\0')
9953 break;
9954 s = p;
9955 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009956 /* s points to '; print "'''...'''" */
9957 putchar('"');
9958 do putchar('\''); while (*++s == '\'');
9959 putchar('"');
9960 } while (*s);
9961}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009962#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009963
Denys Vlasenko1e660422017-07-17 21:10:50 +02009964#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009965static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009966{
9967 do {
9968 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009969 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009970
9971 /* So far we do not check that name is valid (TODO?) */
9972
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009973 if (*name_end == '\0') {
9974 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009975
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009976 vpp = get_ptr_to_local_var(name, name_end - name);
9977 var = vpp ? *vpp : NULL;
9978
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009979 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009980 /* export -n NAME (without =VALUE) */
9981 if (var) {
9982 var->flg_export = 0;
9983 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9984 unsetenv(name);
9985 } /* else: export -n NOT_EXISTING_VAR: no-op */
9986 continue;
9987 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009988 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009989 /* export NAME (without =VALUE) */
9990 if (var) {
9991 var->flg_export = 1;
9992 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9993 putenv(var->varstr);
9994 continue;
9995 }
9996 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009997 if (flags & SETFLAG_MAKE_RO) {
9998 /* readonly NAME (without =VALUE) */
9999 if (var) {
10000 var->flg_read_only = 1;
10001 continue;
10002 }
10003 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010004# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010005 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010006 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010007 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10008 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010009 /* "local x=abc; ...; local x" - ignore second local decl */
10010 continue;
10011 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010012 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010013# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010014 /* Exporting non-existing variable.
10015 * bash does not put it in environment,
10016 * but remembers that it is exported,
10017 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010018 * We just set it to "" and export.
10019 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010020 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010021 * bash sets the value to "".
10022 */
10023 /* Or, it's "readonly NAME" (without =VALUE).
10024 * bash remembers NAME and disallows its creation
10025 * in the future.
10026 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010027 name = xasprintf("%s=", name);
10028 } else {
10029 /* (Un)exporting/making local NAME=VALUE */
10030 name = xstrdup(name);
10031 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010032 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010033 if (set_local_var(name, flags))
10034 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010035 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010036 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010037}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010038#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010039
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010040#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010041static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010042{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010043 unsigned opt_unexport;
10044
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010045#if ENABLE_HUSH_EXPORT_N
10046 /* "!": do not abort on errors */
10047 opt_unexport = getopt32(argv, "!n");
10048 if (opt_unexport == (uint32_t)-1)
10049 return EXIT_FAILURE;
10050 argv += optind;
10051#else
10052 opt_unexport = 0;
10053 argv++;
10054#endif
10055
10056 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010057 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010058 if (e) {
10059 while (*e) {
10060#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010061 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010062#else
10063 /* ash emits: export VAR='VAL'
10064 * bash: declare -x VAR="VAL"
10065 * we follow ash example */
10066 const char *s = *e++;
10067 const char *p = strchr(s, '=');
10068
10069 if (!p) /* wtf? take next variable */
10070 continue;
10071 /* export var= */
10072 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010073 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010074 putchar('\n');
10075#endif
10076 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010077 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010078 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010079 return EXIT_SUCCESS;
10080 }
10081
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010082 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010083}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010084#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010085
Denys Vlasenko295fef82009-06-03 12:47:26 +020010086#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010087static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010088{
10089 if (G.func_nest_level == 0) {
10090 bb_error_msg("%s: not in a function", argv[0]);
10091 return EXIT_FAILURE; /* bash compat */
10092 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010093 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010094 /* Since all builtins run in a nested variable level,
10095 * need to use level - 1 here. Or else the variable will be removed at once
10096 * after builtin returns.
10097 */
10098 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010099}
10100#endif
10101
Denys Vlasenko1e660422017-07-17 21:10:50 +020010102#if ENABLE_HUSH_READONLY
10103static int FAST_FUNC builtin_readonly(char **argv)
10104{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010105 argv++;
10106 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010107 /* bash: readonly [-p]: list all readonly VARs
10108 * (-p has no effect in bash)
10109 */
10110 struct variable *e;
10111 for (e = G.top_var; e; e = e->next) {
10112 if (e->flg_read_only) {
10113//TODO: quote value: readonly VAR='VAL'
10114 printf("readonly %s\n", e->varstr);
10115 }
10116 }
10117 return EXIT_SUCCESS;
10118 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010119 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010120}
10121#endif
10122
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010123#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010124/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10125static int FAST_FUNC builtin_unset(char **argv)
10126{
10127 int ret;
10128 unsigned opts;
10129
10130 /* "!": do not abort on errors */
10131 /* "+": stop at 1st non-option */
10132 opts = getopt32(argv, "!+vf");
10133 if (opts == (unsigned)-1)
10134 return EXIT_FAILURE;
10135 if (opts == 3) {
10136 bb_error_msg("unset: -v and -f are exclusive");
10137 return EXIT_FAILURE;
10138 }
10139 argv += optind;
10140
10141 ret = EXIT_SUCCESS;
10142 while (*argv) {
10143 if (!(opts & 2)) { /* not -f */
10144 if (unset_local_var(*argv)) {
10145 /* unset <nonexistent_var> doesn't fail.
10146 * Error is when one tries to unset RO var.
10147 * Message was printed by unset_local_var. */
10148 ret = EXIT_FAILURE;
10149 }
10150 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010151# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010152 else {
10153 unset_func(*argv);
10154 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010155# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010156 argv++;
10157 }
10158 return ret;
10159}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010160#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010161
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010162#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010163/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10164 * built-in 'set' handler
10165 * SUSv3 says:
10166 * set [-abCefhmnuvx] [-o option] [argument...]
10167 * set [+abCefhmnuvx] [+o option] [argument...]
10168 * set -- [argument...]
10169 * set -o
10170 * set +o
10171 * Implementations shall support the options in both their hyphen and
10172 * plus-sign forms. These options can also be specified as options to sh.
10173 * Examples:
10174 * Write out all variables and their values: set
10175 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10176 * Turn on the -x and -v options: set -xv
10177 * Unset all positional parameters: set --
10178 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10179 * Set the positional parameters to the expansion of x, even if x expands
10180 * with a leading '-' or '+': set -- $x
10181 *
10182 * So far, we only support "set -- [argument...]" and some of the short names.
10183 */
10184static int FAST_FUNC builtin_set(char **argv)
10185{
10186 int n;
10187 char **pp, **g_argv;
10188 char *arg = *++argv;
10189
10190 if (arg == NULL) {
10191 struct variable *e;
10192 for (e = G.top_var; e; e = e->next)
10193 puts(e->varstr);
10194 return EXIT_SUCCESS;
10195 }
10196
10197 do {
10198 if (strcmp(arg, "--") == 0) {
10199 ++argv;
10200 goto set_argv;
10201 }
10202 if (arg[0] != '+' && arg[0] != '-')
10203 break;
10204 for (n = 1; arg[n]; ++n) {
10205 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10206 goto error;
10207 if (arg[n] == 'o' && argv[1])
10208 argv++;
10209 }
10210 } while ((arg = *++argv) != NULL);
10211 /* Now argv[0] is 1st argument */
10212
10213 if (arg == NULL)
10214 return EXIT_SUCCESS;
10215 set_argv:
10216
10217 /* NB: G.global_argv[0] ($0) is never freed/changed */
10218 g_argv = G.global_argv;
10219 if (G.global_args_malloced) {
10220 pp = g_argv;
10221 while (*++pp)
10222 free(*pp);
10223 g_argv[1] = NULL;
10224 } else {
10225 G.global_args_malloced = 1;
10226 pp = xzalloc(sizeof(pp[0]) * 2);
10227 pp[0] = g_argv[0]; /* retain $0 */
10228 g_argv = pp;
10229 }
10230 /* This realloc's G.global_argv */
10231 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10232
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010233 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010234
10235 return EXIT_SUCCESS;
10236
10237 /* Nothing known, so abort */
10238 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010239 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010240 return EXIT_FAILURE;
10241}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010242#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010243
10244static int FAST_FUNC builtin_shift(char **argv)
10245{
10246 int n = 1;
10247 argv = skip_dash_dash(argv);
10248 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010249 n = bb_strtou(argv[0], NULL, 10);
10250 if (errno || n < 0) {
10251 /* shared string with ash.c */
10252 bb_error_msg("Illegal number: %s", argv[0]);
10253 /*
10254 * ash aborts in this case.
10255 * bash prints error message and set $? to 1.
10256 * Interestingly, for "shift 99999" bash does not
10257 * print error message, but does set $? to 1
10258 * (and does no shifting at all).
10259 */
10260 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010261 }
10262 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010263 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010264 int m = 1;
10265 while (m <= n)
10266 free(G.global_argv[m++]);
10267 }
10268 G.global_argc -= n;
10269 memmove(&G.global_argv[1], &G.global_argv[n+1],
10270 G.global_argc * sizeof(G.global_argv[0]));
10271 return EXIT_SUCCESS;
10272 }
10273 return EXIT_FAILURE;
10274}
10275
Denys Vlasenko74d40582017-08-11 01:32:46 +020010276#if ENABLE_HUSH_GETOPTS
10277static int FAST_FUNC builtin_getopts(char **argv)
10278{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010279/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10280
Denys Vlasenko74d40582017-08-11 01:32:46 +020010281TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010282If a required argument is not found, and getopts is not silent,
10283a question mark (?) is placed in VAR, OPTARG is unset, and a
10284diagnostic message is printed. If getopts is silent, then a
10285colon (:) is placed in VAR and OPTARG is set to the option
10286character found.
10287
10288Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010289
10290"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010291*/
10292 char cbuf[2];
10293 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010294 int c, n, exitcode, my_opterr;
10295 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010296
10297 optstring = *++argv;
10298 if (!optstring || !(var = *++argv)) {
10299 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10300 return EXIT_FAILURE;
10301 }
10302
Denys Vlasenko238ff982017-08-29 13:38:30 +020010303 if (argv[1])
10304 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10305 else
10306 argv = G.global_argv;
10307 cbuf[1] = '\0';
10308
10309 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010310 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010311 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010312 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010313 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010314 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010315
10316 /* getopts stops on first non-option. Add "+" to force that */
10317 /*if (optstring[0] != '+')*/ {
10318 char *s = alloca(strlen(optstring) + 2);
10319 sprintf(s, "+%s", optstring);
10320 optstring = s;
10321 }
10322
Denys Vlasenko238ff982017-08-29 13:38:30 +020010323 /* Naively, now we should just
10324 * cp = get_local_var_value("OPTIND");
10325 * optind = cp ? atoi(cp) : 0;
10326 * optarg = NULL;
10327 * opterr = my_opterr;
10328 * c = getopt(string_array_len(argv), argv, optstring);
10329 * and be done? Not so fast...
10330 * Unlike normal getopt() usage in C programs, here
10331 * each successive call will (usually) have the same argv[] CONTENTS,
10332 * but not the ADDRESSES. Worse yet, it's possible that between
10333 * invocations of "getopts", there will be calls to shell builtins
10334 * which use getopt() internally. Example:
10335 * while getopts "abc" RES -a -bc -abc de; do
10336 * unset -ff func
10337 * done
10338 * This would not work correctly: getopt() call inside "unset"
10339 * modifies internal libc state which is tracking position in
10340 * multi-option strings ("-abc"). At best, it can skip options
10341 * or return the same option infinitely. With glibc implementation
10342 * of getopt(), it would use outright invalid pointers and return
10343 * garbage even _without_ "unset" mangling internal state.
10344 *
10345 * We resort to resetting getopt() state and calling it N times,
10346 * until we get Nth result (or failure).
10347 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10348 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010349 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010350 count = 0;
10351 n = string_array_len(argv);
10352 do {
10353 optarg = NULL;
10354 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10355 c = getopt(n, argv, optstring);
10356 if (c < 0)
10357 break;
10358 count++;
10359 } while (count <= G.getopt_count);
10360
10361 /* Set OPTIND. Prevent resetting of the magic counter! */
10362 set_local_var_from_halves("OPTIND", utoa(optind));
10363 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010364 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010365
10366 /* Set OPTARG */
10367 /* Always set or unset, never left as-is, even on exit/error:
10368 * "If no option was found, or if the option that was found
10369 * does not have an option-argument, OPTARG shall be unset."
10370 */
10371 cp = optarg;
10372 if (c == '?') {
10373 /* If ":optstring" and unknown option is seen,
10374 * it is stored to OPTARG.
10375 */
10376 if (optstring[1] == ':') {
10377 cbuf[0] = optopt;
10378 cp = cbuf;
10379 }
10380 }
10381 if (cp)
10382 set_local_var_from_halves("OPTARG", cp);
10383 else
10384 unset_local_var("OPTARG");
10385
10386 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010387 exitcode = EXIT_SUCCESS;
10388 if (c < 0) { /* -1: end of options */
10389 exitcode = EXIT_FAILURE;
10390 c = '?';
10391 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010392
Denys Vlasenko238ff982017-08-29 13:38:30 +020010393 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010394 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010395 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010396
Denys Vlasenko74d40582017-08-11 01:32:46 +020010397 return exitcode;
10398}
10399#endif
10400
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010401static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010402{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010403 char *arg_path, *filename;
10404 FILE *input;
10405 save_arg_t sv;
10406 char *args_need_save;
10407#if ENABLE_HUSH_FUNCTIONS
10408 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010409#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010410
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010411 argv = skip_dash_dash(argv);
10412 filename = argv[0];
10413 if (!filename) {
10414 /* bash says: "bash: .: filename argument required" */
10415 return 2; /* bash compat */
10416 }
10417 arg_path = NULL;
10418 if (!strchr(filename, '/')) {
10419 arg_path = find_in_path(filename);
10420 if (arg_path)
10421 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010422 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010423 errno = ENOENT;
10424 bb_simple_perror_msg(filename);
10425 return EXIT_FAILURE;
10426 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010427 }
10428 input = remember_FILE(fopen_or_warn(filename, "r"));
10429 free(arg_path);
10430 if (!input) {
10431 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10432 /* POSIX: non-interactive shell should abort here,
10433 * not merely fail. So far no one complained :)
10434 */
10435 return EXIT_FAILURE;
10436 }
10437
10438#if ENABLE_HUSH_FUNCTIONS
10439 sv_flg = G_flag_return_in_progress;
10440 /* "we are inside sourced file, ok to use return" */
10441 G_flag_return_in_progress = -1;
10442#endif
10443 args_need_save = argv[1]; /* used as a boolean variable */
10444 if (args_need_save)
10445 save_and_replace_G_args(&sv, argv);
10446
10447 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10448 G.last_exitcode = 0;
10449 parse_and_run_file(input);
10450 fclose_and_forget(input);
10451
10452 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10453 restore_G_args(&sv, argv);
10454#if ENABLE_HUSH_FUNCTIONS
10455 G_flag_return_in_progress = sv_flg;
10456#endif
10457
10458 return G.last_exitcode;
10459}
10460
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010461#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010462static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010463{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010464 int sig;
10465 char *new_cmd;
10466
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010467 if (!G_traps)
10468 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010469
10470 argv++;
10471 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010472 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010473 /* No args: print all trapped */
10474 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010475 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010476 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010477 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010478 /* note: bash adds "SIG", but only if invoked
10479 * as "bash". If called as "sh", or if set -o posix,
10480 * then it prints short signal names.
10481 * We are printing short names: */
10482 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010483 }
10484 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010485 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010486 return EXIT_SUCCESS;
10487 }
10488
10489 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010490 /* If first arg is a number: reset all specified signals */
10491 sig = bb_strtou(*argv, NULL, 10);
10492 if (errno == 0) {
10493 int ret;
10494 process_sig_list:
10495 ret = EXIT_SUCCESS;
10496 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010497 sighandler_t handler;
10498
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010499 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010500 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010501 ret = EXIT_FAILURE;
10502 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010503 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010504 continue;
10505 }
10506
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010507 free(G_traps[sig]);
10508 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010509
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010510 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010511 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010512
10513 /* There is no signal for 0 (EXIT) */
10514 if (sig == 0)
10515 continue;
10516
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010517 if (new_cmd)
10518 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10519 else
10520 /* We are removing trap handler */
10521 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010522 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010523 }
10524 return ret;
10525 }
10526
10527 if (!argv[1]) { /* no second arg */
10528 bb_error_msg("trap: invalid arguments");
10529 return EXIT_FAILURE;
10530 }
10531
10532 /* First arg is "-": reset all specified to default */
10533 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10534 /* Everything else: set arg as signal handler
10535 * (includes "" case, which ignores signal) */
10536 if (argv[0][0] == '-') {
10537 if (argv[0][1] == '\0') { /* "-" */
10538 /* new_cmd remains NULL: "reset these sigs" */
10539 goto reset_traps;
10540 }
10541 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10542 argv++;
10543 }
10544 /* else: "-something", no special meaning */
10545 }
10546 new_cmd = *argv;
10547 reset_traps:
10548 argv++;
10549 goto process_sig_list;
10550}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010551#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010552
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010553#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010554static struct pipe *parse_jobspec(const char *str)
10555{
10556 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010557 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010558
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010559 if (sscanf(str, "%%%u", &jobnum) != 1) {
10560 if (str[0] != '%'
10561 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10562 ) {
10563 bb_error_msg("bad argument '%s'", str);
10564 return NULL;
10565 }
10566 /* It is "%%", "%+" or "%" - current job */
10567 jobnum = G.last_jobid;
10568 if (jobnum == 0) {
10569 bb_error_msg("no current job");
10570 return NULL;
10571 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010572 }
10573 for (pi = G.job_list; pi; pi = pi->next) {
10574 if (pi->jobid == jobnum) {
10575 return pi;
10576 }
10577 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010578 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010579 return NULL;
10580}
10581
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010582static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10583{
10584 struct pipe *job;
10585 const char *status_string;
10586
10587 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10588 for (job = G.job_list; job; job = job->next) {
10589 if (job->alive_cmds == job->stopped_cmds)
10590 status_string = "Stopped";
10591 else
10592 status_string = "Running";
10593
10594 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10595 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010596
10597 clean_up_last_dead_job();
10598
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010599 return EXIT_SUCCESS;
10600}
10601
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010602/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010603static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010604{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010605 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010606 struct pipe *pi;
10607
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010608 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010609 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010610
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010611 /* If they gave us no args, assume they want the last backgrounded task */
10612 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010613 for (pi = G.job_list; pi; pi = pi->next) {
10614 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010615 goto found;
10616 }
10617 }
10618 bb_error_msg("%s: no current job", argv[0]);
10619 return EXIT_FAILURE;
10620 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010621
10622 pi = parse_jobspec(argv[1]);
10623 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010624 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010625 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010626 /* TODO: bash prints a string representation
10627 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010628 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010629 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010630 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010631 }
10632
10633 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010634 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10635 for (i = 0; i < pi->num_cmds; i++) {
10636 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010637 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010638 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010639
10640 i = kill(- pi->pgrp, SIGCONT);
10641 if (i < 0) {
10642 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010643 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010644 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010645 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010646 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010647 }
10648
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010649 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010650 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010651 return checkjobs_and_fg_shell(pi);
10652 }
10653 return EXIT_SUCCESS;
10654}
10655#endif
10656
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010657#if ENABLE_HUSH_KILL
10658static int FAST_FUNC builtin_kill(char **argv)
10659{
10660 int ret = 0;
10661
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010662# if ENABLE_HUSH_JOB
10663 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10664 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010665
10666 do {
10667 struct pipe *pi;
10668 char *dst;
10669 int j, n;
10670
10671 if (argv[i][0] != '%')
10672 continue;
10673 /*
10674 * "kill %N" - job kill
10675 * Converting to pgrp / pid kill
10676 */
10677 pi = parse_jobspec(argv[i]);
10678 if (!pi) {
10679 /* Eat bad jobspec */
10680 j = i;
10681 do {
10682 j++;
10683 argv[j - 1] = argv[j];
10684 } while (argv[j]);
10685 ret = 1;
10686 i--;
10687 continue;
10688 }
10689 /*
10690 * In jobs started under job control, we signal
10691 * entire process group by kill -PGRP_ID.
10692 * This happens, f.e., in interactive shell.
10693 *
10694 * Otherwise, we signal each child via
10695 * kill PID1 PID2 PID3.
10696 * Testcases:
10697 * sh -c 'sleep 1|sleep 1 & kill %1'
10698 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10699 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10700 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010701 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010702 dst = alloca(n * sizeof(int)*4);
10703 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010704 if (G_interactive_fd)
10705 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010706 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010707 struct command *cmd = &pi->cmds[j];
10708 /* Skip exited members of the job */
10709 if (cmd->pid == 0)
10710 continue;
10711 /*
10712 * kill_main has matching code to expect
10713 * leading space. Needed to not confuse
10714 * negative pids with "kill -SIGNAL_NO" syntax
10715 */
10716 dst += sprintf(dst, " %u", (int)cmd->pid);
10717 }
10718 *dst = '\0';
10719 } while (argv[++i]);
10720 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010721# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010722
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010723 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010724 ret = run_applet_main(argv, kill_main);
10725 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010726 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010727 return ret;
10728}
10729#endif
10730
10731#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010732/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010733#if !ENABLE_HUSH_JOB
10734# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10735#endif
10736static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010737{
10738 int ret = 0;
10739 for (;;) {
10740 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010741 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010742
Denys Vlasenko830ea352016-11-08 04:59:11 +010010743 if (!sigisemptyset(&G.pending_set))
10744 goto check_sig;
10745
Denys Vlasenko7e675362016-10-28 21:57:31 +020010746 /* waitpid is not interruptible by SA_RESTARTed
10747 * signals which we use. Thus, this ugly dance:
10748 */
10749
10750 /* Make sure possible SIGCHLD is stored in kernel's
10751 * pending signal mask before we call waitpid.
10752 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010753 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010754 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010755 sigfillset(&oldset); /* block all signals, remember old set */
10756 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010757
10758 if (!sigisemptyset(&G.pending_set)) {
10759 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010760 goto restore;
10761 }
10762
10763 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010764/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010765 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010766 debug_printf_exec("checkjobs:%d\n", ret);
10767#if ENABLE_HUSH_JOB
10768 if (waitfor_pipe) {
10769 int rcode = job_exited_or_stopped(waitfor_pipe);
10770 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10771 if (rcode >= 0) {
10772 ret = rcode;
10773 sigprocmask(SIG_SETMASK, &oldset, NULL);
10774 break;
10775 }
10776 }
10777#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010778 /* if ECHILD, there are no children (ret is -1 or 0) */
10779 /* if ret == 0, no children changed state */
10780 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010781 if (errno == ECHILD || ret) {
10782 ret--;
10783 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010784 ret = 0;
10785 sigprocmask(SIG_SETMASK, &oldset, NULL);
10786 break;
10787 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010788 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010789 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10790 /* Note: sigsuspend invokes signal handler */
10791 sigsuspend(&oldset);
10792 restore:
10793 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010794 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010795 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010796 sig = check_and_run_traps();
10797 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010798 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010799 ret = 128 + sig;
10800 break;
10801 }
10802 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10803 }
10804 return ret;
10805}
10806
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010807static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010808{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010809 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010810 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010811
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010812 argv = skip_dash_dash(argv);
10813 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010814 /* Don't care about wait results */
10815 /* Note 1: must wait until there are no more children */
10816 /* Note 2: must be interruptible */
10817 /* Examples:
10818 * $ sleep 3 & sleep 6 & wait
10819 * [1] 30934 sleep 3
10820 * [2] 30935 sleep 6
10821 * [1] Done sleep 3
10822 * [2] Done sleep 6
10823 * $ sleep 3 & sleep 6 & wait
10824 * [1] 30936 sleep 3
10825 * [2] 30937 sleep 6
10826 * [1] Done sleep 3
10827 * ^C <-- after ~4 sec from keyboard
10828 * $
10829 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010830 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010831 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010832
Denys Vlasenko7e675362016-10-28 21:57:31 +020010833 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010834 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010835 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010836#if ENABLE_HUSH_JOB
10837 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010838 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010839 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010840 wait_pipe = parse_jobspec(*argv);
10841 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010842 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010843 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010844 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010845 } else {
10846 /* waiting on "last dead job" removes it */
10847 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010848 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010849 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010850 /* else: parse_jobspec() already emitted error msg */
10851 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010852 }
10853#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010854 /* mimic bash message */
10855 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010856 ret = EXIT_FAILURE;
10857 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010858 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010859
Denys Vlasenko7e675362016-10-28 21:57:31 +020010860 /* Do we have such child? */
10861 ret = waitpid(pid, &status, WNOHANG);
10862 if (ret < 0) {
10863 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010864 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010865 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010866 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010867 /* "wait $!" but last bg task has already exited. Try:
10868 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10869 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010870 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010871 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010872 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010873 } else {
10874 /* Example: "wait 1". mimic bash message */
10875 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010876 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010877 } else {
10878 /* ??? */
10879 bb_perror_msg("wait %s", *argv);
10880 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010881 continue; /* bash checks all argv[] */
10882 }
10883 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010884 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010885 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010886 } else {
10887 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010888 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010889 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010890 if (WIFSIGNALED(status))
10891 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010892 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010893 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010894
10895 return ret;
10896}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010897#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010898
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010899#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10900static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10901{
10902 if (argv[1]) {
10903 def = bb_strtou(argv[1], NULL, 10);
10904 if (errno || def < def_min || argv[2]) {
10905 bb_error_msg("%s: bad arguments", argv[0]);
10906 def = UINT_MAX;
10907 }
10908 }
10909 return def;
10910}
10911#endif
10912
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010913#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010914static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010915{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010916 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010917 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010918 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010919 /* if we came from builtin_continue(), need to undo "= 1" */
10920 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010921 return EXIT_SUCCESS; /* bash compat */
10922 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010923 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010924
10925 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10926 if (depth == UINT_MAX)
10927 G.flag_break_continue = BC_BREAK;
10928 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010929 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010930
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010931 return EXIT_SUCCESS;
10932}
10933
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010934static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010935{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010936 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10937 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010938}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010939#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010940
10941#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010942static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010943{
10944 int rc;
10945
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010946 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010947 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10948 return EXIT_FAILURE; /* bash compat */
10949 }
10950
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010951 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010952
10953 /* bash:
10954 * out of range: wraps around at 256, does not error out
10955 * non-numeric param:
10956 * f() { false; return qwe; }; f; echo $?
10957 * bash: return: qwe: numeric argument required <== we do this
10958 * 255 <== we also do this
10959 */
10960 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10961 return rc;
10962}
10963#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010964
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010965#if ENABLE_HUSH_TIMES
10966static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10967{
10968 static const uint8_t times_tbl[] ALIGN1 = {
10969 ' ', offsetof(struct tms, tms_utime),
10970 '\n', offsetof(struct tms, tms_stime),
10971 ' ', offsetof(struct tms, tms_cutime),
10972 '\n', offsetof(struct tms, tms_cstime),
10973 0
10974 };
10975 const uint8_t *p;
10976 unsigned clk_tck;
10977 struct tms buf;
10978
10979 clk_tck = bb_clk_tck();
10980
10981 times(&buf);
10982 p = times_tbl;
10983 do {
10984 unsigned sec, frac;
10985 unsigned long t;
10986 t = *(clock_t *)(((char *) &buf) + p[1]);
10987 sec = t / clk_tck;
10988 frac = t % clk_tck;
10989 printf("%um%u.%03us%c",
10990 sec / 60, sec % 60,
10991 (frac * 1000) / clk_tck,
10992 p[0]);
10993 p += 2;
10994 } while (*p);
10995
10996 return EXIT_SUCCESS;
10997}
10998#endif
10999
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011000#if ENABLE_HUSH_MEMLEAK
11001static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11002{
11003 void *p;
11004 unsigned long l;
11005
11006# ifdef M_TRIM_THRESHOLD
11007 /* Optional. Reduces probability of false positives */
11008 malloc_trim(0);
11009# endif
11010 /* Crude attempt to find where "free memory" starts,
11011 * sans fragmentation. */
11012 p = malloc(240);
11013 l = (unsigned long)p;
11014 free(p);
11015 p = malloc(3400);
11016 if (l < (unsigned long)p) l = (unsigned long)p;
11017 free(p);
11018
11019
11020# if 0 /* debug */
11021 {
11022 struct mallinfo mi = mallinfo();
11023 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11024 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11025 }
11026# endif
11027
11028 if (!G.memleak_value)
11029 G.memleak_value = l;
11030
11031 l -= G.memleak_value;
11032 if ((long)l < 0)
11033 l = 0;
11034 l /= 1024;
11035 if (l > 127)
11036 l = 127;
11037
11038 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11039 return l;
11040}
11041#endif