blob: 577faf466145c2e0046e855cc2bf542163fe5a70 [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
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100315/* -i (interactive) and -s (read stdin) are also accepted,
316 * but currently do nothing, therefore aren't shown in help.
317 * 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 Vlasenko9fda6092017-07-14 13:36:48 +0200321//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [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
2126/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002127 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002128 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002129#define SETFLAG_EXPORT (1 << 0)
2130#define SETFLAG_UNEXPORT (1 << 1)
2131#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002132#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002133static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002134{
Denys Vlasenko61407802018-04-04 21:14:28 +02002135 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002137 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002138 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002139 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002140 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141
Denis Vlasenko950bd722009-04-21 11:23:56 +00002142 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002143 if (HUSH_DEBUG && !eq_sign)
2144 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145
Denis Vlasenko950bd722009-04-21 11:23:56 +00002146 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002147 cur_pp = &G.top_var;
2148 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002150 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002151 continue;
2152 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002153
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002155 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002156 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002157 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002158//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2159//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002160 return -1;
2161 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002162 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002163 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2164 *eq_sign = '\0';
2165 unsetenv(str);
2166 *eq_sign = '=';
2167 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002168 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002169 /* bash 3.2.33(1) and exported vars:
2170 * # export z=z
2171 * # f() { local z=a; env | grep ^z; }
2172 * # f
2173 * z=a
2174 * # env | grep ^z
2175 * z=z
2176 */
2177 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002178 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002179 /* New variable is local ("local VAR=VAL" or
2180 * "VAR=VAL cmd")
2181 * and existing one is global, or local
2182 * on a lower level that new one.
2183 * Remove it from global variable list:
2184 */
2185 *cur_pp = cur->next;
2186 if (G.shadowed_vars_pp) {
2187 /* Save in "shadowed" list */
2188 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2189 cur->flg_export ? "exported " : "",
2190 cur->varstr, cur->var_nest_level, str, local_lvl
2191 );
2192 cur->next = *G.shadowed_vars_pp;
2193 *G.shadowed_vars_pp = cur;
2194 } else {
2195 /* Came from pseudo_exec_argv(), no need to save: delete it */
2196 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2197 cur->flg_export ? "exported " : "",
2198 cur->varstr, cur->var_nest_level, str, local_lvl
2199 );
2200 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2201 free_me = cur->varstr; /* then free it later */
2202 free(cur);
2203 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002204 break;
2205 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002206
Denis Vlasenko950bd722009-04-21 11:23:56 +00002207 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002208 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002209 free_and_exp:
2210 free(str);
2211 goto exp;
2212 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002213
2214 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002215 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002216 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002217 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002218 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002219 strcpy(cur->varstr, str);
2220 goto free_and_exp;
2221 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002222 /* Can't reuse */
2223 cur->max_len = 0;
2224 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002225 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002226 /* max_len == 0 signifies "malloced" var, which we can
2227 * (and have to) free. But we can't free(cur->varstr) here:
2228 * if cur->flg_export is 1, it is in the environment.
2229 * We should either unsetenv+free, or wait until putenv,
2230 * then putenv(new)+free(old).
2231 */
2232 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002233 goto set_str_and_exp;
2234 }
2235
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002236 /* Not found or shadowed - create new variable struct */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002237 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002238 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002239 cur->next = *cur_pp;
2240 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002241
2242 set_str_and_exp:
2243 cur->varstr = str;
2244 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002245#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002246 if (flags & SETFLAG_MAKE_RO) {
2247 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002248 }
2249#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002250 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002251 cur->flg_export = 1;
2252 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002253 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002254 cur->flg_export = 0;
2255 /* unsetenv was already done */
2256 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002257 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002258 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002259 i = putenv(cur->varstr);
2260 /* only now we can free old exported malloced string */
2261 free(free_me);
2262 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002263 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002264 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002265 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002266
2267 /* Handle special names */
2268 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2269 cmdedit_update_prompt();
2270 else
2271 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS) && name_len == 7) {
2272#if ENABLE_HUSH_LINENO_VAR
2273 if (G.lineno_var && strncmp(cur->varstr, "LINENO", 6) == 0)
2274 G.lineno_var = NULL;
2275#endif
2276#if ENABLE_HUSH_GETOPTS
2277 /* defoptindvar is a "OPTIND=..." constant string */
2278 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
2279 G.getopt_count = 0;
2280#endif
2281 }
2282
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002283 return 0;
2284}
2285
Denys Vlasenko6db47842009-09-05 20:15:17 +02002286/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002287static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002288{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002289 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002290}
2291
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002292static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002293{
2294 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002295 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002296
2297 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002298 return EXIT_SUCCESS;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002299
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002300 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS) && name_len == 6) {
Denys Vlasenko238ff982017-08-29 13:38:30 +02002301#if ENABLE_HUSH_GETOPTS
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002302 if (strncmp(name, "OPTIND", 6) == 0)
2303 G.getopt_count = 0;
Denys Vlasenko238ff982017-08-29 13:38:30 +02002304#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +01002305#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002306 if (G.lineno_var && strncmp(name, "LINENO", 6) == 0)
2307 G.lineno_var = NULL;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002308#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002309 }
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) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002313 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2314 if (cur->flg_read_only) {
2315 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002316 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002317 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002318 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002319 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2320 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002321 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2322 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002323 if (!cur->max_len)
2324 free(cur->varstr);
2325 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002326 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002328 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002329 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002330 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002331}
2332
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002333#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002334static int unset_local_var(const char *name)
2335{
2336 return unset_local_var_len(name, strlen(name));
2337}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002338#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002339
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002340#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002341static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002342{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002343 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002344 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002345}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002346#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002347
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002348
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002349/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002350 * Helpers for "var1=val1 var2=val2 cmd" feature
2351 */
2352static void add_vars(struct variable *var)
2353{
2354 struct variable *next;
2355
2356 while (var) {
2357 next = var->next;
2358 var->next = G.top_var;
2359 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002360 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002361 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002362 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002363 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002364 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002365 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002366 var = next;
2367 }
2368}
2369
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002370/* We put strings[i] into variable table and possibly putenv them.
2371 * If variable is read only, we can free the strings[i]
2372 * which attempts to overwrite it.
2373 * The strings[] vector itself is freed.
2374 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002375static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002376{
2377 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002378
2379 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002380 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002381
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002382 s = strings;
2383 while (*s) {
2384 struct variable *var_p;
2385 struct variable **var_pp;
2386 char *eq;
2387
2388 eq = strchr(*s, '=');
2389 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002390 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002391 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002392 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002393 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002394 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002395 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002396 /*
2397 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2398 * If VAR is readonly, leaving it in the list
2399 * after asssignment error (msg above)
2400 * causes doubled error message later, on unset.
2401 */
2402 debug_printf_env("removing/freeing '%s' element\n", *s);
2403 free(*s);
2404 p = s;
2405 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002406 goto next;
2407 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002408 /* below, set_local_var() with nest level will
2409 * "shadow" (remove) this variable from
2410 * global linked list.
2411 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002412 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002413 //bb_error_msg("G.var_nest_level:%d", G.var_nest_level);
2414 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2415 } else if (HUSH_DEBUG) {
2416 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002417 }
2418 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002419 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002420 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002421 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002422}
2423
2424
2425/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002426 * Unicode helper
2427 */
2428static void reinit_unicode_for_hush(void)
2429{
2430 /* Unicode support should be activated even if LANG is set
2431 * _during_ shell execution, not only if it was set when
2432 * shell was started. Therefore, re-check LANG every time:
2433 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002434 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2435 || ENABLE_UNICODE_USING_LOCALE
2436 ) {
2437 const char *s = get_local_var_value("LC_ALL");
2438 if (!s) s = get_local_var_value("LC_CTYPE");
2439 if (!s) s = get_local_var_value("LANG");
2440 reinit_unicode(s);
2441 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002442}
2443
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002444/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002445 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002446 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002447
2448#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002449/* To test correct lineedit/interactive behavior, type from command line:
2450 * echo $P\
2451 * \
2452 * AT\
2453 * H\
2454 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002455 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002456 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002457static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002458{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002459 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002460 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002461 if (G.PS1 == NULL)
2462 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002463 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002464 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002465 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002466 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002467 if (G.PS2 == NULL)
2468 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002469}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002470static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002471{
2472 const char *prompt_str;
2473 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002474 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2475 /* Set up the prompt */
2476 if (promptmode == 0) { /* PS1 */
2477 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002478 /* bash uses $PWD value, even if it is set by user.
2479 * It uses current dir only if PWD is unset.
2480 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002481 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002482 prompt_str = G.PS1;
2483 } else
2484 prompt_str = G.PS2;
2485 } else
2486 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002487 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488 return prompt_str;
2489}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002490static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002491{
2492 int r;
2493 const char *prompt_str;
2494
2495 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002496# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002497 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002498 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002499 if (G.flag_SIGINT) {
2500 /* There was ^C'ed, make it look prettier: */
2501 bb_putchar('\n');
2502 G.flag_SIGINT = 0;
2503 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002504 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002505 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002506 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002507 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002508 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002509 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002510 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002511 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002512 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002513 if (r != 0 && !G.flag_SIGINT)
2514 break;
2515 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002516 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2517 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002518 G.last_exitcode = 128 + SIGINT;
2519 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002520 if (r < 0) {
2521 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002522 i->p = NULL;
2523 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002524 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002525 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002526 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002527 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002528# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002529 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002530 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002531 if (i->last_char == '\0' || i->last_char == '\n') {
2532 /* Why check_and_run_traps here? Try this interactively:
2533 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2534 * $ <[enter], repeatedly...>
2535 * Without check_and_run_traps, handler never runs.
2536 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002537 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002538 fputs(prompt_str, stdout);
2539 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002540 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002541//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002542 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002543 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2544 * no ^C masking happens during fgetc, no special code for ^C:
2545 * it generates SIGINT as usual.
2546 */
2547 check_and_run_traps();
2548 if (G.flag_SIGINT)
2549 G.last_exitcode = 128 + SIGINT;
2550 if (r != '\0')
2551 break;
2552 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002553 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002554# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002555}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556/* This is the magic location that prints prompts
2557 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002558static int fgetc_interactive(struct in_str *i)
2559{
2560 int ch;
2561 /* If it's interactive stdin, get new line. */
2562 if (G_interactive_fd && i->file == stdin) {
2563 /* Returns first char (or EOF), the rest is in i->p[] */
2564 ch = get_user_input(i);
2565 i->promptmode = 1; /* PS2 */
2566 } else {
2567 /* Not stdin: script file, sourced file, etc */
2568 do ch = fgetc(i->file); while (ch == '\0');
2569 }
2570 return ch;
2571}
2572#else
2573static inline int fgetc_interactive(struct in_str *i)
2574{
2575 int ch;
2576 do ch = fgetc(i->file); while (ch == '\0');
2577 return ch;
2578}
2579#endif /* INTERACTIVE */
2580
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002581static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002582{
2583 int ch;
2584
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002585 if (!i->file) {
2586 /* string-based in_str */
2587 ch = (unsigned char)*i->p;
2588 if (ch != '\0') {
2589 i->p++;
2590 i->last_char = ch;
2591 return ch;
2592 }
2593 return EOF;
2594 }
2595
2596 /* FILE-based in_str */
2597
Denys Vlasenko4074d492016-09-30 01:49:53 +02002598#if ENABLE_FEATURE_EDITING
2599 /* This can be stdin, check line editing char[] buffer */
2600 if (i->p && *i->p != '\0') {
2601 ch = (unsigned char)*i->p++;
2602 goto out;
2603 }
2604#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002605 /* peek_buf[] is an int array, not char. Can contain EOF. */
2606 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002607 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002608 int ch2 = i->peek_buf[1];
2609 i->peek_buf[0] = ch2;
2610 if (ch2 == 0) /* very likely, avoid redundant write */
2611 goto out;
2612 i->peek_buf[1] = 0;
2613 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002614 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002615
Denys Vlasenko4074d492016-09-30 01:49:53 +02002616 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002617 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002618 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002619 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002620#if ENABLE_HUSH_LINENO_VAR
2621 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002622 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002623 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2624 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002625#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002626 return ch;
2627}
2628
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002629static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002630{
2631 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002632
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002633 if (!i->file) {
2634 /* string-based in_str */
2635 /* Doesn't report EOF on NUL. None of the callers care. */
2636 return (unsigned char)*i->p;
2637 }
2638
2639 /* FILE-based in_str */
2640
Denys Vlasenko4074d492016-09-30 01:49:53 +02002641#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002642 /* This can be stdin, check line editing char[] buffer */
2643 if (i->p && *i->p != '\0')
2644 return (unsigned char)*i->p;
2645#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002646 /* peek_buf[] is an int array, not char. Can contain EOF. */
2647 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002648 if (ch != 0)
2649 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002650
Denys Vlasenko4074d492016-09-30 01:49:53 +02002651 /* Need to get a new char */
2652 ch = fgetc_interactive(i);
2653 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2654
2655 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2656#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2657 if (i->p) {
2658 i->p -= 1;
2659 return ch;
2660 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002661#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002662 i->peek_buf[0] = ch;
2663 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002664 return ch;
2665}
2666
Denys Vlasenko4074d492016-09-30 01:49:53 +02002667/* Only ever called if i_peek() was called, and did not return EOF.
2668 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2669 * not end-of-line. Therefore we never need to read a new editing line here.
2670 */
2671static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002672{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002673 int ch;
2674
2675 /* There are two cases when i->p[] buffer exists.
2676 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002677 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002678 * In both cases, we know that i->p[0] exists and not NUL, and
2679 * the peek2 result is in i->p[1].
2680 */
2681 if (i->p)
2682 return (unsigned char)i->p[1];
2683
2684 /* Now we know it is a file-based in_str. */
2685
2686 /* peek_buf[] is an int array, not char. Can contain EOF. */
2687 /* Is there 2nd char? */
2688 ch = i->peek_buf[1];
2689 if (ch == 0) {
2690 /* We did not read it yet, get it now */
2691 do ch = fgetc(i->file); while (ch == '\0');
2692 i->peek_buf[1] = ch;
2693 }
2694
2695 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2696 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002697}
2698
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002699static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2700{
2701 for (;;) {
2702 int ch, ch2;
2703
2704 ch = i_getch(input);
2705 if (ch != '\\')
2706 return ch;
2707 ch2 = i_peek(input);
2708 if (ch2 != '\n')
2709 return ch;
2710 /* backslash+newline, skip it */
2711 i_getch(input);
2712 }
2713}
2714
2715/* Note: this function _eats_ \<newline> pairs, safe to use plain
2716 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2717 */
2718static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2719{
2720 for (;;) {
2721 int ch, ch2;
2722
2723 ch = i_peek(input);
2724 if (ch != '\\')
2725 return ch;
2726 ch2 = i_peek2(input);
2727 if (ch2 != '\n')
2728 return ch;
2729 /* backslash+newline, skip it */
2730 i_getch(input);
2731 i_getch(input);
2732 }
2733}
2734
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002735static void setup_file_in_str(struct in_str *i, FILE *f)
2736{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002737 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002738 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002739 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002740 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002741}
2742
2743static void setup_string_in_str(struct in_str *i, const char *s)
2744{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002745 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002746 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002747 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002748 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002749}
2750
2751
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002752/*
2753 * o_string support
2754 */
2755#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002756
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002757static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002758{
2759 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002760 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002761 if (o->data)
2762 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002763}
2764
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002765static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002766{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002767 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002768 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002769}
2770
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002771static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2772{
2773 free(o->data);
2774}
2775
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002776static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002777{
2778 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002779 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002780 o->data = xrealloc(o->data, 1 + o->maxlen);
2781 }
2782}
2783
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002784static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002785{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002786 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002787 if (o->length < o->maxlen) {
2788 /* likely. avoid o_grow_by() call */
2789 add:
2790 o->data[o->length] = ch;
2791 o->length++;
2792 o->data[o->length] = '\0';
2793 return;
2794 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002795 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002796 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002797}
2798
Denys Vlasenko657086a2016-09-29 18:07:42 +02002799#if 0
2800/* Valid only if we know o_string is not empty */
2801static void o_delchr(o_string *o)
2802{
2803 o->length--;
2804 o->data[o->length] = '\0';
2805}
2806#endif
2807
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002808static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002809{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002810 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002811 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002812 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002813}
2814
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002815static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002816{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002817 o_addblock(o, str, strlen(str));
2818}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002819
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002820#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002821static void nommu_addchr(o_string *o, int ch)
2822{
2823 if (o)
2824 o_addchr(o, ch);
2825}
2826#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002827# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002828#endif
2829
2830static void o_addstr_with_NUL(o_string *o, const char *str)
2831{
2832 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002833}
2834
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002835/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002836 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002837 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2838 * Apparently, on unquoted $v bash still does globbing
2839 * ("v='*.txt'; echo $v" prints all .txt files),
2840 * but NOT brace expansion! Thus, there should be TWO independent
2841 * quoting mechanisms on $v expansion side: one protects
2842 * $v from brace expansion, and other additionally protects "$v" against globbing.
2843 * We have only second one.
2844 */
2845
Denys Vlasenko9e800222010-10-03 14:28:04 +02002846#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002847# define MAYBE_BRACES "{}"
2848#else
2849# define MAYBE_BRACES ""
2850#endif
2851
Eric Andersen25f27032001-04-26 23:22:31 +00002852/* My analysis of quoting semantics tells me that state information
2853 * is associated with a destination, not a source.
2854 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002855static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002856{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002857 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002858 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002859 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002860 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002861 o_grow_by(o, sz);
2862 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002863 o->data[o->length] = '\\';
2864 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002865 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002866 o->data[o->length] = ch;
2867 o->length++;
2868 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002869}
2870
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002871static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002872{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002873 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002874 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2875 && strchr("*?[\\" MAYBE_BRACES, ch)
2876 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002877 sz++;
2878 o->data[o->length] = '\\';
2879 o->length++;
2880 }
2881 o_grow_by(o, sz);
2882 o->data[o->length] = ch;
2883 o->length++;
2884 o->data[o->length] = '\0';
2885}
2886
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002887static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002888{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002889 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002890 char ch;
2891 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002892 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002893 if (ordinary_cnt > len) /* paranoia */
2894 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002895 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002896 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002897 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002898 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002899 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002900
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002901 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002902 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002903 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002904 sz++;
2905 o->data[o->length] = '\\';
2906 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002907 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002908 o_grow_by(o, sz);
2909 o->data[o->length] = ch;
2910 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002911 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002912 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002913}
2914
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002915static void o_addQblock(o_string *o, const char *str, int len)
2916{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002917 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002918 o_addblock(o, str, len);
2919 return;
2920 }
2921 o_addqblock(o, str, len);
2922}
2923
Denys Vlasenko38292b62010-09-05 14:49:40 +02002924static void o_addQstr(o_string *o, const char *str)
2925{
2926 o_addQblock(o, str, strlen(str));
2927}
2928
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002929/* A special kind of o_string for $VAR and `cmd` expansion.
2930 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002931 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002932 * list[i] contains an INDEX (int!) into this string data.
2933 * It means that if list[] needs to grow, data needs to be moved higher up
2934 * but list[i]'s need not be modified.
2935 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002936 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002937 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2938 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002939#if DEBUG_EXPAND || DEBUG_GLOB
2940static void debug_print_list(const char *prefix, o_string *o, int n)
2941{
2942 char **list = (char**)o->data;
2943 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2944 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002945
2946 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002947 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 +02002948 prefix, list, n, string_start, o->length, o->maxlen,
2949 !!(o->o_expflags & EXP_FLAG_GLOB),
2950 o->has_quoted_part,
2951 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002952 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002953 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002954 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2955 o->data + (int)(uintptr_t)list[i] + string_start,
2956 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002957 i++;
2958 }
2959 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002960 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002961 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002962 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002963 }
2964}
2965#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002966# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002967#endif
2968
2969/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2970 * in list[n] so that it points past last stored byte so far.
2971 * It returns n+1. */
2972static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002973{
2974 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002975 int string_start;
2976 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002977
2978 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002979 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2980 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002981 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002982 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002983 /* list[n] points to string_start, make space for 16 more pointers */
2984 o->maxlen += 0x10 * sizeof(list[0]);
2985 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002986 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002987 memmove(list + n + 0x10, list + n, string_len);
2988 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002989 } else {
2990 debug_printf_list("list[%d]=%d string_start=%d\n",
2991 n, string_len, string_start);
2992 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002993 } else {
2994 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002995 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2996 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002997 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2998 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002999 o->has_empty_slot = 0;
3000 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003001 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003002 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003003 return n + 1;
3004}
3005
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003006/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003007static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003008{
3009 char **list = (char**)o->data;
3010 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3011
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003012 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003013}
3014
Denys Vlasenko9e800222010-10-03 14:28:04 +02003015#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003016/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3017 * first, it processes even {a} (no commas), second,
3018 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003019 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003020 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003021
3022/* Helper */
3023static int glob_needed(const char *s)
3024{
3025 while (*s) {
3026 if (*s == '\\') {
3027 if (!s[1])
3028 return 0;
3029 s += 2;
3030 continue;
3031 }
3032 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3033 return 1;
3034 s++;
3035 }
3036 return 0;
3037}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003038/* Return pointer to next closing brace or to comma */
3039static const char *next_brace_sub(const char *cp)
3040{
3041 unsigned depth = 0;
3042 cp++;
3043 while (*cp != '\0') {
3044 if (*cp == '\\') {
3045 if (*++cp == '\0')
3046 break;
3047 cp++;
3048 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003049 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003050 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003051 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003052 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003053 depth++;
3054 }
3055
3056 return *cp != '\0' ? cp : NULL;
3057}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003058/* Recursive brace globber. Note: may garble pattern[]. */
3059static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003060{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003061 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003062 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003063 const char *next;
3064 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003065 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003066 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003067
3068 debug_printf_glob("glob_brace('%s')\n", pattern);
3069
3070 begin = pattern;
3071 while (1) {
3072 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003073 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003074 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003075 /* Find the first sub-pattern and at the same time
3076 * find the rest after the closing brace */
3077 next = next_brace_sub(begin);
3078 if (next == NULL) {
3079 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003080 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003081 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003082 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003083 /* "{abc}" with no commas - illegal
3084 * brace expr, disregard and skip it */
3085 begin = next + 1;
3086 continue;
3087 }
3088 break;
3089 }
3090 if (*begin == '\\' && begin[1] != '\0')
3091 begin++;
3092 begin++;
3093 }
3094 debug_printf_glob("begin:%s\n", begin);
3095 debug_printf_glob("next:%s\n", next);
3096
3097 /* Now find the end of the whole brace expression */
3098 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003099 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003100 rest = next_brace_sub(rest);
3101 if (rest == NULL) {
3102 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003103 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003104 }
3105 debug_printf_glob("rest:%s\n", rest);
3106 }
3107 rest_len = strlen(++rest) + 1;
3108
3109 /* We are sure the brace expression is well-formed */
3110
3111 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003112 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003113
3114 /* We have a brace expression. BEGIN points to the opening {,
3115 * NEXT points past the terminator of the first element, and REST
3116 * points past the final }. We will accumulate result names from
3117 * recursive runs for each brace alternative in the buffer using
3118 * GLOB_APPEND. */
3119
3120 p = begin + 1;
3121 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003122 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003123 memcpy(
3124 mempcpy(
3125 mempcpy(new_pattern_buf,
3126 /* We know the prefix for all sub-patterns */
3127 pattern, begin - pattern),
3128 p, next - p),
3129 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003130
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003131 /* Note: glob_brace() may garble new_pattern_buf[].
3132 * That's why we re-copy prefix every time (1st memcpy above).
3133 */
3134 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003135 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003136 /* We saw the last entry */
3137 break;
3138 }
3139 p = next + 1;
3140 next = next_brace_sub(next);
3141 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003142 free(new_pattern_buf);
3143 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003144
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003145 simple_glob:
3146 {
3147 int gr;
3148 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003149
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003150 memset(&globdata, 0, sizeof(globdata));
3151 gr = glob(pattern, 0, NULL, &globdata);
3152 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3153 if (gr != 0) {
3154 if (gr == GLOB_NOMATCH) {
3155 globfree(&globdata);
3156 /* NB: garbles parameter */
3157 unbackslash(pattern);
3158 o_addstr_with_NUL(o, pattern);
3159 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3160 return o_save_ptr_helper(o, n);
3161 }
3162 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003163 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003164 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3165 * but we didn't specify it. Paranoia again. */
3166 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3167 }
3168 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3169 char **argv = globdata.gl_pathv;
3170 while (1) {
3171 o_addstr_with_NUL(o, *argv);
3172 n = o_save_ptr_helper(o, n);
3173 argv++;
3174 if (!*argv)
3175 break;
3176 }
3177 }
3178 globfree(&globdata);
3179 }
3180 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003181}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003182/* Performs globbing on last list[],
3183 * saving each result as a new list[].
3184 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003185static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003186{
3187 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003188
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003189 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003190 if (!o->data)
3191 return o_save_ptr_helper(o, n);
3192 pattern = o->data + o_get_last_ptr(o, n);
3193 debug_printf_glob("glob pattern '%s'\n", pattern);
3194 if (!glob_needed(pattern)) {
3195 /* unbackslash last string in o in place, fix length */
3196 o->length = unbackslash(pattern) - o->data;
3197 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3198 return o_save_ptr_helper(o, n);
3199 }
3200
3201 copy = xstrdup(pattern);
3202 /* "forget" pattern in o */
3203 o->length = pattern - o->data;
3204 n = glob_brace(copy, o, n);
3205 free(copy);
3206 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003207 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003208 return n;
3209}
3210
Denys Vlasenko238081f2010-10-03 14:26:26 +02003211#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003212
3213/* Helper */
3214static int glob_needed(const char *s)
3215{
3216 while (*s) {
3217 if (*s == '\\') {
3218 if (!s[1])
3219 return 0;
3220 s += 2;
3221 continue;
3222 }
3223 if (*s == '*' || *s == '[' || *s == '?')
3224 return 1;
3225 s++;
3226 }
3227 return 0;
3228}
3229/* Performs globbing on last list[],
3230 * saving each result as a new list[].
3231 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003232static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003233{
3234 glob_t globdata;
3235 int gr;
3236 char *pattern;
3237
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003238 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003239 if (!o->data)
3240 return o_save_ptr_helper(o, n);
3241 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003242 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003243 if (!glob_needed(pattern)) {
3244 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003245 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003246 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003247 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003248 return o_save_ptr_helper(o, n);
3249 }
3250
3251 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003252 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3253 * If we glob "*.\*" and don't find anything, we need
3254 * to fall back to using literal "*.*", but GLOB_NOCHECK
3255 * will return "*.\*"!
3256 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003257 gr = glob(pattern, 0, NULL, &globdata);
3258 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003259 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003260 if (gr == GLOB_NOMATCH) {
3261 globfree(&globdata);
3262 goto literal;
3263 }
3264 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003265 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003266 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3267 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003268 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003269 }
3270 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3271 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003272 /* "forget" pattern in o */
3273 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003274 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003275 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003276 n = o_save_ptr_helper(o, n);
3277 argv++;
3278 if (!*argv)
3279 break;
3280 }
3281 }
3282 globfree(&globdata);
3283 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003284 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003285 return n;
3286}
3287
Denys Vlasenko238081f2010-10-03 14:26:26 +02003288#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003289
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003290/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003291 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003292static int o_save_ptr(o_string *o, int n)
3293{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003294 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003295 /* If o->has_empty_slot, list[n] was already globbed
3296 * (if it was requested back then when it was filled)
3297 * so don't do that again! */
3298 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003299 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003300 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003301 return o_save_ptr_helper(o, n);
3302}
3303
3304/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003305static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003306{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003307 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003308 int string_start;
3309
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003310 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3311 if (DEBUG_EXPAND)
3312 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003313 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003314 list = (char**)o->data;
3315 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3316 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003317 while (n) {
3318 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003319 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003320 }
3321 return list;
3322}
3323
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003324static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003325
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003326/* Returns pi->next - next pipe in the list */
3327static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003328{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003329 struct pipe *next;
3330 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003331
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003332 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003333 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003334 struct command *command;
3335 struct redir_struct *r, *rnext;
3336
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003337 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003338 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003339 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003340 if (DEBUG_CLEAN) {
3341 int a;
3342 char **p;
3343 for (a = 0, p = command->argv; *p; a++, p++) {
3344 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3345 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003346 }
3347 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003348 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003349 }
3350 /* not "else if": on syntax error, we may have both! */
3351 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003352 debug_printf_clean(" begin group (cmd_type:%d)\n",
3353 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003354 free_pipe_list(command->group);
3355 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003356 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003357 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003358 /* else is crucial here.
3359 * If group != NULL, child_func is meaningless */
3360#if ENABLE_HUSH_FUNCTIONS
3361 else if (command->child_func) {
3362 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3363 command->child_func->parent_cmd = NULL;
3364 }
3365#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003366#if !BB_MMU
3367 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003369#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003370 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003371 debug_printf_clean(" redirect %d%s",
3372 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003373 /* guard against the case >$FOO, where foo is unset or blank */
3374 if (r->rd_filename) {
3375 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3376 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003377 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003378 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003379 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 rnext = r->next;
3381 free(r);
3382 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003383 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003384 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003385 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003386 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003387#if ENABLE_HUSH_JOB
3388 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003389 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003390#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003391
3392 next = pi->next;
3393 free(pi);
3394 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003395}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003396
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003397static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003398{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003399 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003400#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003401 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003402#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003403 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003404 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003405 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003406}
3407
3408
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003409/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003410
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003411#ifndef debug_print_tree
3412static void debug_print_tree(struct pipe *pi, int lvl)
3413{
3414 static const char *const PIPE[] = {
3415 [PIPE_SEQ] = "SEQ",
3416 [PIPE_AND] = "AND",
3417 [PIPE_OR ] = "OR" ,
3418 [PIPE_BG ] = "BG" ,
3419 };
3420 static const char *RES[] = {
3421 [RES_NONE ] = "NONE" ,
3422# if ENABLE_HUSH_IF
3423 [RES_IF ] = "IF" ,
3424 [RES_THEN ] = "THEN" ,
3425 [RES_ELIF ] = "ELIF" ,
3426 [RES_ELSE ] = "ELSE" ,
3427 [RES_FI ] = "FI" ,
3428# endif
3429# if ENABLE_HUSH_LOOPS
3430 [RES_FOR ] = "FOR" ,
3431 [RES_WHILE] = "WHILE",
3432 [RES_UNTIL] = "UNTIL",
3433 [RES_DO ] = "DO" ,
3434 [RES_DONE ] = "DONE" ,
3435# endif
3436# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3437 [RES_IN ] = "IN" ,
3438# endif
3439# if ENABLE_HUSH_CASE
3440 [RES_CASE ] = "CASE" ,
3441 [RES_CASE_IN ] = "CASE_IN" ,
3442 [RES_MATCH] = "MATCH",
3443 [RES_CASE_BODY] = "CASE_BODY",
3444 [RES_ESAC ] = "ESAC" ,
3445# endif
3446 [RES_XXXX ] = "XXXX" ,
3447 [RES_SNTX ] = "SNTX" ,
3448 };
3449 static const char *const CMDTYPE[] = {
3450 "{}",
3451 "()",
3452 "[noglob]",
3453# if ENABLE_HUSH_FUNCTIONS
3454 "func()",
3455# endif
3456 };
3457
3458 int pin, prn;
3459
3460 pin = 0;
3461 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003462 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3463 lvl*2, "",
3464 pin,
3465 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3466 RES[pi->res_word],
3467 pi->followup, PIPE[pi->followup]
3468 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003469 prn = 0;
3470 while (prn < pi->num_cmds) {
3471 struct command *command = &pi->cmds[prn];
3472 char **argv = command->argv;
3473
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003474 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003475 lvl*2, "", prn,
3476 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003477#if ENABLE_HUSH_LINENO_VAR
3478 fdprintf(2, " LINENO:%u", command->lineno);
3479#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003480 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003481 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003482 CMDTYPE[command->cmd_type],
3483 argv
3484# if !BB_MMU
3485 , " group_as_string:", command->group_as_string
3486# else
3487 , "", ""
3488# endif
3489 );
3490 debug_print_tree(command->group, lvl+1);
3491 prn++;
3492 continue;
3493 }
3494 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003495 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003496 argv++;
3497 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003498 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003499 prn++;
3500 }
3501 pi = pi->next;
3502 pin++;
3503 }
3504}
3505#endif /* debug_print_tree */
3506
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003507static struct pipe *new_pipe(void)
3508{
Eric Andersen25f27032001-04-26 23:22:31 +00003509 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003510 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003511 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003512 return pi;
3513}
3514
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003515/* Command (member of a pipe) is complete, or we start a new pipe
3516 * if ctx->command is NULL.
3517 * No errors possible here.
3518 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003519static int done_command(struct parse_context *ctx)
3520{
3521 /* The command is really already in the pipe structure, so
3522 * advance the pipe counter and make a new, null command. */
3523 struct pipe *pi = ctx->pipe;
3524 struct command *command = ctx->command;
3525
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003526#if 0 /* Instead we emit error message at run time */
3527 if (ctx->pending_redirect) {
3528 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003529 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003530 ctx->pending_redirect = NULL;
3531 }
3532#endif
3533
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003534 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003535 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003536 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003537 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003538 }
3539 pi->num_cmds++;
3540 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003541 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003542 } else {
3543 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3544 }
3545
3546 /* Only real trickiness here is that the uncommitted
3547 * command structure is not counted in pi->num_cmds. */
3548 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003549 ctx->command = command = &pi->cmds[pi->num_cmds];
3550 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003551 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003552#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003553 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003554 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003555#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003556 return pi->num_cmds; /* used only for 0/nonzero check */
3557}
3558
3559static void done_pipe(struct parse_context *ctx, pipe_style type)
3560{
3561 int not_null;
3562
3563 debug_printf_parse("done_pipe entered, followup %d\n", type);
3564 /* Close previous command */
3565 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003566#if HAS_KEYWORDS
3567 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3568 ctx->ctx_inverted = 0;
3569 ctx->pipe->res_word = ctx->ctx_res_w;
3570#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003571 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3572 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003573 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3574 * in a backgrounded subshell.
3575 */
3576 struct pipe *pi;
3577 struct command *command;
3578
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003579 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003580 pi = ctx->list_head;
3581 while (pi != ctx->pipe) {
3582 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3583 goto no_conv;
3584 pi = pi->next;
3585 }
3586
3587 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3588 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3589 pi = xzalloc(sizeof(*pi));
3590 pi->followup = PIPE_BG;
3591 pi->num_cmds = 1;
3592 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3593 command = &pi->cmds[0];
3594 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3595 command->cmd_type = CMD_NORMAL;
3596 command->group = ctx->list_head;
3597#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003598 command->group_as_string = xstrndup(
3599 ctx->as_string.data,
3600 ctx->as_string.length - 1 /* do not copy last char, "&" */
3601 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003602#endif
3603 /* Replace all pipes in ctx with one newly created */
3604 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003605 } else {
3606 no_conv:
3607 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003608 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003609
3610 /* Without this check, even just <enter> on command line generates
3611 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003612 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003613 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003614#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003615 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003616#endif
3617#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003618 || ctx->ctx_res_w == RES_DONE
3619 || ctx->ctx_res_w == RES_FOR
3620 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003621#endif
3622#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003623 || ctx->ctx_res_w == RES_ESAC
3624#endif
3625 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003626 struct pipe *new_p;
3627 debug_printf_parse("done_pipe: adding new pipe: "
3628 "not_null:%d ctx->ctx_res_w:%d\n",
3629 not_null, ctx->ctx_res_w);
3630 new_p = new_pipe();
3631 ctx->pipe->next = new_p;
3632 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003633 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003634 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003635 * This is used to control execution.
3636 * RES_FOR and RES_IN are NOT sticky (needed to support
3637 * cases where variable or value happens to match a keyword):
3638 */
3639#if ENABLE_HUSH_LOOPS
3640 if (ctx->ctx_res_w == RES_FOR
3641 || ctx->ctx_res_w == RES_IN)
3642 ctx->ctx_res_w = RES_NONE;
3643#endif
3644#if ENABLE_HUSH_CASE
3645 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003646 ctx->ctx_res_w = RES_CASE_BODY;
3647 if (ctx->ctx_res_w == RES_CASE)
3648 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003649#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003650 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003651 /* Create the memory for command, roughly:
3652 * ctx->pipe->cmds = new struct command;
3653 * ctx->command = &ctx->pipe->cmds[0];
3654 */
3655 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003656 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003657 }
3658 debug_printf_parse("done_pipe return\n");
3659}
3660
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003661static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003662{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003663 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003664 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003665 /* Create the memory for command, roughly:
3666 * ctx->pipe->cmds = new struct command;
3667 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003668 */
3669 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003670}
3671
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003672/* If a reserved word is found and processed, parse context is modified
3673 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003674 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003675#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003676struct reserved_combo {
3677 char literal[6];
3678 unsigned char res;
3679 unsigned char assignment_flag;
3680 int flag;
3681};
3682enum {
3683 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003684# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003685 FLAG_IF = (1 << RES_IF ),
3686 FLAG_THEN = (1 << RES_THEN ),
3687 FLAG_ELIF = (1 << RES_ELIF ),
3688 FLAG_ELSE = (1 << RES_ELSE ),
3689 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003690# endif
3691# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003692 FLAG_FOR = (1 << RES_FOR ),
3693 FLAG_WHILE = (1 << RES_WHILE),
3694 FLAG_UNTIL = (1 << RES_UNTIL),
3695 FLAG_DO = (1 << RES_DO ),
3696 FLAG_DONE = (1 << RES_DONE ),
3697 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003698# endif
3699# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003700 FLAG_MATCH = (1 << RES_MATCH),
3701 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003702# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003703 FLAG_START = (1 << RES_XXXX ),
3704};
3705
3706static const struct reserved_combo* match_reserved_word(o_string *word)
3707{
Eric Andersen25f27032001-04-26 23:22:31 +00003708 /* Mostly a list of accepted follow-up reserved words.
3709 * FLAG_END means we are done with the sequence, and are ready
3710 * to turn the compound list into a command.
3711 * FLAG_START means the word must start a new compound list.
3712 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003713 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003714# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003715 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3716 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3717 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3718 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3719 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3720 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003721# endif
3722# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003723 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3724 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3725 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3726 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3727 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3728 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003729# endif
3730# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003731 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3732 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003733# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003734 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003735 const struct reserved_combo *r;
3736
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003737 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003738 if (strcmp(word->data, r->literal) == 0)
3739 return r;
3740 }
3741 return NULL;
3742}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003743/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003744 */
Denys Vlasenko5807e182018-02-08 19:19:04 +01003745static const struct reserved_combo* reserved_word(o_string *word, struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003746{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003747# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003748 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003749 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003750 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003751# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003752 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003753
Denys Vlasenko38292b62010-09-05 14:49:40 +02003754 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003755 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003756 r = match_reserved_word(word);
3757 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003758 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003759
3760 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003761# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003762 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3763 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003764 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003765 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003766# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003767 if (r->flag == 0) { /* '!' */
3768 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003769 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003770 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003771 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003772 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003773 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003774 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003775 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003776 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003777
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003778 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003779 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003780 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003781 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003782 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003783 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003784 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003785 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003786 } else {
3787 /* "{...} fi" is ok. "{...} if" is not
3788 * Example:
3789 * if { echo foo; } then { echo bar; } fi */
3790 if (ctx->command->group)
3791 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003792 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003793
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003794 ctx->ctx_res_w = r->res;
3795 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003796 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003797 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003798
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003799 if (ctx->old_flag & FLAG_END) {
3800 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003801
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003802 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003803 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003804 old = ctx->stack;
3805 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003806 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003807# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003808 /* At this point, the compound command's string is in
3809 * ctx->as_string... except for the leading keyword!
3810 * Consider this example: "echo a | if true; then echo a; fi"
3811 * ctx->as_string will contain "true; then echo a; fi",
3812 * with "if " remaining in old->as_string!
3813 */
3814 {
3815 char *str;
3816 int len = old->as_string.length;
3817 /* Concatenate halves */
3818 o_addstr(&old->as_string, ctx->as_string.data);
3819 o_free_unsafe(&ctx->as_string);
3820 /* Find where leading keyword starts in first half */
3821 str = old->as_string.data + len;
3822 if (str > old->as_string.data)
3823 str--; /* skip whitespace after keyword */
3824 while (str > old->as_string.data && isalpha(str[-1]))
3825 str--;
3826 /* Ugh, we're done with this horrid hack */
3827 old->command->group_as_string = xstrdup(str);
3828 debug_printf_parse("pop, remembering as:'%s'\n",
3829 old->command->group_as_string);
3830 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003831# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003832 *ctx = *old; /* physical copy */
3833 free(old);
3834 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003835 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003836}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003837#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003838
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003839/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003840 * Normal return is 0. Syntax errors return 1.
3841 * Note: on return, word is reset, but not o_free'd!
3842 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003843static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003844{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003845 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003846
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003847 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003848 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003849 debug_printf_parse("done_word return 0: true null, ignored\n");
3850 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003851 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003852
Eric Andersen25f27032001-04-26 23:22:31 +00003853 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003854 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3855 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003856 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003857 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003858 * If the redirection operator is "<<" or "<<-", the word
3859 * that follows the redirection operator shall be
3860 * subjected to quote removal; it is unspecified whether
3861 * any of the other expansions occur. For the other
3862 * redirection operators, the word that follows the
3863 * redirection operator shall be subjected to tilde
3864 * expansion, parameter expansion, command substitution,
3865 * arithmetic expansion, and quote removal.
3866 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003867 * on the word by a non-interactive shell; an interactive
3868 * shell may perform it, but shall do so only when
3869 * the expansion would result in one word."
3870 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003871//bash does not do parameter/command substitution or arithmetic expansion
3872//for _heredoc_ redirection word: these constructs look for exact eof marker
3873// as written:
3874// <<EOF$t
3875// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003876// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3877
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003878 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003879 /* Cater for >\file case:
3880 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3881 * Same with heredocs:
3882 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3883 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003884 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3885 unbackslash(ctx->pending_redirect->rd_filename);
3886 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003887 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003888 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3889 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003890 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003891 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003892 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003893 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003894#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003895# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003896 if (ctx->ctx_dsemicolon
3897 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3898 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003899 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003900 /* ctx->ctx_res_w = RES_MATCH; */
3901 ctx->ctx_dsemicolon = 0;
3902 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003903# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003904 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003905# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003906 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3907 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003908# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003909# if ENABLE_HUSH_CASE
3910 && ctx->ctx_res_w != RES_CASE
3911# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003912 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003913 const struct reserved_combo *reserved;
3914 reserved = reserved_word(word, ctx);
3915 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003916 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003917# if ENABLE_HUSH_LINENO_VAR
3918/* Case:
3919 * "while ...; do
3920 * cmd ..."
3921 * If we don't close the pipe _now_, immediately after "do", lineno logic
3922 * sees "cmd" as starting at "do" - i.e., at the previous line.
3923 */
3924 if (0
3925 IF_HUSH_IF(|| reserved->res == RES_THEN)
3926 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3927 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3928 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3929 ) {
3930 done_pipe(ctx, PIPE_SEQ);
3931 }
3932# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003933 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003934 debug_printf_parse("done_word return %d\n",
3935 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003936 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003937 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003938# if defined(CMD_SINGLEWORD_NOGLOB)
3939 if (0
3940# if BASH_TEST2
3941 || strcmp(word->data, "[[") == 0
3942# endif
3943 /* In bash, local/export/readonly are special, args
3944 * are assignments and therefore expansion of them
3945 * should be "one-word" expansion:
3946 * $ export i=`echo 'a b'` # one arg: "i=a b"
3947 * compare with:
3948 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3949 * ls: cannot access i=a: No such file or directory
3950 * ls: cannot access b: No such file or directory
3951 * Note: bash 3.2.33(1) does this only if export word
3952 * itself is not quoted:
3953 * $ export i=`echo 'aaa bbb'`; echo "$i"
3954 * aaa bbb
3955 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3956 * aaa
3957 */
3958 IF_HUSH_LOCAL( || strcmp(word->data, "local") == 0)
3959 IF_HUSH_EXPORT( || strcmp(word->data, "export") == 0)
3960 IF_HUSH_READONLY( || strcmp(word->data, "readonly") == 0)
3961 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003962 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3963 }
3964 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003965# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003966 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003967#endif /* HAS_KEYWORDS */
3968
Denis Vlasenkobb929512009-04-16 10:59:40 +00003969 if (command->group) {
3970 /* "{ echo foo; } echo bar" - bad */
3971 syntax_error_at(word->data);
3972 debug_printf_parse("done_word return 1: syntax error, "
3973 "groups and arglists don't mix\n");
3974 return 1;
3975 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003976
3977 /* If this word wasn't an assignment, next ones definitely
3978 * can't be assignments. Even if they look like ones. */
3979 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3980 && word->o_assignment != WORD_IS_KEYWORD
3981 ) {
3982 word->o_assignment = NOT_ASSIGNMENT;
3983 } else {
3984 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3985 command->assignment_cnt++;
3986 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3987 }
3988 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3989 word->o_assignment = MAYBE_ASSIGNMENT;
3990 }
3991 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003992 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003993 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003994 }
Eric Andersen25f27032001-04-26 23:22:31 +00003995
Denis Vlasenko06810332007-05-21 23:30:54 +00003996#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003997 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003998 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003999 || !is_well_formed_var_name(command->argv[0], '\0')
4000 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004001 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004002 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004003 return 1;
4004 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004005 /* Force FOR to have just one word (variable name) */
4006 /* NB: basically, this makes hush see "for v in ..."
4007 * syntax as if it is "for v; in ...". FOR and IN become
4008 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004009 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004010 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004011#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004012#if ENABLE_HUSH_CASE
4013 /* Force CASE to have just one word */
4014 if (ctx->ctx_res_w == RES_CASE) {
4015 done_pipe(ctx, PIPE_SEQ);
4016 }
4017#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004018
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004019 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004020
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004021 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004022 return 0;
4023}
4024
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004025
4026/* Peek ahead in the input to find out if we have a "&n" construct,
4027 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004028 * Return:
4029 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4030 * REDIRFD_SYNTAX_ERR if syntax error,
4031 * REDIRFD_TO_FILE if no & was seen,
4032 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004033 */
4034#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004035#define parse_redir_right_fd(as_string, input) \
4036 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004037#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004038static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004039{
4040 int ch, d, ok;
4041
4042 ch = i_peek(input);
4043 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004044 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004045
4046 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004047 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004048 ch = i_peek(input);
4049 if (ch == '-') {
4050 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004051 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004052 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004053 }
4054 d = 0;
4055 ok = 0;
4056 while (ch != EOF && isdigit(ch)) {
4057 d = d*10 + (ch-'0');
4058 ok = 1;
4059 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004060 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004061 ch = i_peek(input);
4062 }
4063 if (ok) return d;
4064
4065//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4066
4067 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004068 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004069}
4070
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004071/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004072 */
4073static int parse_redirect(struct parse_context *ctx,
4074 int fd,
4075 redir_type style,
4076 struct in_str *input)
4077{
4078 struct command *command = ctx->command;
4079 struct redir_struct *redir;
4080 struct redir_struct **redirp;
4081 int dup_num;
4082
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004083 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004084 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004085 /* Check for a '>&1' type redirect */
4086 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4087 if (dup_num == REDIRFD_SYNTAX_ERR)
4088 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004089 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004090 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004091 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004092 if (dup_num) { /* <<-... */
4093 ch = i_getch(input);
4094 nommu_addchr(&ctx->as_string, ch);
4095 ch = i_peek(input);
4096 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004098
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004099 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004100 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004101 if (ch == '|') {
4102 /* >|FILE redirect ("clobbering" >).
4103 * Since we do not support "set -o noclobber" yet,
4104 * >| and > are the same for now. Just eat |.
4105 */
4106 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004107 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004108 }
4109 }
4110
4111 /* Create a new redir_struct and append it to the linked list */
4112 redirp = &command->redirects;
4113 while ((redir = *redirp) != NULL) {
4114 redirp = &(redir->next);
4115 }
4116 *redirp = redir = xzalloc(sizeof(*redir));
4117 /* redir->next = NULL; */
4118 /* redir->rd_filename = NULL; */
4119 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004120 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004121
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004122 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4123 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004124
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004125 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004126 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004127 /* Erik had a check here that the file descriptor in question
4128 * is legit; I postpone that to "run time"
4129 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004130 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4131 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004132 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004133#if 0 /* Instead we emit error message at run time */
4134 if (ctx->pending_redirect) {
4135 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004136 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004137 }
4138#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004139 /* Set ctx->pending_redirect, so we know what to do at the
4140 * end of the next parsed word. */
4141 ctx->pending_redirect = redir;
4142 }
4143 return 0;
4144}
4145
Eric Andersen25f27032001-04-26 23:22:31 +00004146/* If a redirect is immediately preceded by a number, that number is
4147 * supposed to tell which file descriptor to redirect. This routine
4148 * looks for such preceding numbers. In an ideal world this routine
4149 * needs to handle all the following classes of redirects...
4150 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4151 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4152 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4153 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004154 *
4155 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4156 * "2.7 Redirection
4157 * ... If n is quoted, the number shall not be recognized as part of
4158 * the redirection expression. For example:
4159 * echo \2>a
4160 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004161 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004162 *
4163 * A -1 return means no valid number was found,
4164 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004165 */
4166static int redirect_opt_num(o_string *o)
4167{
4168 int num;
4169
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004170 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004171 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004172 num = bb_strtou(o->data, NULL, 10);
4173 if (errno || num < 0)
4174 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004175 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004176 return num;
4177}
4178
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004179#if BB_MMU
4180#define fetch_till_str(as_string, input, word, skip_tabs) \
4181 fetch_till_str(input, word, skip_tabs)
4182#endif
4183static char *fetch_till_str(o_string *as_string,
4184 struct in_str *input,
4185 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004186 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004187{
4188 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004189 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004190 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004191 int ch;
4192
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004193 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004194
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004195 while (1) {
4196 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004197 if (ch != EOF)
4198 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004199 if (ch == '\n' || ch == EOF) {
4200 check_heredoc_end:
4201 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4202 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4203 heredoc.data[past_EOL] = '\0';
4204 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4205 return heredoc.data;
4206 }
4207 if (ch == '\n') {
4208 /* This is a new line.
4209 * Remember position and backslash-escaping status.
4210 */
4211 o_addchr(&heredoc, ch);
4212 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004213 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004214 past_EOL = heredoc.length;
4215 /* Get 1st char of next line, possibly skipping leading tabs */
4216 do {
4217 ch = i_getch(input);
4218 if (ch != EOF)
4219 nommu_addchr(as_string, ch);
4220 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4221 /* If this immediately ended the line,
4222 * go back to end-of-line checks.
4223 */
4224 if (ch == '\n')
4225 goto check_heredoc_end;
4226 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004227 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004228 }
4229 if (ch == EOF) {
4230 o_free_unsafe(&heredoc);
4231 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004232 }
4233 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004234 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004235 if (prev == '\\' && ch == '\\')
4236 /* Correctly handle foo\\<eol> (not a line cont.) */
4237 prev = 0; /* not \ */
4238 else
4239 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004240 }
4241}
4242
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004243/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4244 * and load them all. There should be exactly heredoc_cnt of them.
4245 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004246static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4247{
4248 struct pipe *pi = ctx->list_head;
4249
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004250 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004251 int i;
4252 struct command *cmd = pi->cmds;
4253
4254 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4255 pi->num_cmds,
4256 cmd->argv ? cmd->argv[0] : "NONE");
4257 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004258 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004259
4260 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4261 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004262 while (redir) {
4263 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004264 char *p;
4265
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004266 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004267 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004268 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004269 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004270 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004271 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004272 return 1;
4273 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004274 free(redir->rd_filename);
4275 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004276 heredoc_cnt--;
4277 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004278 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004279 }
4280 cmd++;
4281 }
4282 pi = pi->next;
4283 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004284#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004285 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004286 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004287 bb_error_msg_and_die("heredoc BUG 2");
4288#endif
4289 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004290}
4291
4292
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004293static int run_list(struct pipe *pi);
4294#if BB_MMU
4295#define parse_stream(pstring, input, end_trigger) \
4296 parse_stream(input, end_trigger)
4297#endif
4298static struct pipe *parse_stream(char **pstring,
4299 struct in_str *input,
4300 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004301
Eric Andersen25f27032001-04-26 23:22:31 +00004302
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004303#if !ENABLE_HUSH_FUNCTIONS
4304#define parse_group(dest, ctx, input, ch) \
4305 parse_group(ctx, input, ch)
4306#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004307static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004308 struct in_str *input, int ch)
4309{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004310 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004311 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004312 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004313#if BB_MMU
4314# define as_string NULL
4315#else
4316 char *as_string = NULL;
4317#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004318 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004319 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004320 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004321
4322 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004323#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004324 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004325 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004326 if (done_word(dest, ctx))
4327 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004328 if (!command->argv)
4329 goto skip; /* (... */
4330 if (command->argv[1]) { /* word word ... (... */
4331 syntax_error_unexpected_ch('(');
4332 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004333 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004334 /* it is "word(..." or "word (..." */
4335 do
4336 ch = i_getch(input);
4337 while (ch == ' ' || ch == '\t');
4338 if (ch != ')') {
4339 syntax_error_unexpected_ch(ch);
4340 return 1;
4341 }
4342 nommu_addchr(&ctx->as_string, ch);
4343 do
4344 ch = i_getch(input);
4345 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004346 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004347 syntax_error_unexpected_ch(ch);
4348 return 1;
4349 }
4350 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004351 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004352 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004353 }
4354#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004355
4356#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004357 if (command->argv /* word [word]{... */
4358 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004359 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004360 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004361 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004362 debug_printf_parse("parse_group return 1: "
4363 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004364 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004365 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004366#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004367
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004368 IF_HUSH_FUNCTIONS(skip:)
4369
Denis Vlasenko240c2552009-04-03 03:45:05 +00004370 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004371 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004372 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004373 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4374 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004375 } else {
4376 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004377 ch = i_peek(input);
4378 if (ch != ' ' && ch != '\t' && ch != '\n'
4379 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4380 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004381 syntax_error_unexpected_ch(ch);
4382 return 1;
4383 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004384 if (ch != '(') {
4385 ch = i_getch(input);
4386 nommu_addchr(&ctx->as_string, ch);
4387 }
Eric Andersen25f27032001-04-26 23:22:31 +00004388 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004389
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004390 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004391#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004392 if (as_string)
4393 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004394#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004395
4396 /* empty ()/{} or parse error? */
4397 if (!pipe_list || pipe_list == ERR_PTR) {
4398 /* parse_stream already emitted error msg */
4399 if (!BB_MMU)
4400 free(as_string);
4401 debug_printf_parse("parse_group return 1: "
4402 "parse_stream returned %p\n", pipe_list);
4403 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004404 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004405#if !BB_MMU
4406 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4407 command->group_as_string = as_string;
4408 debug_printf_parse("end of group, remembering as:'%s'\n",
4409 command->group_as_string);
4410#endif
4411
4412#if ENABLE_HUSH_FUNCTIONS
4413 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4414 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4415 struct command *cmd2;
4416
4417 cmd2 = xzalloc(sizeof(*cmd2));
4418 cmd2->cmd_type = CMD_SUBSHELL;
4419 cmd2->group = pipe_list;
4420# if !BB_MMU
4421//UNTESTED!
4422 cmd2->group_as_string = command->group_as_string;
4423 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4424# endif
4425
4426 pipe_list = new_pipe();
4427 pipe_list->cmds = cmd2;
4428 pipe_list->num_cmds = 1;
4429 }
4430#endif
4431
4432 command->group = pipe_list;
4433
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004434 debug_printf_parse("parse_group return 0\n");
4435 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004436 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004437#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004438}
4439
Denys Vlasenko0b883582016-12-23 16:49:07 +01004440#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004441/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004442static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004443/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004444static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004445{
4446 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004447 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004448 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004449 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004450 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004451 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004452 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004453 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004454 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004455 }
4456}
4457/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004458static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004459{
4460 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004461 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004462 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004463 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004464 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004465 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004466 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004467 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004468 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004469 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004470 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004471 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004472 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004473 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004474 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4475 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004476 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477 continue;
4478 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004479 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004480 }
4481}
4482/* Process `cmd` - copy contents until "`" is seen. Complicated by
4483 * \` quoting.
4484 * "Within the backquoted style of command substitution, backslash
4485 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4486 * The search for the matching backquote shall be satisfied by the first
4487 * backquote found without a preceding backslash; during this search,
4488 * if a non-escaped backquote is encountered within a shell comment,
4489 * a here-document, an embedded command substitution of the $(command)
4490 * form, or a quoted string, undefined results occur. A single-quoted
4491 * or double-quoted string that begins, but does not end, within the
4492 * "`...`" sequence produces undefined results."
4493 * Example Output
4494 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4495 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004496static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004497{
4498 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004499 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004500 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004501 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004502 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004503 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4504 ch = i_getch(input);
4505 if (ch != '`'
4506 && ch != '$'
4507 && ch != '\\'
4508 && (!in_dquote || ch != '"')
4509 ) {
4510 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004511 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004512 }
4513 if (ch == EOF) {
4514 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004515 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004516 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004517 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004518 }
4519}
4520/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4521 * quoting and nested ()s.
4522 * "With the $(command) style of command substitution, all characters
4523 * following the open parenthesis to the matching closing parenthesis
4524 * constitute the command. Any valid shell script can be used for command,
4525 * except a script consisting solely of redirections which produces
4526 * unspecified results."
4527 * Example Output
4528 * echo $(echo '(TEST)' BEST) (TEST) BEST
4529 * echo $(echo 'TEST)' BEST) TEST) BEST
4530 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004531 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004532 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004533 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004534 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4535 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004536 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004537#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004538static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004539{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004540 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004541 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004542# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004543 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004544# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004545 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4546
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004547 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004548 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004549 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004550 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004551 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004552 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004553 if (ch == end_ch
4554# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004555 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004556# endif
4557 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004558 if (!dbl)
4559 break;
4560 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004561 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004562 i_getch(input); /* eat second ')' */
4563 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004564 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004565 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004566 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004567 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004568 if (ch == '(' || ch == '{') {
4569 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004570 if (!add_till_closing_bracket(dest, input, ch))
4571 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004572 o_addchr(dest, ch);
4573 continue;
4574 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004575 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004576 if (!add_till_single_quote(dest, input))
4577 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004578 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004579 continue;
4580 }
4581 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004582 if (!add_till_double_quote(dest, input))
4583 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004584 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004585 continue;
4586 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004587 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4589 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004590 o_addchr(dest, ch);
4591 continue;
4592 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004593 if (ch == '\\') {
4594 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004595 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004596 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004597 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004598 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004599 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004600#if 0
4601 if (ch == '\n') {
4602 /* "backslash+newline", ignore both */
4603 o_delchr(dest); /* undo insertion of '\' */
4604 continue;
4605 }
4606#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004607 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004608 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004609 continue;
4610 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004611 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004612 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004613}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004614#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004615
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004616/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004617#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004618#define parse_dollar(as_string, dest, input, quote_mask) \
4619 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004620#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004621#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004622static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004623 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004624 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004625{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004626 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004627
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004628 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004629 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004630 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004631 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004632 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004633 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004634 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004635 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004636 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004637 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004638 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004639 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004640 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004641 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004642 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004643 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004644 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004645 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004646 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004647 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004648 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004649 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004650 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004651 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004652 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004653 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004654 o_addchr(dest, ch | quote_mask);
4655 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004656 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004657 case '$': /* pid */
4658 case '!': /* last bg pid */
4659 case '?': /* last exit code */
4660 case '#': /* number of args */
4661 case '*': /* args */
4662 case '@': /* args */
4663 goto make_one_char_var;
4664 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004665 char len_single_ch;
4666
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004667 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4668
Denys Vlasenko74369502010-05-21 19:52:01 +02004669 ch = i_getch(input); /* eat '{' */
4670 nommu_addchr(as_string, ch);
4671
Denys Vlasenko46e64982016-09-29 19:50:55 +02004672 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004673 /* It should be ${?}, or ${#var},
4674 * or even ${?+subst} - operator acting on a special variable,
4675 * or the beginning of variable name.
4676 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004677 if (ch == EOF
4678 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4679 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004680 bad_dollar_syntax:
4681 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004682 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4683 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004684 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004685 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004686 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004687 ch |= quote_mask;
4688
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004689 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004690 * However, this regresses some of our testsuite cases
4691 * which check invalid constructs like ${%}.
4692 * Oh well... let's check that the var name part is fine... */
4693
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004694 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004695 unsigned pos;
4696
Denys Vlasenko74369502010-05-21 19:52:01 +02004697 o_addchr(dest, ch);
4698 debug_printf_parse(": '%c'\n", ch);
4699
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004700 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004701 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004702 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004703 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004704
Denys Vlasenko74369502010-05-21 19:52:01 +02004705 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004706 unsigned end_ch;
4707 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004708 /* handle parameter expansions
4709 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4710 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004711 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4712 if (len_single_ch != '#'
4713 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4714 || i_peek(input) != '}'
4715 ) {
4716 goto bad_dollar_syntax;
4717 }
4718 /* else: it's "length of C" ${#C} op,
4719 * where C is a single char
4720 * special var name, e.g. ${#!}.
4721 */
4722 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004723 /* Eat everything until closing '}' (or ':') */
4724 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004725 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004726 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004727 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004728 ) {
4729 /* It's ${var:N[:M]} thing */
4730 end_ch = '}' * 0x100 + ':';
4731 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004732 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004733 && ch == '/'
4734 ) {
4735 /* It's ${var/[/]pattern[/repl]} thing */
4736 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4737 i_getch(input);
4738 nommu_addchr(as_string, '/');
4739 ch = '\\';
4740 }
4741 end_ch = '}' * 0x100 + '/';
4742 }
4743 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004744 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004745 if (!BB_MMU)
4746 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004747#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004748 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004749 if (last_ch == 0) /* error? */
4750 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004751#else
4752#error Simple code to only allow ${var} is not implemented
4753#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004754 if (as_string) {
4755 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004756 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004757 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004758
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004759 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4760 && (end_ch & 0xff00)
4761 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004762 /* close the first block: */
4763 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004764 /* while parsing N from ${var:N[:M]}
4765 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004766 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004767 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004768 end_ch = '}';
4769 goto again;
4770 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004771 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004772 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004773 /* it's ${var:N} - emulate :999999999 */
4774 o_addstr(dest, "999999999");
4775 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004776 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004777 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004778 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004779 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004780 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004781 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4782 break;
4783 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004784#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004785 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004786 unsigned pos;
4787
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004788 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004789 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004790# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004791 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004792 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004793 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004794 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4795 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004796 if (!BB_MMU)
4797 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004798 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4799 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004800 if (as_string) {
4801 o_addstr(as_string, dest->data + pos);
4802 o_addchr(as_string, ')');
4803 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004804 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004805 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004806 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004807 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004808# endif
4809# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004810 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4811 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004812 if (!BB_MMU)
4813 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004814 if (!add_till_closing_bracket(dest, input, ')'))
4815 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004816 if (as_string) {
4817 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004818 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004819 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004820 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004821# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004822 break;
4823 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004824#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004825 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004826 goto make_var;
4827#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004828 /* TODO: $_ and $-: */
4829 /* $_ Shell or shell script name; or last argument of last command
4830 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4831 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004832 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004833 ch = i_getch(input);
4834 nommu_addchr(as_string, ch);
4835 ch = i_peek_and_eat_bkslash_nl(input);
4836 if (isalnum(ch)) { /* it's $_name or $_123 */
4837 ch = '_';
4838 goto make_var1;
4839 }
4840 /* else: it's $_ */
4841#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004842 default:
4843 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004844 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004845 debug_printf_parse("parse_dollar return 1 (ok)\n");
4846 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004847#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004848}
4849
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004850#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004851# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004852#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4853 encode_string(dest, input, dquote_end, process_bkslash)
4854# else
4855/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4856#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4857 encode_string(dest, input, dquote_end)
4858# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004859#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004860
4861#else /* !MMU */
4862
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004863# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004864/* all parameters are needed, no macro tricks */
4865# else
4866#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4867 encode_string(as_string, dest, input, dquote_end)
4868# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004869#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004870static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004871 o_string *dest,
4872 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004873 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004874 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004875{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004876#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004877 const int process_bkslash = 1;
4878#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004879 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004880 int next;
4881
4882 again:
4883 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004884 if (ch != EOF)
4885 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004886 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004887 debug_printf_parse("encode_string return 1 (ok)\n");
4888 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004889 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004890 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004891 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004892 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004893 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004894 }
4895 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004896 if (ch != '\n') {
4897 next = i_peek(input);
4898 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004899 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004900 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004901 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004902 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004903 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004904 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004905 }
4906 /* bash:
4907 * "The backslash retains its special meaning [in "..."]
4908 * only when followed by one of the following characters:
4909 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004910 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004911 * NB: in (unquoted) heredoc, above does not apply to ",
4912 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004913 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004914 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004915 ch = i_getch(input); /* eat next */
4916 if (ch == '\n')
4917 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004918 } /* else: ch remains == '\\', and we double it below: */
4919 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004920 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004921 goto again;
4922 }
4923 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004924 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4925 debug_printf_parse("encode_string return 0: "
4926 "parse_dollar returned 0 (error)\n");
4927 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004928 }
4929 goto again;
4930 }
4931#if ENABLE_HUSH_TICK
4932 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004933 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004934 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4935 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004936 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4937 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004938 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4939 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004940 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004941 }
4942#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004943 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004944 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004945#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004946}
4947
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004948/*
4949 * Scan input until EOF or end_trigger char.
4950 * Return a list of pipes to execute, or NULL on EOF
4951 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004952 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004953 * reset parsing machinery and start parsing anew,
4954 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004955 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004956static struct pipe *parse_stream(char **pstring,
4957 struct in_str *input,
4958 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004959{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004960 struct parse_context ctx;
4961 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004962 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004963
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004964 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004965 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004966 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004967 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004968 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004969 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004970
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004971 /* If very first arg is "" or '', dest.data may end up NULL.
4972 * Preventing this: */
4973 o_addchr(&dest, '\0');
4974 dest.length = 0;
4975
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004976 /* We used to separate words on $IFS here. This was wrong.
4977 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004978 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004979 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004980
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004981 if (MAYBE_ASSIGNMENT != 0)
4982 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004983 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004984 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004985 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004986 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004987 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004988 int ch;
4989 int next;
4990 int redir_fd;
4991 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004992
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004993 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004994 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004995 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004996 if (ch == EOF) {
4997 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004998
4999 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005000 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005001 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005002 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005003 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005004 syntax_error_unterm_ch('(');
5005 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005006 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005007 if (end_trigger == '}') {
5008 syntax_error_unterm_ch('{');
5009 goto parse_error;
5010 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005011
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005012 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005013 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005014 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005015 o_free(&dest);
5016 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005017 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005018 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005019 /* (this makes bare "&" cmd a no-op.
5020 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005021 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005022 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005023 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005024 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005025 pi = NULL;
5026 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005027#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005028 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005029 if (pstring)
5030 *pstring = ctx.as_string.data;
5031 else
5032 o_free_unsafe(&ctx.as_string);
5033#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005034 debug_leave();
5035 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005036 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005037 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005038 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005039
5040 next = '\0';
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005041 if (ch != '\n') {
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005042 next = i_peek(input);
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005043 /* Can't use i_peek_and_eat_bkslash_nl(input) here:
5044 * echo '\
5045 * '
5046 * will break.
5047 */
5048 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005049
5050 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005051 "\\$\"" IF_HUSH_TICK("`") /* always special */
5052 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005053 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005054 if (ctx.command->argv /* word [word]{... - non-special */
5055 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005056 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005057 || (next != ';' /* }; - special */
5058 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005059 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005060 && next != '&' /* }& and }&& ... - special */
5061 && next != '|' /* }|| ... - special */
5062 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005063 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005064 ) {
5065 /* They are not special, skip "{}" */
5066 is_special += 2;
5067 }
5068 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005069 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005070
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005071 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005072 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005073 o_addQchr(&dest, ch);
5074 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5075 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005076 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005077 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005078 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005079 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005080 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005081 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005082 continue;
5083 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005084
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005085 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005086#if ENABLE_HUSH_LINENO_VAR
5087/* Case:
5088 * "while ...; do<whitespace><newline>
5089 * cmd ..."
5090 * would think that "cmd" starts in <whitespace> -
5091 * i.e., at the previous line.
5092 * We need to skip all whitespace before newlines.
5093 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005094 while (ch != '\n') {
5095 next = i_peek(input);
5096 if (next != ' ' && next != '\t' && next != '\n')
5097 break; /* next char is not ws */
5098 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005099 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005100 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005101#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005102 if (done_word(&dest, &ctx)) {
5103 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005104 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005105 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005106 /* Is this a case when newline is simply ignored?
5107 * Some examples:
5108 * "cmd | <newline> cmd ..."
5109 * "case ... in <newline> word) ..."
5110 */
5111 if (IS_NULL_CMD(ctx.command)
5112 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005113 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005114 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005115 * Without check #1, interactive shell
5116 * ignores even bare <newline>,
5117 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005118 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005119 * ps2> _ <=== wrong, should be ps1
5120 * Without check #2, "cmd & <newline>"
5121 * is similarly mistreated.
5122 * (BTW, this makes "cmd & cmd"
5123 * and "cmd && cmd" non-orthogonal.
5124 * Really, ask yourself, why
5125 * "cmd && <newline>" doesn't start
5126 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005127 * The only reason is that it might be
5128 * a "cmd1 && <nl> cmd2 &" construct,
5129 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005130 */
5131 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005132 if (pi->num_cmds != 0 /* check #1 */
5133 && pi->followup != PIPE_BG /* check #2 */
5134 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005135 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005136 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005137 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005138 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005139 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005140 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5141 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005142 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005143 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005144 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005145 heredoc_cnt = 0;
5146 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005147 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005148 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005149 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005150 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005151 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005152 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005153 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005154
5155 /* "cmd}" or "cmd }..." without semicolon or &:
5156 * } is an ordinary char in this case, even inside { cmd; }
5157 * Pathological example: { ""}; } should exec "}" cmd
5158 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005159 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005160 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005161 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005162 ) {
5163 goto ordinary_char;
5164 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005165 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5166 /* Generally, there should be semicolon: "cmd; }"
5167 * However, bash allows to omit it if "cmd" is
5168 * a group. Examples:
5169 * { { echo 1; } }
5170 * {(echo 1)}
5171 * { echo 0 >&2 | { echo 1; } }
5172 * { while false; do :; done }
5173 * { case a in b) ;; esac }
5174 */
5175 if (ctx.command->group)
5176 goto term_group;
5177 goto ordinary_char;
5178 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005179 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005180 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005181 goto skip_end_trigger;
5182 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005183 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005184 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005185 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005186 && (ch != ';' || heredoc_cnt == 0)
5187#if ENABLE_HUSH_CASE
5188 && (ch != ')'
5189 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005190 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005191 )
5192#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005193 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005194 if (heredoc_cnt) {
5195 /* This is technically valid:
5196 * { cat <<HERE; }; echo Ok
5197 * heredoc
5198 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005199 * HERE
5200 * but we don't support this.
5201 * We require heredoc to be in enclosing {}/(),
5202 * if any.
5203 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005204 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005205 goto parse_error;
5206 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005207 if (done_word(&dest, &ctx)) {
5208 goto parse_error;
5209 }
5210 done_pipe(&ctx, PIPE_SEQ);
5211 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005212 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005213 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005214 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005215 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005216 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005217 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005218#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005219 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005220 if (pstring)
5221 *pstring = ctx.as_string.data;
5222 else
5223 o_free_unsafe(&ctx.as_string);
5224#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005225 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5226 /* Example: bare "{ }", "()" */
5227 G.last_exitcode = 2; /* bash compat */
5228 syntax_error_unexpected_ch(ch);
5229 goto parse_error2;
5230 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005231 debug_printf_parse("parse_stream return %p: "
5232 "end_trigger char found\n",
5233 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005234 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005235 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005236 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005237 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005238 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005239 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005240 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005241
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005242 /* Catch <, > before deciding whether this word is
5243 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5244 switch (ch) {
5245 case '>':
5246 redir_fd = redirect_opt_num(&dest);
5247 if (done_word(&dest, &ctx)) {
5248 goto parse_error;
5249 }
5250 redir_style = REDIRECT_OVERWRITE;
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02005251 if (next == '\\')
5252 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005253 if (next == '>') {
5254 redir_style = REDIRECT_APPEND;
5255 ch = i_getch(input);
5256 nommu_addchr(&ctx.as_string, ch);
5257 }
5258#if 0
5259 else if (next == '(') {
5260 syntax_error(">(process) not supported");
5261 goto parse_error;
5262 }
5263#endif
5264 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5265 goto parse_error;
5266 continue; /* back to top of while (1) */
5267 case '<':
5268 redir_fd = redirect_opt_num(&dest);
5269 if (done_word(&dest, &ctx)) {
5270 goto parse_error;
5271 }
5272 redir_style = REDIRECT_INPUT;
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02005273 if (next == '\\')
5274 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005275 if (next == '<') {
5276 redir_style = REDIRECT_HEREDOC;
5277 heredoc_cnt++;
5278 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5279 ch = i_getch(input);
5280 nommu_addchr(&ctx.as_string, ch);
5281 } else if (next == '>') {
5282 redir_style = REDIRECT_IO;
5283 ch = i_getch(input);
5284 nommu_addchr(&ctx.as_string, ch);
5285 }
5286#if 0
5287 else if (next == '(') {
5288 syntax_error("<(process) not supported");
5289 goto parse_error;
5290 }
5291#endif
5292 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5293 goto parse_error;
5294 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005295 case '#':
5296 if (dest.length == 0 && !dest.has_quoted_part) {
5297 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005298 /* note: we do not add it to &ctx.as_string */
5299/* TODO: in bash:
5300 * comment inside $() goes to the next \n, even inside quoted string (!):
5301 * cmd "$(cmd2 #comment)" - syntax error
5302 * cmd "`cmd2 #comment`" - ok
5303 * We accept both (comment ends where command subst ends, in both cases).
5304 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005305 while (1) {
5306 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005307 if (ch == '\n') {
5308 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005309 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005310 }
5311 ch = i_getch(input);
5312 if (ch == EOF)
5313 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005314 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005315 continue; /* back to top of while (1) */
5316 }
5317 break;
5318 case '\\':
5319 if (next == '\n') {
5320 /* It's "\<newline>" */
5321#if !BB_MMU
5322 /* Remove trailing '\' from ctx.as_string */
5323 ctx.as_string.data[--ctx.as_string.length] = '\0';
5324#endif
5325 ch = i_getch(input); /* eat it */
5326 continue; /* back to top of while (1) */
5327 }
5328 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005329 }
5330
5331 if (dest.o_assignment == MAYBE_ASSIGNMENT
5332 /* check that we are not in word in "a=1 2>word b=1": */
5333 && !ctx.pending_redirect
5334 ) {
5335 /* ch is a special char and thus this word
5336 * cannot be an assignment */
5337 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005338 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005339 }
5340
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005341 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5342
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005343 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005344 case SPECIAL_VAR_SYMBOL:
5345 /* Convert raw ^C to corresponding special variable reference */
5346 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5347 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5348 /* fall through */
5349 case '#':
5350 /* non-comment #: "echo a#b" etc */
5351 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005352 break;
5353 case '\\':
5354 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005355 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005356 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005357 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005358 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005359 /* note: ch != '\n' (that case does not reach this place) */
5360 o_addchr(&dest, '\\');
5361 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5362 o_addchr(&dest, ch);
5363 nommu_addchr(&ctx.as_string, ch);
5364 /* Example: echo Hello \2>file
5365 * we need to know that word 2 is quoted */
5366 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005367 break;
5368 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005369 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005370 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005371 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005372 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005373 }
Eric Andersen25f27032001-04-26 23:22:31 +00005374 break;
5375 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005376 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005377 if (next == '\'' && !ctx.pending_redirect) {
5378 insert_empty_quoted_str_marker:
5379 nommu_addchr(&ctx.as_string, next);
5380 i_getch(input); /* eat second ' */
5381 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5382 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5383 } else {
5384 while (1) {
5385 ch = i_getch(input);
5386 if (ch == EOF) {
5387 syntax_error_unterm_ch('\'');
5388 goto parse_error;
5389 }
5390 nommu_addchr(&ctx.as_string, ch);
5391 if (ch == '\'')
5392 break;
Denys Vlasenko9809a822018-01-13 19:14:27 +01005393 if (ch == SPECIAL_VAR_SYMBOL) {
5394 /* Convert raw ^C to corresponding special variable reference */
5395 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5396 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5397 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005398 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005399 }
Eric Andersen25f27032001-04-26 23:22:31 +00005400 }
Eric Andersen25f27032001-04-26 23:22:31 +00005401 break;
5402 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005403 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005404 if (next == '"' && !ctx.pending_redirect)
5405 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005406 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005407 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005408 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005409 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005410 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005411 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005412#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005413 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005414 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005415
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005416 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5417 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005418 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005419 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5420 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005421# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005422 o_addstr(&ctx.as_string, dest.data + pos);
5423 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005424# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005425 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5426 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005427 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005428 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005429#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005430 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005431#if ENABLE_HUSH_CASE
5432 case_semi:
5433#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005434 if (done_word(&dest, &ctx)) {
5435 goto parse_error;
5436 }
5437 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005438#if ENABLE_HUSH_CASE
5439 /* Eat multiple semicolons, detect
5440 * whether it means something special */
5441 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005442 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005443 if (ch != ';')
5444 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005445 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005446 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005447 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005448 ctx.ctx_dsemicolon = 1;
5449 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005450 break;
5451 }
5452 }
5453#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005454 new_cmd:
5455 /* We just finished a cmd. New one may start
5456 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005457 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005458 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005459 break;
5460 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005461 if (done_word(&dest, &ctx)) {
5462 goto parse_error;
5463 }
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005464 if (next == '\\')
5465 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005466 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005467 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005468 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005469 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005470 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005471 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005472 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005473 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005474 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005475 if (done_word(&dest, &ctx)) {
5476 goto parse_error;
5477 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005478#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005479 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005480 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005481#endif
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005482 if (next == '\\')
5483 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005484 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005485 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005486 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005487 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005488 } else {
5489 /* we could pick up a file descriptor choice here
5490 * with redirect_opt_num(), but bash doesn't do it.
5491 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005492 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005493 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005494 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005495 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005496#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005497 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005498 if (ctx.ctx_res_w == RES_MATCH
5499 && ctx.command->argv == NULL /* not (word|(... */
5500 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005501 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005502 ) {
5503 continue;
5504 }
5505#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005506 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005507 if (parse_group(&dest, &ctx, input, ch) != 0) {
5508 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005509 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005510 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005511 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005512#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005513 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005514 goto case_semi;
5515#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005516 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005517 /* proper use of this character is caught by end_trigger:
5518 * if we see {, we call parse_group(..., end_trigger='}')
5519 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005520 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005521 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005522 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005523 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005524 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005525 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005526 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005527 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005528
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005529 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005530 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005531 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005532 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005533 struct parse_context *pctx;
5534 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005535
5536 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005537 * Sample for finding leaks on syntax error recovery path.
5538 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005539 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005540 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005541 * while if (true | { true;}); then echo ok; fi; do break; done
5542 * 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 +00005543 */
5544 pctx = &ctx;
5545 do {
5546 /* Update pipe/command counts,
5547 * otherwise freeing may miss some */
5548 done_pipe(pctx, PIPE_SEQ);
5549 debug_printf_clean("freeing list %p from ctx %p\n",
5550 pctx->list_head, pctx);
5551 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005552 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005553 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005554#if !BB_MMU
5555 o_free_unsafe(&pctx->as_string);
5556#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005557 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005558 if (pctx != &ctx) {
5559 free(pctx);
5560 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005561 IF_HAS_KEYWORDS(pctx = p2;)
5562 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005563
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005564 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005565#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005566 if (pstring)
5567 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005568#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005569 debug_leave();
5570 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005571 }
Eric Andersen25f27032001-04-26 23:22:31 +00005572}
5573
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005574
5575/*** Execution routines ***/
5576
5577/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005578#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005579/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5580#define expand_string_to_string(str, do_unbackslash) \
5581 expand_string_to_string(str)
5582#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005583static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005584#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005585static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005586#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005587
5588/* expand_strvec_to_strvec() takes a list of strings, expands
5589 * all variable references within and returns a pointer to
5590 * a list of expanded strings, possibly with larger number
5591 * of strings. (Think VAR="a b"; echo $VAR).
5592 * This new list is allocated as a single malloc block.
5593 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005594 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005595 * Caller can deallocate entire list by single free(list). */
5596
Denys Vlasenko238081f2010-10-03 14:26:26 +02005597/* A horde of its helpers come first: */
5598
5599static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5600{
5601 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005602 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005603
Denys Vlasenko9e800222010-10-03 14:28:04 +02005604#if ENABLE_HUSH_BRACE_EXPANSION
5605 if (c == '{' || c == '}') {
5606 /* { -> \{, } -> \} */
5607 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005608 /* And now we want to add { or } and continue:
5609 * o_addchr(o, c);
5610 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005611 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005612 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005613 }
5614#endif
5615 o_addchr(o, c);
5616 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005617 /* \z -> \\\z; \<eol> -> \\<eol> */
5618 o_addchr(o, '\\');
5619 if (len) {
5620 len--;
5621 o_addchr(o, '\\');
5622 o_addchr(o, *str++);
5623 }
5624 }
5625 }
5626}
5627
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005628/* Store given string, finalizing the word and starting new one whenever
5629 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005630 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5631 * Return in *ended_with_ifs:
5632 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5633 */
5634static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005635{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005636 int last_is_ifs = 0;
5637
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005638 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005639 int word_len;
5640
5641 if (!*str) /* EOL - do not finalize word */
5642 break;
5643 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005644 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005645 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005646 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005647 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005648 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005649 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005650 * Example: "v='\*'; echo b$v" prints "b\*"
5651 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005652 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005653 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005654 /*/ Why can't we do it easier? */
5655 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5656 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5657 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005658 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005660 if (!*str) /* EOL - do not finalize word */
5661 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005662 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005663
5664 /* We know str here points to at least one IFS char */
5665 last_is_ifs = 1;
5666 str += strspn(str, G.ifs); /* skip IFS chars */
5667 if (!*str) /* EOL - do not finalize word */
5668 break;
5669
5670 /* Start new word... but not always! */
5671 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005672 if (output->has_quoted_part
5673 /* Case "v=' a'; echo $v":
5674 * here nothing precedes the space in $v expansion,
5675 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005676 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005677 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005678 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005679 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005680 o_addchr(output, '\0');
5681 debug_print_list("expand_on_ifs", output, n);
5682 n = o_save_ptr(output, n);
5683 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005684 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005685
5686 if (ended_with_ifs)
5687 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005688 debug_print_list("expand_on_ifs[1]", output, n);
5689 return n;
5690}
5691
5692/* Helper to expand $((...)) and heredoc body. These act as if
5693 * they are in double quotes, with the exception that they are not :).
5694 * Just the rules are similar: "expand only $var and `cmd`"
5695 *
5696 * Returns malloced string.
5697 * As an optimization, we return NULL if expansion is not needed.
5698 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005699#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005700/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5701#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5702 encode_then_expand_string(str)
5703#endif
5704static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005705{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005706#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005707 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005708#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005709 char *exp_str;
5710 struct in_str input;
5711 o_string dest = NULL_O_STRING;
5712
5713 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005714 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005715#if ENABLE_HUSH_TICK
5716 && !strchr(str, '`')
5717#endif
5718 ) {
5719 return NULL;
5720 }
5721
5722 /* We need to expand. Example:
5723 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5724 */
5725 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005726 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005727//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005728 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005729 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005730 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5731 o_free_unsafe(&dest);
5732 return exp_str;
5733}
5734
Denys Vlasenko0b883582016-12-23 16:49:07 +01005735#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005736static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005737{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005738 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739 arith_t res;
5740 char *exp_str;
5741
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005742 math_state.lookupvar = get_local_var_value;
5743 math_state.setvar = set_local_var_from_halves;
5744 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005745 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005746 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005747 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005748 if (errmsg_p)
5749 *errmsg_p = math_state.errmsg;
5750 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005751 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005752 return res;
5753}
5754#endif
5755
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005756#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005757/* ${var/[/]pattern[/repl]} helpers */
5758static char *strstr_pattern(char *val, const char *pattern, int *size)
5759{
5760 while (1) {
5761 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5762 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5763 if (end) {
5764 *size = end - val;
5765 return val;
5766 }
5767 if (*val == '\0')
5768 return NULL;
5769 /* Optimization: if "*pat" did not match the start of "string",
5770 * we know that "tring", "ring" etc will not match too:
5771 */
5772 if (pattern[0] == '*')
5773 return NULL;
5774 val++;
5775 }
5776}
5777static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5778{
5779 char *result = NULL;
5780 unsigned res_len = 0;
5781 unsigned repl_len = strlen(repl);
5782
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005783 /* Null pattern never matches, including if "var" is empty */
5784 if (!pattern[0])
5785 return result; /* NULL, no replaces happened */
5786
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005787 while (1) {
5788 int size;
5789 char *s = strstr_pattern(val, pattern, &size);
5790 if (!s)
5791 break;
5792
5793 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005794 strcpy(mempcpy(result + res_len, val, s - val), repl);
5795 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005796 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5797
5798 val = s + size;
5799 if (exp_op == '/')
5800 break;
5801 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005802 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005803 result = xrealloc(result, res_len + strlen(val) + 1);
5804 strcpy(result + res_len, val);
5805 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5806 }
5807 debug_printf_varexp("result:'%s'\n", result);
5808 return result;
5809}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005810#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005811
5812/* Helper:
5813 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5814 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005815static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005816{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005817 const char *val;
5818 char *to_be_freed;
5819 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005820 char *var;
5821 char first_char;
5822 char exp_op;
5823 char exp_save = exp_save; /* for compiler */
5824 char *exp_saveptr; /* points to expansion operator */
5825 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005826 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005827
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005828 val = NULL;
5829 to_be_freed = NULL;
5830 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005831 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005832 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005833 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005834 arg0 = arg[0];
5835 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005836 exp_op = 0;
5837
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005838 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5839 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5840 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5841 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005842 ) {
5843 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005844 var++;
5845 exp_op = 'L';
5846 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005847 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005848 if (exp_saveptr /* if 2nd char is one of expansion operators */
5849 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5850 ) {
5851 /* ${?:0}, ${#[:]%0} etc */
5852 exp_saveptr = var + 1;
5853 } else {
5854 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5855 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5856 }
5857 exp_op = exp_save = *exp_saveptr;
5858 if (exp_op) {
5859 exp_word = exp_saveptr + 1;
5860 if (exp_op == ':') {
5861 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005862//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005863 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005864 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005865 ) {
5866 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5867 exp_op = ':';
5868 exp_word--;
5869 }
5870 }
5871 *exp_saveptr = '\0';
5872 } /* else: it's not an expansion op, but bare ${var} */
5873 }
5874
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005875 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005876 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005877 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878 int n = xatoi_positive(var);
5879 if (n < G.global_argc)
5880 val = G.global_argv[n];
5881 /* else val remains NULL: $N with too big N */
5882 } else {
5883 switch (var[0]) {
5884 case '$': /* pid */
5885 val = utoa(G.root_pid);
5886 break;
5887 case '!': /* bg pid */
5888 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5889 break;
5890 case '?': /* exitcode */
5891 val = utoa(G.last_exitcode);
5892 break;
5893 case '#': /* argc */
5894 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5895 break;
5896 default:
5897 val = get_local_var_value(var);
5898 }
5899 }
5900
5901 /* Handle any expansions */
5902 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005903 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005904 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005905 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005906 debug_printf_expand("%s\n", val);
5907 } else if (exp_op) {
5908 if (exp_op == '%' || exp_op == '#') {
5909 /* Standard-mandated substring removal ops:
5910 * ${parameter%word} - remove smallest suffix pattern
5911 * ${parameter%%word} - remove largest suffix pattern
5912 * ${parameter#word} - remove smallest prefix pattern
5913 * ${parameter##word} - remove largest prefix pattern
5914 *
5915 * Word is expanded to produce a glob pattern.
5916 * Then var's value is matched to it and matching part removed.
5917 */
5918 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005919 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005920 char *exp_exp_word;
5921 char *loc;
5922 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005923 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005924 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005925 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005926 /*
5927 * process_bkslash:1 unbackslash:1 breaks this:
5928 * a='a\\'; echo ${a%\\\\} # correct output is: a
5929 * process_bkslash:1 unbackslash:0 breaks this:
5930 * a='a}'; echo ${a%\}} # correct output is: a
5931 */
5932 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005933 if (exp_exp_word)
5934 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005935 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005936 /* HACK ALERT. We depend here on the fact that
5937 * G.global_argv and results of utoa and get_local_var_value
5938 * are actually in writable memory:
5939 * scan_and_match momentarily stores NULs there. */
5940 t = (char*)val;
5941 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005942 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 +02005943 free(exp_exp_word);
5944 if (loc) { /* match was found */
5945 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005946 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005947 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005948 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005949 }
5950 }
5951 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005952#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005953 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005954 /* It's ${var/[/]pattern[/repl]} thing.
5955 * Note that in encoded form it has TWO parts:
5956 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005957 * and if // is used, it is encoded as \:
5958 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005959 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005960 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005961 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005962 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005963 * by the usual expansion rules:
5964 * >az; >bz;
5965 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5966 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5967 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5968 * v='a bz'; echo ${v/a*z/\z} prints "z"
5969 * (note that a*z _pattern_ is never globbed!)
5970 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005971 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005972 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005973 if (!pattern)
5974 pattern = xstrdup(exp_word);
5975 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5976 *p++ = SPECIAL_VAR_SYMBOL;
5977 exp_word = p;
5978 p = strchr(p, SPECIAL_VAR_SYMBOL);
5979 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005980 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005981 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5982 /* HACK ALERT. We depend here on the fact that
5983 * G.global_argv and results of utoa and get_local_var_value
5984 * are actually in writable memory:
5985 * replace_pattern momentarily stores NULs there. */
5986 t = (char*)val;
5987 to_be_freed = replace_pattern(t,
5988 pattern,
5989 (repl ? repl : exp_word),
5990 exp_op);
5991 if (to_be_freed) /* at least one replace happened */
5992 val = to_be_freed;
5993 free(pattern);
5994 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005995 } else {
5996 /* Empty variable always gives nothing */
5997 // "v=''; echo ${v/*/w}" prints "", not "w"
5998 /* Just skip "replace" part */
5999 *p++ = SPECIAL_VAR_SYMBOL;
6000 p = strchr(p, SPECIAL_VAR_SYMBOL);
6001 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006002 }
6003 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006004#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006005 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006006#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006007 /* It's ${var:N[:M]} bashism.
6008 * Note that in encoded form it has TWO parts:
6009 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6010 */
6011 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006012 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006013
Denys Vlasenko063847d2010-09-15 13:33:02 +02006014 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6015 if (errmsg)
6016 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6018 *p++ = SPECIAL_VAR_SYMBOL;
6019 exp_word = p;
6020 p = strchr(p, SPECIAL_VAR_SYMBOL);
6021 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006022 len = expand_and_evaluate_arith(exp_word, &errmsg);
6023 if (errmsg)
6024 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006025 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006026 if (beg < 0) {
6027 /* negative beg counts from the end */
6028 beg = (arith_t)strlen(val) + beg;
6029 if (beg < 0) /* ${v: -999999} is "" */
6030 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006031 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006032 debug_printf_varexp("from val:'%s'\n", val);
6033 if (len < 0) {
6034 /* in bash, len=-n means strlen()-n */
6035 len = (arith_t)strlen(val) - beg + len;
6036 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006037 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006038 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006039 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006040 arith_err:
6041 val = NULL;
6042 } else {
6043 /* Paranoia. What if user entered 9999999999999
6044 * which fits in arith_t but not int? */
6045 if (len >= INT_MAX)
6046 len = INT_MAX;
6047 val = to_be_freed = xstrndup(val + beg, len);
6048 }
6049 debug_printf_varexp("val:'%s'\n", val);
6050#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006051 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006052 val = NULL;
6053#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006054 } else { /* one of "-=+?" */
6055 /* Standard-mandated substitution ops:
6056 * ${var?word} - indicate error if unset
6057 * If var is unset, word (or a message indicating it is unset
6058 * if word is null) is written to standard error
6059 * and the shell exits with a non-zero exit status.
6060 * Otherwise, the value of var is substituted.
6061 * ${var-word} - use default value
6062 * If var is unset, word is substituted.
6063 * ${var=word} - assign and use default value
6064 * If var is unset, word is assigned to var.
6065 * In all cases, final value of var is substituted.
6066 * ${var+word} - use alternative value
6067 * If var is unset, null is substituted.
6068 * Otherwise, word is substituted.
6069 *
6070 * Word is subjected to tilde expansion, parameter expansion,
6071 * command substitution, and arithmetic expansion.
6072 * If word is not needed, it is not expanded.
6073 *
6074 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6075 * but also treat null var as if it is unset.
6076 */
6077 int use_word = (!val || ((exp_save == ':') && !val[0]));
6078 if (exp_op == '+')
6079 use_word = !use_word;
6080 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6081 (exp_save == ':') ? "true" : "false", use_word);
6082 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006083 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006084 if (to_be_freed)
6085 exp_word = to_be_freed;
6086 if (exp_op == '?') {
6087 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006088 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006089 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006090 exp_word[0]
6091 ? exp_word
6092 : "parameter null or not set"
6093 /* ash has more specific messages, a-la: */
6094 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006095 );
6096//TODO: how interactive bash aborts expansion mid-command?
6097 } else {
6098 val = exp_word;
6099 }
6100
6101 if (exp_op == '=') {
6102 /* ${var=[word]} or ${var:=[word]} */
6103 if (isdigit(var[0]) || var[0] == '#') {
6104 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006105 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006106 val = NULL;
6107 } else {
6108 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006109 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006110 }
6111 }
6112 }
6113 } /* one of "-=+?" */
6114
6115 *exp_saveptr = exp_save;
6116 } /* if (exp_op) */
6117
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006118 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006119
6120 *pp = p;
6121 *to_be_freed_pp = to_be_freed;
6122 return val;
6123}
6124
6125/* Expand all variable references in given string, adding words to list[]
6126 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6127 * to be filled). This routine is extremely tricky: has to deal with
6128 * variables/parameters with whitespace, $* and $@, and constructs like
6129 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006130static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006131{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006132 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006133 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006134 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006135 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006136 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006137 char *p;
6138
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006139 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6140 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006141 debug_print_list("expand_vars_to_list", output, n);
6142 n = o_save_ptr(output, n);
6143 debug_print_list("expand_vars_to_list[0]", output, n);
6144
6145 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6146 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006147 char *to_be_freed = NULL;
6148 const char *val = NULL;
6149#if ENABLE_HUSH_TICK
6150 o_string subst_result = NULL_O_STRING;
6151#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006152#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153 char arith_buf[sizeof(arith_t)*3 + 2];
6154#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006155
6156 if (ended_in_ifs) {
6157 o_addchr(output, '\0');
6158 n = o_save_ptr(output, n);
6159 ended_in_ifs = 0;
6160 }
6161
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006162 o_addblock(output, arg, p - arg);
6163 debug_print_list("expand_vars_to_list[1]", output, n);
6164 arg = ++p;
6165 p = strchr(p, SPECIAL_VAR_SYMBOL);
6166
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006167 /* Fetch special var name (if it is indeed one of them)
6168 * and quote bit, force the bit on if singleword expansion -
6169 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006170 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006171
6172 /* Is this variable quoted and thus expansion can't be null?
6173 * "$@" is special. Even if quoted, it can still
6174 * expand to nothing (not even an empty string),
6175 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006176 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006177 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006178
6179 switch (first_ch & 0x7f) {
6180 /* Highest bit in first_ch indicates that var is double-quoted */
6181 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006182 case '@': {
6183 int i;
6184 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006185 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006186 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006187 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006188 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006189 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006190 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006191 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6192 if (G.global_argv[i++][0] && G.global_argv[i]) {
6193 /* this argv[] is not empty and not last:
6194 * put terminating NUL, start new word */
6195 o_addchr(output, '\0');
6196 debug_print_list("expand_vars_to_list[2]", output, n);
6197 n = o_save_ptr(output, n);
6198 debug_print_list("expand_vars_to_list[3]", output, n);
6199 }
6200 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006201 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006202 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006203 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006204 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006205 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006206 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006207 while (1) {
6208 o_addQstr(output, G.global_argv[i]);
6209 if (++i >= G.global_argc)
6210 break;
6211 o_addchr(output, '\0');
6212 debug_print_list("expand_vars_to_list[4]", output, n);
6213 n = o_save_ptr(output, n);
6214 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006215 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006216 while (1) {
6217 o_addQstr(output, G.global_argv[i]);
6218 if (!G.global_argv[++i])
6219 break;
6220 if (G.ifs[0])
6221 o_addchr(output, G.ifs[0]);
6222 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006223 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006224 }
6225 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006226 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006227 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6228 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006229 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006230 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006231 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006232 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006233 case SPECIAL_VAR_QUOTED_SVS:
6234 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6235 arg++;
6236 val = SPECIAL_VAR_SYMBOL_STR;
6237 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006238#if ENABLE_HUSH_TICK
6239 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006240 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006241 arg++;
6242 /* Can't just stuff it into output o_string,
6243 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006244 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006245 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6246 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006247 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006248 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6249 val = subst_result.data;
6250 goto store_val;
6251#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006252#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006253 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6254 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006255
6256 arg++; /* skip '+' */
6257 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6258 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006259 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006260 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6261 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006262 val = arith_buf;
6263 break;
6264 }
6265#endif
6266 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006267 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268 IF_HUSH_TICK(store_val:)
6269 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006270 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6271 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006272 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006273 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006274 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006275 }
6276 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006277 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006278 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6279 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006280 }
6281 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006282 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6283
6284 if (val && val[0]) {
6285 o_addQstr(output, val);
6286 }
6287 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006288
6289 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6290 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006291 if (*p != SPECIAL_VAR_SYMBOL)
6292 *p = SPECIAL_VAR_SYMBOL;
6293
6294#if ENABLE_HUSH_TICK
6295 o_free(&subst_result);
6296#endif
6297 arg = ++p;
6298 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6299
6300 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006301 if (ended_in_ifs) {
6302 o_addchr(output, '\0');
6303 n = o_save_ptr(output, n);
6304 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006305 debug_print_list("expand_vars_to_list[a]", output, n);
6306 /* this part is literal, and it was already pre-quoted
6307 * if needed (much earlier), do not use o_addQstr here! */
6308 o_addstr_with_NUL(output, arg);
6309 debug_print_list("expand_vars_to_list[b]", output, n);
6310 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006311 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 ) {
6313 n--;
6314 /* allow to reuse list[n] later without re-growth */
6315 output->has_empty_slot = 1;
6316 } else {
6317 o_addchr(output, '\0');
6318 }
6319
6320 return n;
6321}
6322
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006323static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324{
6325 int n;
6326 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006327 o_string output = NULL_O_STRING;
6328
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006329 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006330
6331 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006332 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006333 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006334 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006335 }
6336 debug_print_list("expand_variables", &output, n);
6337
6338 /* output.data (malloced in one block) gets returned in "list" */
6339 list = o_finalize_list(&output, n);
6340 debug_print_strings("expand_variables[1]", list);
6341 return list;
6342}
6343
6344static char **expand_strvec_to_strvec(char **argv)
6345{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006346 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006347}
6348
Denys Vlasenko11752d42018-04-03 08:20:58 +02006349#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006350static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6351{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006352 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006353}
6354#endif
6355
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006356/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006357 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006358 *
6359 * NB: should NOT do globbing!
6360 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6361 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006362static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006363{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006364#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006365 const int do_unbackslash = 1;
6366#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006367 char *argv[2], **list;
6368
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006369 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006370 /* This is generally an optimization, but it also
6371 * handles "", which otherwise trips over !list[0] check below.
6372 * (is this ever happens that we actually get str="" here?)
6373 */
6374 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6375 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006376 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006377 return xstrdup(str);
6378 }
6379
6380 argv[0] = (char*)str;
6381 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006382 list = expand_variables(argv, do_unbackslash
6383 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6384 : EXP_FLAG_SINGLEWORD
6385 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006386 if (HUSH_DEBUG)
6387 if (!list[0] || list[1])
6388 bb_error_msg_and_die("BUG in varexp2");
6389 /* actually, just move string 2*sizeof(char*) bytes back */
6390 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006391 if (do_unbackslash)
6392 unbackslash((char*)list);
6393 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006394 return (char*)list;
6395}
6396
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006397#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006398static char* expand_strvec_to_string(char **argv)
6399{
6400 char **list;
6401
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006402 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403 /* Convert all NULs to spaces */
6404 if (list[0]) {
6405 int n = 1;
6406 while (list[n]) {
6407 if (HUSH_DEBUG)
6408 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6409 bb_error_msg_and_die("BUG in varexp3");
6410 /* bash uses ' ' regardless of $IFS contents */
6411 list[n][-1] = ' ';
6412 n++;
6413 }
6414 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006415 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006416 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6417 return (char*)list;
6418}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006419#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006420
6421static char **expand_assignments(char **argv, int count)
6422{
6423 int i;
6424 char **p;
6425
6426 G.expanded_assignments = p = NULL;
6427 /* Expand assignments into one string each */
6428 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006429 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006430 }
6431 G.expanded_assignments = NULL;
6432 return p;
6433}
6434
6435
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006436static void switch_off_special_sigs(unsigned mask)
6437{
6438 unsigned sig = 0;
6439 while ((mask >>= 1) != 0) {
6440 sig++;
6441 if (!(mask & 1))
6442 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006443#if ENABLE_HUSH_TRAP
6444 if (G_traps) {
6445 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006446 /* trap is '', has to remain SIG_IGN */
6447 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006448 free(G_traps[sig]);
6449 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006450 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006451#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006452 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006453 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006454 }
6455}
6456
Denys Vlasenkob347df92011-08-09 22:49:15 +02006457#if BB_MMU
6458/* never called */
6459void re_execute_shell(char ***to_free, const char *s,
6460 char *g_argv0, char **g_argv,
6461 char **builtin_argv) NORETURN;
6462
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006463static void reset_traps_to_defaults(void)
6464{
6465 /* This function is always called in a child shell
6466 * after fork (not vfork, NOMMU doesn't use this function).
6467 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006468 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006469 unsigned mask;
6470
6471 /* Child shells are not interactive.
6472 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6473 * Testcase: (while :; do :; done) + ^Z should background.
6474 * Same goes for SIGTERM, SIGHUP, SIGINT.
6475 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006476 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006477 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006478 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006479
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006480 /* Switch off special sigs */
6481 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006482# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006483 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006484# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006485 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006486 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6487 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006489# if ENABLE_HUSH_TRAP
6490 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006491 return;
6492
6493 /* Reset all sigs to default except ones with empty traps */
6494 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006495 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006496 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006497 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006498 continue; /* empty trap: has to remain SIG_IGN */
6499 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006500 free(G_traps[sig]);
6501 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006502 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006503 if (sig == 0)
6504 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006505 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006506 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006507# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006508}
6509
6510#else /* !BB_MMU */
6511
6512static void re_execute_shell(char ***to_free, const char *s,
6513 char *g_argv0, char **g_argv,
6514 char **builtin_argv) NORETURN;
6515static void re_execute_shell(char ***to_free, const char *s,
6516 char *g_argv0, char **g_argv,
6517 char **builtin_argv)
6518{
6519# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6520 /* delims + 2 * (number of bytes in printed hex numbers) */
6521 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6522 char *heredoc_argv[4];
6523 struct variable *cur;
6524# if ENABLE_HUSH_FUNCTIONS
6525 struct function *funcp;
6526# endif
6527 char **argv, **pp;
6528 unsigned cnt;
6529 unsigned long long empty_trap_mask;
6530
6531 if (!g_argv0) { /* heredoc */
6532 argv = heredoc_argv;
6533 argv[0] = (char *) G.argv0_for_re_execing;
6534 argv[1] = (char *) "-<";
6535 argv[2] = (char *) s;
6536 argv[3] = NULL;
6537 pp = &argv[3]; /* used as pointer to empty environment */
6538 goto do_exec;
6539 }
6540
6541 cnt = 0;
6542 pp = builtin_argv;
6543 if (pp) while (*pp++)
6544 cnt++;
6545
6546 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006547 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006548 int sig;
6549 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006550 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 empty_trap_mask |= 1LL << sig;
6552 }
6553 }
6554
6555 sprintf(param_buf, NOMMU_HACK_FMT
6556 , (unsigned) G.root_pid
6557 , (unsigned) G.root_ppid
6558 , (unsigned) G.last_bg_pid
6559 , (unsigned) G.last_exitcode
6560 , cnt
6561 , empty_trap_mask
6562 IF_HUSH_LOOPS(, G.depth_of_loop)
6563 );
6564# undef NOMMU_HACK_FMT
6565 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6566 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6567 */
6568 cnt += 6;
6569 for (cur = G.top_var; cur; cur = cur->next) {
6570 if (!cur->flg_export || cur->flg_read_only)
6571 cnt += 2;
6572 }
6573# if ENABLE_HUSH_FUNCTIONS
6574 for (funcp = G.top_func; funcp; funcp = funcp->next)
6575 cnt += 3;
6576# endif
6577 pp = g_argv;
6578 while (*pp++)
6579 cnt++;
6580 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6581 *pp++ = (char *) G.argv0_for_re_execing;
6582 *pp++ = param_buf;
6583 for (cur = G.top_var; cur; cur = cur->next) {
6584 if (strcmp(cur->varstr, hush_version_str) == 0)
6585 continue;
6586 if (cur->flg_read_only) {
6587 *pp++ = (char *) "-R";
6588 *pp++ = cur->varstr;
6589 } else if (!cur->flg_export) {
6590 *pp++ = (char *) "-V";
6591 *pp++ = cur->varstr;
6592 }
6593 }
6594# if ENABLE_HUSH_FUNCTIONS
6595 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6596 *pp++ = (char *) "-F";
6597 *pp++ = funcp->name;
6598 *pp++ = funcp->body_as_string;
6599 }
6600# endif
6601 /* We can pass activated traps here. Say, -Tnn:trap_string
6602 *
6603 * However, POSIX says that subshells reset signals with traps
6604 * to SIG_DFL.
6605 * I tested bash-3.2 and it not only does that with true subshells
6606 * of the form ( list ), but with any forked children shells.
6607 * I set trap "echo W" WINCH; and then tried:
6608 *
6609 * { echo 1; sleep 20; echo 2; } &
6610 * while true; do echo 1; sleep 20; echo 2; break; done &
6611 * true | { echo 1; sleep 20; echo 2; } | cat
6612 *
6613 * In all these cases sending SIGWINCH to the child shell
6614 * did not run the trap. If I add trap "echo V" WINCH;
6615 * _inside_ group (just before echo 1), it works.
6616 *
6617 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 */
6619 *pp++ = (char *) "-c";
6620 *pp++ = (char *) s;
6621 if (builtin_argv) {
6622 while (*++builtin_argv)
6623 *pp++ = *builtin_argv;
6624 *pp++ = (char *) "";
6625 }
6626 *pp++ = g_argv0;
6627 while (*g_argv)
6628 *pp++ = *g_argv++;
6629 /* *pp = NULL; - is already there */
6630 pp = environ;
6631
6632 do_exec:
6633 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006634 /* Don't propagate SIG_IGN to the child */
6635 if (SPECIAL_JOBSTOP_SIGS != 0)
6636 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006637 execve(bb_busybox_exec_path, argv, pp);
6638 /* Fallback. Useful for init=/bin/hush usage etc */
6639 if (argv[0][0] == '/')
6640 execve(argv[0], argv, pp);
6641 xfunc_error_retval = 127;
6642 bb_error_msg_and_die("can't re-execute the shell");
6643}
6644#endif /* !BB_MMU */
6645
6646
6647static int run_and_free_list(struct pipe *pi);
6648
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006649/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006650 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6651 * end_trigger controls how often we stop parsing
6652 * NUL: parse all, execute, return
6653 * ';': parse till ';' or newline, execute, repeat till EOF
6654 */
6655static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006656{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006657 /* Why we need empty flag?
6658 * An obscure corner case "false; ``; echo $?":
6659 * empty command in `` should still set $? to 0.
6660 * But we can't just set $? to 0 at the start,
6661 * this breaks "false; echo `echo $?`" case.
6662 */
6663 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006664 while (1) {
6665 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006666
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006667#if ENABLE_HUSH_INTERACTIVE
6668 if (end_trigger == ';')
6669 inp->promptmode = 0; /* PS1 */
6670#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006671 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006672 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6673 /* If we are in "big" script
6674 * (not in `cmd` or something similar)...
6675 */
6676 if (pipe_list == ERR_PTR && end_trigger == ';') {
6677 /* Discard cached input (rest of line) */
6678 int ch = inp->last_char;
6679 while (ch != EOF && ch != '\n') {
6680 //bb_error_msg("Discarded:'%c'", ch);
6681 ch = i_getch(inp);
6682 }
6683 /* Force prompt */
6684 inp->p = NULL;
6685 /* This stream isn't empty */
6686 empty = 0;
6687 continue;
6688 }
6689 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006690 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006691 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006692 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006693 debug_print_tree(pipe_list, 0);
6694 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6695 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006696 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006697 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006698 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006699 }
Eric Andersen25f27032001-04-26 23:22:31 +00006700}
6701
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006702static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006703{
6704 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006705 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6706
Eric Andersen25f27032001-04-26 23:22:31 +00006707 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006708 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006709 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006710}
6711
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006712static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006713{
Eric Andersen25f27032001-04-26 23:22:31 +00006714 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006715 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006716
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006717 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006718 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006719 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006720 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006721}
6722
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006723#if ENABLE_HUSH_TICK
6724static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6725{
6726 pid_t pid;
6727 int channel[2];
6728# if !BB_MMU
6729 char **to_free = NULL;
6730# endif
6731
6732 xpipe(channel);
6733 pid = BB_MMU ? xfork() : xvfork();
6734 if (pid == 0) { /* child */
6735 disable_restore_tty_pgrp_on_exit();
6736 /* Process substitution is not considered to be usual
6737 * 'command execution'.
6738 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6739 */
6740 bb_signals(0
6741 + (1 << SIGTSTP)
6742 + (1 << SIGTTIN)
6743 + (1 << SIGTTOU)
6744 , SIG_IGN);
6745 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6746 close(channel[0]); /* NB: close _first_, then move fd! */
6747 xmove_fd(channel[1], 1);
6748 /* Prevent it from trying to handle ctrl-z etc */
6749 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006750# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006751 /* Awful hack for `trap` or $(trap).
6752 *
6753 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6754 * contains an example where "trap" is executed in a subshell:
6755 *
6756 * save_traps=$(trap)
6757 * ...
6758 * eval "$save_traps"
6759 *
6760 * Standard does not say that "trap" in subshell shall print
6761 * parent shell's traps. It only says that its output
6762 * must have suitable form, but then, in the above example
6763 * (which is not supposed to be normative), it implies that.
6764 *
6765 * bash (and probably other shell) does implement it
6766 * (traps are reset to defaults, but "trap" still shows them),
6767 * but as a result, "trap" logic is hopelessly messed up:
6768 *
6769 * # trap
6770 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6771 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6772 * # true | trap <--- trap is in subshell - no output (ditto)
6773 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6774 * trap -- 'echo Ho' SIGWINCH
6775 * # echo `(trap)` <--- in subshell in subshell - output
6776 * trap -- 'echo Ho' SIGWINCH
6777 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6778 * trap -- 'echo Ho' SIGWINCH
6779 *
6780 * The rules when to forget and when to not forget traps
6781 * get really complex and nonsensical.
6782 *
6783 * Our solution: ONLY bare $(trap) or `trap` is special.
6784 */
6785 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006786 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006787 && skip_whitespace(s + 4)[0] == '\0'
6788 ) {
6789 static const char *const argv[] = { NULL, NULL };
6790 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006791 fflush_all(); /* important */
6792 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006793 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006794# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795# if BB_MMU
6796 reset_traps_to_defaults();
6797 parse_and_run_string(s);
6798 _exit(G.last_exitcode);
6799# else
6800 /* We re-execute after vfork on NOMMU. This makes this script safe:
6801 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6802 * huge=`cat BIG` # was blocking here forever
6803 * echo OK
6804 */
6805 re_execute_shell(&to_free,
6806 s,
6807 G.global_argv[0],
6808 G.global_argv + 1,
6809 NULL);
6810# endif
6811 }
6812
6813 /* parent */
6814 *pid_p = pid;
6815# if ENABLE_HUSH_FAST
6816 G.count_SIGCHLD++;
6817//bb_error_msg("[%d] fork in generate_stream_from_string:"
6818// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6819// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6820# endif
6821 enable_restore_tty_pgrp_on_exit();
6822# if !BB_MMU
6823 free(to_free);
6824# endif
6825 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006826 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006827}
6828
6829/* Return code is exit status of the process that is run. */
6830static int process_command_subs(o_string *dest, const char *s)
6831{
6832 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006833 pid_t pid;
6834 int status, ch, eol_cnt;
6835
6836 fp = generate_stream_from_string(s, &pid);
6837
6838 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006839 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006840 while ((ch = getc(fp)) != EOF) {
6841 if (ch == '\0')
6842 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006843 if (ch == '\n') {
6844 eol_cnt++;
6845 continue;
6846 }
6847 while (eol_cnt) {
6848 o_addchr(dest, '\n');
6849 eol_cnt--;
6850 }
6851 o_addQchr(dest, ch);
6852 }
6853
6854 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006855 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006856 /* We need to extract exitcode. Test case
6857 * "true; echo `sleep 1; false` $?"
6858 * should print 1 */
6859 safe_waitpid(pid, &status, 0);
6860 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6861 return WEXITSTATUS(status);
6862}
6863#endif /* ENABLE_HUSH_TICK */
6864
6865
6866static void setup_heredoc(struct redir_struct *redir)
6867{
6868 struct fd_pair pair;
6869 pid_t pid;
6870 int len, written;
6871 /* the _body_ of heredoc (misleading field name) */
6872 const char *heredoc = redir->rd_filename;
6873 char *expanded;
6874#if !BB_MMU
6875 char **to_free;
6876#endif
6877
6878 expanded = NULL;
6879 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006880 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006881 if (expanded)
6882 heredoc = expanded;
6883 }
6884 len = strlen(heredoc);
6885
6886 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6887 xpiped_pair(pair);
6888 xmove_fd(pair.rd, redir->rd_fd);
6889
6890 /* Try writing without forking. Newer kernels have
6891 * dynamically growing pipes. Must use non-blocking write! */
6892 ndelay_on(pair.wr);
6893 while (1) {
6894 written = write(pair.wr, heredoc, len);
6895 if (written <= 0)
6896 break;
6897 len -= written;
6898 if (len == 0) {
6899 close(pair.wr);
6900 free(expanded);
6901 return;
6902 }
6903 heredoc += written;
6904 }
6905 ndelay_off(pair.wr);
6906
6907 /* Okay, pipe buffer was not big enough */
6908 /* Note: we must not create a stray child (bastard? :)
6909 * for the unsuspecting parent process. Child creates a grandchild
6910 * and exits before parent execs the process which consumes heredoc
6911 * (that exec happens after we return from this function) */
6912#if !BB_MMU
6913 to_free = NULL;
6914#endif
6915 pid = xvfork();
6916 if (pid == 0) {
6917 /* child */
6918 disable_restore_tty_pgrp_on_exit();
6919 pid = BB_MMU ? xfork() : xvfork();
6920 if (pid != 0)
6921 _exit(0);
6922 /* grandchild */
6923 close(redir->rd_fd); /* read side of the pipe */
6924#if BB_MMU
6925 full_write(pair.wr, heredoc, len); /* may loop or block */
6926 _exit(0);
6927#else
6928 /* Delegate blocking writes to another process */
6929 xmove_fd(pair.wr, STDOUT_FILENO);
6930 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6931#endif
6932 }
6933 /* parent */
6934#if ENABLE_HUSH_FAST
6935 G.count_SIGCHLD++;
6936//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6937#endif
6938 enable_restore_tty_pgrp_on_exit();
6939#if !BB_MMU
6940 free(to_free);
6941#endif
6942 close(pair.wr);
6943 free(expanded);
6944 wait(NULL); /* wait till child has died */
6945}
6946
Denys Vlasenko2db74612017-07-07 22:07:28 +02006947struct squirrel {
6948 int orig_fd;
6949 int moved_to;
6950 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6951 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6952};
6953
Denys Vlasenko621fc502017-07-24 12:42:17 +02006954static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6955{
6956 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6957 sq[i].orig_fd = orig;
6958 sq[i].moved_to = moved;
6959 sq[i+1].orig_fd = -1; /* end marker */
6960 return sq;
6961}
6962
Denys Vlasenko2db74612017-07-07 22:07:28 +02006963static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6964{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006965 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006966 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006967
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006968 i = 0;
6969 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006970 /* If we collide with an already moved fd... */
6971 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006972 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006973 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6974 if (sq[i].moved_to < 0) /* what? */
6975 xfunc_die();
6976 return sq;
6977 }
6978 if (fd == sq[i].orig_fd) {
6979 /* Example: echo Hello >/dev/null 1>&2 */
6980 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6981 return sq;
6982 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006983 }
6984
Denys Vlasenko2db74612017-07-07 22:07:28 +02006985 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006986 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02006987 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6988 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006989 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006990 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006991}
6992
Denys Vlasenko657e9002017-07-30 23:34:04 +02006993static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6994{
6995 int i;
6996
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006997 i = 0;
6998 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006999 /* If we collide with an already moved fd... */
7000 if (fd == sq[i].orig_fd) {
7001 /* Examples:
7002 * "echo 3>FILE 3>&- 3>FILE"
7003 * "echo 3>&- 3>FILE"
7004 * No need for last redirect to insert
7005 * another "need to close 3" indicator.
7006 */
7007 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7008 return sq;
7009 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007010 }
7011
7012 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7013 return append_squirrel(sq, i, fd, -1);
7014}
7015
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007016/* fd: redirect wants this fd to be used (e.g. 3>file).
7017 * Move all conflicting internally used fds,
7018 * and remember them so that we can restore them later.
7019 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007020static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007021{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007022 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7023 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007024
7025#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007026 if (fd == G.interactive_fd) {
7027 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007028 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007029 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7030 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007031 }
7032#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007033 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7034 * (1) Redirect in a forked child. No need to save FILEs' fds,
7035 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007036 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7037 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007038 * "fileno(fd) = new_fd" can't be done.
7039 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007040 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007041 return 0;
7042
Denys Vlasenko2db74612017-07-07 22:07:28 +02007043 /* If this one of script's fds? */
7044 if (save_FILEs_on_redirect(fd, avoid_fd))
7045 return 1; /* yes. "we closed fd" */
7046
7047 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7048 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7049 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007050}
7051
Denys Vlasenko2db74612017-07-07 22:07:28 +02007052static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007053{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007054 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007055 int i;
7056 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007057 if (sq[i].moved_to >= 0) {
7058 /* We simply die on error */
7059 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7060 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7061 } else {
7062 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7063 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7064 close(sq[i].orig_fd);
7065 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007066 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007067 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007068 }
7069
Denys Vlasenko2db74612017-07-07 22:07:28 +02007070 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007071
7072 restore_redirected_FILEs();
7073}
7074
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007075#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007076static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007077{
7078 if (G_interactive_fd)
7079 close(G_interactive_fd);
7080 close_all_FILE_list();
7081}
7082#endif
7083
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007084static int internally_opened_fd(int fd, struct squirrel *sq)
7085{
7086 int i;
7087
7088#if ENABLE_HUSH_INTERACTIVE
7089 if (fd == G.interactive_fd)
7090 return 1;
7091#endif
7092 /* If this one of script's fds? */
7093 if (fd_in_FILEs(fd))
7094 return 1;
7095
7096 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7097 if (fd == sq[i].moved_to)
7098 return 1;
7099 }
7100 return 0;
7101}
7102
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007103/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7104 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007105static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007106{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007107 struct redir_struct *redir;
7108
7109 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007110 int newfd;
7111 int closed;
7112
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007113 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007114 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007115 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007116 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7117 * of the heredoc */
7118 debug_printf_parse("set heredoc '%s'\n",
7119 redir->rd_filename);
7120 setup_heredoc(redir);
7121 continue;
7122 }
7123
7124 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007125 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007126 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007127 int mode;
7128
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007129 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007130 /*
7131 * Examples:
7132 * "cmd >" (no filename)
7133 * "cmd > <file" (2nd redirect starts too early)
7134 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007135 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007136 continue;
7137 }
7138 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007139 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007140 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007141 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007142 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007143 /* Error message from open_or_warn can be lost
7144 * if stderr has been redirected, but bash
7145 * and ash both lose it as well
7146 * (though zsh doesn't!)
7147 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007148 return 1;
7149 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007150 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007151 /* open() gave us precisely the fd we wanted.
7152 * This means that this fd was not busy
7153 * (not opened to anywhere).
7154 * Remember to close it on restore:
7155 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007156 *sqp = add_squirrel_closed(*sqp, newfd);
7157 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007158 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007159 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007160 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7161 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007162 }
7163
Denys Vlasenko657e9002017-07-30 23:34:04 +02007164 if (newfd == redir->rd_fd)
7165 continue;
7166
7167 /* if "N>FILE": move newfd to redir->rd_fd */
7168 /* if "N>&M": dup newfd to redir->rd_fd */
7169 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7170
7171 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7172 if (newfd == REDIRFD_CLOSE) {
7173 /* "N>&-" means "close me" */
7174 if (!closed) {
7175 /* ^^^ optimization: saving may already
7176 * have closed it. If not... */
7177 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007178 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007179 /* Sometimes we do another close on restore, getting EBADF.
7180 * Consider "echo 3>FILE 3>&-"
7181 * first redirect remembers "need to close 3",
7182 * and second redirect closes 3! Restore code then closes 3 again.
7183 */
7184 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007185 /* if newfd is a script fd or saved fd, simulate EBADF */
7186 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7187 //errno = EBADF;
7188 //bb_perror_msg_and_die("can't duplicate file descriptor");
7189 newfd = -1; /* same effect as code above */
7190 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007191 xdup2(newfd, redir->rd_fd);
7192 if (redir->rd_dup == REDIRFD_TO_FILE)
7193 /* "rd_fd > FILE" */
7194 close(newfd);
7195 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007196 }
7197 }
7198 return 0;
7199}
7200
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007201static char *find_in_path(const char *arg)
7202{
7203 char *ret = NULL;
7204 const char *PATH = get_local_var_value("PATH");
7205
7206 if (!PATH)
7207 return NULL;
7208
7209 while (1) {
7210 const char *end = strchrnul(PATH, ':');
7211 int sz = end - PATH; /* must be int! */
7212
7213 free(ret);
7214 if (sz != 0) {
7215 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7216 } else {
7217 /* We have xxx::yyyy in $PATH,
7218 * it means "use current dir" */
7219 ret = xstrdup(arg);
7220 }
7221 if (access(ret, F_OK) == 0)
7222 break;
7223
7224 if (*end == '\0') {
7225 free(ret);
7226 return NULL;
7227 }
7228 PATH = end + 1;
7229 }
7230
7231 return ret;
7232}
7233
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007234static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007235 const struct built_in_command *x,
7236 const struct built_in_command *end)
7237{
7238 while (x != end) {
7239 if (strcmp(name, x->b_cmd) != 0) {
7240 x++;
7241 continue;
7242 }
7243 debug_printf_exec("found builtin '%s'\n", name);
7244 return x;
7245 }
7246 return NULL;
7247}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007248static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007249{
7250 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7251}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007252static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007253{
7254 const struct built_in_command *x = find_builtin1(name);
7255 if (x)
7256 return x;
7257 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7258}
7259
7260#if ENABLE_HUSH_FUNCTIONS
7261static struct function **find_function_slot(const char *name)
7262{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007263 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007264 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007265
7266 while ((funcp = *funcpp) != NULL) {
7267 if (strcmp(name, funcp->name) == 0) {
7268 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007269 break;
7270 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007271 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007272 }
7273 return funcpp;
7274}
7275
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007276static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277{
7278 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007279 return funcp;
7280}
7281
7282/* Note: takes ownership on name ptr */
7283static struct function *new_function(char *name)
7284{
7285 struct function **funcpp = find_function_slot(name);
7286 struct function *funcp = *funcpp;
7287
7288 if (funcp != NULL) {
7289 struct command *cmd = funcp->parent_cmd;
7290 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7291 if (!cmd) {
7292 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7293 free(funcp->name);
7294 /* Note: if !funcp->body, do not free body_as_string!
7295 * This is a special case of "-F name body" function:
7296 * body_as_string was not malloced! */
7297 if (funcp->body) {
7298 free_pipe_list(funcp->body);
7299# if !BB_MMU
7300 free(funcp->body_as_string);
7301# endif
7302 }
7303 } else {
7304 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7305 cmd->argv[0] = funcp->name;
7306 cmd->group = funcp->body;
7307# if !BB_MMU
7308 cmd->group_as_string = funcp->body_as_string;
7309# endif
7310 }
7311 } else {
7312 debug_printf_exec("remembering new function '%s'\n", name);
7313 funcp = *funcpp = xzalloc(sizeof(*funcp));
7314 /*funcp->next = NULL;*/
7315 }
7316
7317 funcp->name = name;
7318 return funcp;
7319}
7320
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007321# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007322static void unset_func(const char *name)
7323{
7324 struct function **funcpp = find_function_slot(name);
7325 struct function *funcp = *funcpp;
7326
7327 if (funcp != NULL) {
7328 debug_printf_exec("freeing function '%s'\n", funcp->name);
7329 *funcpp = funcp->next;
7330 /* funcp is unlinked now, deleting it.
7331 * Note: if !funcp->body, the function was created by
7332 * "-F name body", do not free ->body_as_string
7333 * and ->name as they were not malloced. */
7334 if (funcp->body) {
7335 free_pipe_list(funcp->body);
7336 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007337# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007338 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007339# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007340 }
7341 free(funcp);
7342 }
7343}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007344# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007345
7346# if BB_MMU
7347#define exec_function(to_free, funcp, argv) \
7348 exec_function(funcp, argv)
7349# endif
7350static void exec_function(char ***to_free,
7351 const struct function *funcp,
7352 char **argv) NORETURN;
7353static void exec_function(char ***to_free,
7354 const struct function *funcp,
7355 char **argv)
7356{
7357# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007358 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007359
7360 argv[0] = G.global_argv[0];
7361 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007362 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007363
7364// Example when we are here: "cmd | func"
7365// func will run with saved-redirect fds open.
7366// $ f() { echo /proc/self/fd/*; }
7367// $ true | f
7368// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7369// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7370// Same in script:
7371// $ . ./SCRIPT
7372// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7373// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7374// They are CLOEXEC so external programs won't see them, but
7375// for "more correctness" we might want to close those extra fds here:
7376//? close_saved_fds_and_FILE_fds();
7377
Denys Vlasenko332e4112018-04-04 22:32:59 +02007378 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007379 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007380 G.var_nest_level++;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007381 IF_HUSH_LOCAL(G.func_nest_level++;)
7382
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007383 /* On MMU, funcp->body is always non-NULL */
7384 n = run_list(funcp->body);
7385 fflush_all();
7386 _exit(n);
7387# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007388//? close_saved_fds_and_FILE_fds();
7389
7390//TODO: check whether "true | func_with_return" works
7391
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007392 re_execute_shell(to_free,
7393 funcp->body_as_string,
7394 G.global_argv[0],
7395 argv + 1,
7396 NULL);
7397# endif
7398}
7399
Denys Vlasenko332e4112018-04-04 22:32:59 +02007400static void enter_var_nest_level(void)
7401{
7402 G.var_nest_level++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007403 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007404
7405 /* Try: f() { echo -n .; f; }; f
7406 * struct variable::var_nest_level is uint16_t,
7407 * thus limiting recursion to < 2^16.
7408 * In any case, with 8 Mbyte stack SEGV happens
7409 * not too long after 2^16 recursions anyway.
7410 */
7411 if (G.var_nest_level > 0xff00)
7412 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7413}
7414
7415static void leave_var_nest_level(void)
7416{
7417 struct variable *cur;
7418 struct variable **cur_pp;
7419
7420 cur_pp = &G.top_var;
7421 while ((cur = *cur_pp) != NULL) {
7422 if (cur->var_nest_level < G.var_nest_level) {
7423 cur_pp = &cur->next;
7424 continue;
7425 }
7426 /* Unexport */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007427 if (cur->flg_export) {
7428 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007429 bb_unsetenv(cur->varstr);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007430 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02007431 /* Remove from global list */
7432 *cur_pp = cur->next;
7433 /* Free */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007434 if (!cur->max_len) {
7435 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007436 free(cur->varstr);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007437 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02007438 free(cur);
7439 }
7440
7441 G.var_nest_level--;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007442 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
Denys Vlasenko332e4112018-04-04 22:32:59 +02007443 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7444 bb_error_msg_and_die("BUG: nesting underflow");
7445}
7446
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007447static int run_function(const struct function *funcp, char **argv)
7448{
7449 int rc;
7450 save_arg_t sv;
7451 smallint sv_flg;
7452
7453 save_and_replace_G_args(&sv, argv);
7454
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007455 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007456 sv_flg = G_flag_return_in_progress;
7457 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007458
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007459 /* Make "local" variables properly shadow previous ones */
7460 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007461 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007462
7463 /* On MMU, funcp->body is always non-NULL */
7464# if !BB_MMU
7465 if (!funcp->body) {
7466 /* Function defined by -F */
7467 parse_and_run_string(funcp->body_as_string);
7468 rc = G.last_exitcode;
7469 } else
7470# endif
7471 {
7472 rc = run_list(funcp->body);
7473 }
7474
Denys Vlasenko332e4112018-04-04 22:32:59 +02007475 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007476 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007477
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007478 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007479
7480 restore_G_args(&sv, argv);
7481
7482 return rc;
7483}
7484#endif /* ENABLE_HUSH_FUNCTIONS */
7485
7486
7487#if BB_MMU
7488#define exec_builtin(to_free, x, argv) \
7489 exec_builtin(x, argv)
7490#else
7491#define exec_builtin(to_free, x, argv) \
7492 exec_builtin(to_free, argv)
7493#endif
7494static void exec_builtin(char ***to_free,
7495 const struct built_in_command *x,
7496 char **argv) NORETURN;
7497static void exec_builtin(char ***to_free,
7498 const struct built_in_command *x,
7499 char **argv)
7500{
7501#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007502 int rcode;
7503 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007504//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007505 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007506 fflush_all();
7507 _exit(rcode);
7508#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007509 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007510 /* On NOMMU, we must never block!
7511 * Example: { sleep 99 | read line; } & echo Ok
7512 */
7513 re_execute_shell(to_free,
7514 argv[0],
7515 G.global_argv[0],
7516 G.global_argv + 1,
7517 argv);
7518#endif
7519}
7520
7521
7522static void execvp_or_die(char **argv) NORETURN;
7523static void execvp_or_die(char **argv)
7524{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007525 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007526 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007527 /* Don't propagate SIG_IGN to the child */
7528 if (SPECIAL_JOBSTOP_SIGS != 0)
7529 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007530 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007531 e = 2;
7532 if (errno == EACCES) e = 126;
7533 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007534 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007535 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007536}
7537
7538#if ENABLE_HUSH_MODE_X
7539static void dump_cmd_in_x_mode(char **argv)
7540{
7541 if (G_x_mode && argv) {
7542 /* We want to output the line in one write op */
7543 char *buf, *p;
7544 int len;
7545 int n;
7546
7547 len = 3;
7548 n = 0;
7549 while (argv[n])
7550 len += strlen(argv[n++]) + 1;
7551 buf = xmalloc(len);
7552 buf[0] = '+';
7553 p = buf + 1;
7554 n = 0;
7555 while (argv[n])
7556 p += sprintf(p, " %s", argv[n++]);
7557 *p++ = '\n';
7558 *p = '\0';
7559 fputs(buf, stderr);
7560 free(buf);
7561 }
7562}
7563#else
7564# define dump_cmd_in_x_mode(argv) ((void)0)
7565#endif
7566
Denys Vlasenko57000292018-01-12 14:41:45 +01007567#if ENABLE_HUSH_COMMAND
7568static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7569{
7570 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007571
Denys Vlasenko57000292018-01-12 14:41:45 +01007572 if (!opt_vV)
7573 return;
7574
7575 to_free = NULL;
7576 if (!explanation) {
7577 char *path = getenv("PATH");
7578 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007579 if (!explanation)
7580 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007581 if (opt_vV != 'V')
7582 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7583 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007584 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007585 free(to_free);
7586 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007587 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007588}
7589#else
7590# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7591#endif
7592
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007593#if BB_MMU
7594#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7595 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7596#define pseudo_exec(nommu_save, command, argv_expanded) \
7597 pseudo_exec(command, argv_expanded)
7598#endif
7599
7600/* Called after [v]fork() in run_pipe, or from builtin_exec.
7601 * Never returns.
7602 * Don't exit() here. If you don't exec, use _exit instead.
7603 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007604 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007605 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007606static void pseudo_exec_argv(nommu_save_t *nommu_save,
7607 char **argv, int assignment_cnt,
7608 char **argv_expanded) NORETURN;
7609static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7610 char **argv, int assignment_cnt,
7611 char **argv_expanded)
7612{
Denys Vlasenko57000292018-01-12 14:41:45 +01007613 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007614 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007615 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007616 IF_HUSH_COMMAND(char opt_vV = 0;)
7617 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007618
7619 new_env = expand_assignments(argv, assignment_cnt);
7620 dump_cmd_in_x_mode(new_env);
7621
7622 if (!argv[assignment_cnt]) {
7623 /* Case when we are here: ... | var=val | ...
7624 * (note that we do not exit early, i.e., do not optimize out
7625 * expand_assignments(): think about ... | var=`sleep 1` | ...
7626 */
7627 free_strings(new_env);
7628 _exit(EXIT_SUCCESS);
7629 }
7630
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007631 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007632#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007633 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007634#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007635 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007636#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007637 set_vars_and_save_old(new_env);
7638 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007639
7640 if (argv_expanded) {
7641 argv = argv_expanded;
7642 } else {
7643 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7644#if !BB_MMU
7645 nommu_save->argv = argv;
7646#endif
7647 }
7648 dump_cmd_in_x_mode(argv);
7649
7650#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7651 if (strchr(argv[0], '/') != NULL)
7652 goto skip;
7653#endif
7654
Denys Vlasenko75481d32017-07-31 05:27:09 +02007655#if ENABLE_HUSH_FUNCTIONS
7656 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007657 funcp = find_function(argv[0]);
7658 if (funcp)
7659 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007660#endif
7661
Denys Vlasenko57000292018-01-12 14:41:45 +01007662#if ENABLE_HUSH_COMMAND
7663 /* "command BAR": run BAR without looking it up among functions
7664 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7665 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7666 */
7667 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7668 char *p;
7669
7670 argv++;
7671 p = *argv;
7672 if (p[0] != '-' || !p[1])
7673 continue; /* bash allows "command command command [-OPT] BAR" */
7674
7675 for (;;) {
7676 p++;
7677 switch (*p) {
7678 case '\0':
7679 argv++;
7680 p = *argv;
7681 if (p[0] != '-' || !p[1])
7682 goto after_opts;
7683 continue; /* next arg is also -opts, process it too */
7684 case 'v':
7685 case 'V':
7686 opt_vV = *p;
7687 continue;
7688 default:
7689 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7690 }
7691 }
7692 }
7693 after_opts:
7694# if ENABLE_HUSH_FUNCTIONS
7695 if (opt_vV && find_function(argv[0]))
7696 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7697# endif
7698#endif
7699
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007700 /* Check if the command matches any of the builtins.
7701 * Depending on context, this might be redundant. But it's
7702 * easier to waste a few CPU cycles than it is to figure out
7703 * if this is one of those cases.
7704 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007705 /* Why "BB_MMU ? :" difference in logic? -
7706 * On NOMMU, it is more expensive to re-execute shell
7707 * just in order to run echo or test builtin.
7708 * It's better to skip it here and run corresponding
7709 * non-builtin later. */
7710 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7711 if (x) {
7712 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7713 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007714 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007715
7716#if ENABLE_FEATURE_SH_STANDALONE
7717 /* Check if the command matches any busybox applets */
7718 {
7719 int a = find_applet_by_name(argv[0]);
7720 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007721 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007722# if BB_MMU /* see above why on NOMMU it is not allowed */
7723 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007724 /* Do not leak open fds from opened script files etc.
7725 * Testcase: interactive "ls -l /proc/self/fd"
7726 * should not show tty fd open.
7727 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007728 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007729//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007730//This casuses test failures in
7731//redir_children_should_not_see_saved_fd_2.tests
7732//redir_children_should_not_see_saved_fd_3.tests
7733//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007734 /* Without this, "rm -i FILE" can't be ^C'ed: */
7735 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007736 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007737 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738 }
7739# endif
7740 /* Re-exec ourselves */
7741 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007742 /* Don't propagate SIG_IGN to the child */
7743 if (SPECIAL_JOBSTOP_SIGS != 0)
7744 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007745 execv(bb_busybox_exec_path, argv);
7746 /* If they called chroot or otherwise made the binary no longer
7747 * executable, fall through */
7748 }
7749 }
7750#endif
7751
7752#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7753 skip:
7754#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007755 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007756 execvp_or_die(argv);
7757}
7758
7759/* Called after [v]fork() in run_pipe
7760 */
7761static void pseudo_exec(nommu_save_t *nommu_save,
7762 struct command *command,
7763 char **argv_expanded) NORETURN;
7764static void pseudo_exec(nommu_save_t *nommu_save,
7765 struct command *command,
7766 char **argv_expanded)
7767{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007768#if ENABLE_HUSH_FUNCTIONS
7769 if (command->cmd_type == CMD_FUNCDEF) {
7770 /* Ignore funcdefs in pipes:
7771 * true | f() { cmd }
7772 */
7773 _exit(0);
7774 }
7775#endif
7776
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007777 if (command->argv) {
7778 pseudo_exec_argv(nommu_save, command->argv,
7779 command->assignment_cnt, argv_expanded);
7780 }
7781
7782 if (command->group) {
7783 /* Cases when we are here:
7784 * ( list )
7785 * { list } &
7786 * ... | ( list ) | ...
7787 * ... | { list } | ...
7788 */
7789#if BB_MMU
7790 int rcode;
7791 debug_printf_exec("pseudo_exec: run_list\n");
7792 reset_traps_to_defaults();
7793 rcode = run_list(command->group);
7794 /* OK to leak memory by not calling free_pipe_list,
7795 * since this process is about to exit */
7796 _exit(rcode);
7797#else
7798 re_execute_shell(&nommu_save->argv_from_re_execing,
7799 command->group_as_string,
7800 G.global_argv[0],
7801 G.global_argv + 1,
7802 NULL);
7803#endif
7804 }
7805
7806 /* Case when we are here: ... | >file */
7807 debug_printf_exec("pseudo_exec'ed null command\n");
7808 _exit(EXIT_SUCCESS);
7809}
7810
7811#if ENABLE_HUSH_JOB
7812static const char *get_cmdtext(struct pipe *pi)
7813{
7814 char **argv;
7815 char *p;
7816 int len;
7817
7818 /* This is subtle. ->cmdtext is created only on first backgrounding.
7819 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7820 * On subsequent bg argv is trashed, but we won't use it */
7821 if (pi->cmdtext)
7822 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007823
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007824 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007825 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007826 pi->cmdtext = xzalloc(1);
7827 return pi->cmdtext;
7828 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007829 len = 0;
7830 do {
7831 len += strlen(*argv) + 1;
7832 } while (*++argv);
7833 p = xmalloc(len);
7834 pi->cmdtext = p;
7835 argv = pi->cmds[0].argv;
7836 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007837 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007838 *p++ = ' ';
7839 } while (*++argv);
7840 p[-1] = '\0';
7841 return pi->cmdtext;
7842}
7843
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007844static void remove_job_from_table(struct pipe *pi)
7845{
7846 struct pipe *prev_pipe;
7847
7848 if (pi == G.job_list) {
7849 G.job_list = pi->next;
7850 } else {
7851 prev_pipe = G.job_list;
7852 while (prev_pipe->next != pi)
7853 prev_pipe = prev_pipe->next;
7854 prev_pipe->next = pi->next;
7855 }
7856 G.last_jobid = 0;
7857 if (G.job_list)
7858 G.last_jobid = G.job_list->jobid;
7859}
7860
7861static void delete_finished_job(struct pipe *pi)
7862{
7863 remove_job_from_table(pi);
7864 free_pipe(pi);
7865}
7866
7867static void clean_up_last_dead_job(void)
7868{
7869 if (G.job_list && !G.job_list->alive_cmds)
7870 delete_finished_job(G.job_list);
7871}
7872
Denys Vlasenko16096292017-07-10 10:00:28 +02007873static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007874{
7875 struct pipe *job, **jobp;
7876 int i;
7877
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007878 clean_up_last_dead_job();
7879
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007880 /* Find the end of the list, and find next job ID to use */
7881 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007882 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007883 while ((job = *jobp) != NULL) {
7884 if (job->jobid > i)
7885 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007886 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007887 }
7888 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007889
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007890 /* Create a new job struct at the end */
7891 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007892 job->next = NULL;
7893 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7894 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7895 for (i = 0; i < pi->num_cmds; i++) {
7896 job->cmds[i].pid = pi->cmds[i].pid;
7897 /* all other fields are not used and stay zero */
7898 }
7899 job->cmdtext = xstrdup(get_cmdtext(pi));
7900
7901 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007902 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007903 G.last_jobid = job->jobid;
7904}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007905#endif /* JOB */
7906
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007907static int job_exited_or_stopped(struct pipe *pi)
7908{
7909 int rcode, i;
7910
7911 if (pi->alive_cmds != pi->stopped_cmds)
7912 return -1;
7913
7914 /* All processes in fg pipe have exited or stopped */
7915 rcode = 0;
7916 i = pi->num_cmds;
7917 while (--i >= 0) {
7918 rcode = pi->cmds[i].cmd_exitcode;
7919 /* usually last process gives overall exitstatus,
7920 * but with "set -o pipefail", last *failed* process does */
7921 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7922 break;
7923 }
7924 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7925 return rcode;
7926}
7927
Denys Vlasenko7e675362016-10-28 21:57:31 +02007928static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007929{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007930#if ENABLE_HUSH_JOB
7931 struct pipe *pi;
7932#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007933 int i, dead;
7934
7935 dead = WIFEXITED(status) || WIFSIGNALED(status);
7936
7937#if DEBUG_JOBS
7938 if (WIFSTOPPED(status))
7939 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7940 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7941 if (WIFSIGNALED(status))
7942 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7943 childpid, WTERMSIG(status), WEXITSTATUS(status));
7944 if (WIFEXITED(status))
7945 debug_printf_jobs("pid %d exited, exitcode %d\n",
7946 childpid, WEXITSTATUS(status));
7947#endif
7948 /* Were we asked to wait for a fg pipe? */
7949 if (fg_pipe) {
7950 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007951
Denys Vlasenko7e675362016-10-28 21:57:31 +02007952 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007953 int rcode;
7954
Denys Vlasenko7e675362016-10-28 21:57:31 +02007955 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7956 if (fg_pipe->cmds[i].pid != childpid)
7957 continue;
7958 if (dead) {
7959 int ex;
7960 fg_pipe->cmds[i].pid = 0;
7961 fg_pipe->alive_cmds--;
7962 ex = WEXITSTATUS(status);
7963 /* bash prints killer signal's name for *last*
7964 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7965 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7966 */
7967 if (WIFSIGNALED(status)) {
7968 int sig = WTERMSIG(status);
7969 if (i == fg_pipe->num_cmds-1)
7970 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7971 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7972 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7973 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7974 * Maybe we need to use sig | 128? */
7975 ex = sig + 128;
7976 }
7977 fg_pipe->cmds[i].cmd_exitcode = ex;
7978 } else {
7979 fg_pipe->stopped_cmds++;
7980 }
7981 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7982 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007983 rcode = job_exited_or_stopped(fg_pipe);
7984 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007985/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7986 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7987 * and "killall -STOP cat" */
7988 if (G_interactive_fd) {
7989#if ENABLE_HUSH_JOB
7990 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007991 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007992#endif
7993 return rcode;
7994 }
7995 if (fg_pipe->alive_cmds == 0)
7996 return rcode;
7997 }
7998 /* There are still running processes in the fg_pipe */
7999 return -1;
8000 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008001 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008002 }
8003
8004#if ENABLE_HUSH_JOB
8005 /* We were asked to wait for bg or orphaned children */
8006 /* No need to remember exitcode in this case */
8007 for (pi = G.job_list; pi; pi = pi->next) {
8008 for (i = 0; i < pi->num_cmds; i++) {
8009 if (pi->cmds[i].pid == childpid)
8010 goto found_pi_and_prognum;
8011 }
8012 }
8013 /* Happens when shell is used as init process (init=/bin/sh) */
8014 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8015 return -1; /* this wasn't a process from fg_pipe */
8016
8017 found_pi_and_prognum:
8018 if (dead) {
8019 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008020 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008021 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008022 rcode = 128 + WTERMSIG(status);
8023 pi->cmds[i].cmd_exitcode = rcode;
8024 if (G.last_bg_pid == pi->cmds[i].pid)
8025 G.last_bg_pid_exitcode = rcode;
8026 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008027 pi->alive_cmds--;
8028 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008029 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008030 printf(JOB_STATUS_FORMAT, pi->jobid,
8031 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008032 delete_finished_job(pi);
8033 } else {
8034/*
8035 * bash deletes finished jobs from job table only in interactive mode,
8036 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8037 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8038 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8039 * We only retain one "dead" job, if it's the single job on the list.
8040 * This covers most of real-world scenarios where this is useful.
8041 */
8042 if (pi != G.job_list)
8043 delete_finished_job(pi);
8044 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008045 }
8046 } else {
8047 /* child stopped */
8048 pi->stopped_cmds++;
8049 }
8050#endif
8051 return -1; /* this wasn't a process from fg_pipe */
8052}
8053
8054/* Check to see if any processes have exited -- if they have,
8055 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008056 *
8057 * If non-NULL fg_pipe: wait for its completion or stop.
8058 * Return its exitcode or zero if stopped.
8059 *
8060 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8061 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8062 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8063 * or 0 if no children changed status.
8064 *
8065 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8066 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8067 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008068 */
8069static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8070{
8071 int attributes;
8072 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008073 int rcode = 0;
8074
8075 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8076
8077 attributes = WUNTRACED;
8078 if (fg_pipe == NULL)
8079 attributes |= WNOHANG;
8080
8081 errno = 0;
8082#if ENABLE_HUSH_FAST
8083 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8084//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8085//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8086 /* There was neither fork nor SIGCHLD since last waitpid */
8087 /* Avoid doing waitpid syscall if possible */
8088 if (!G.we_have_children) {
8089 errno = ECHILD;
8090 return -1;
8091 }
8092 if (fg_pipe == NULL) { /* is WNOHANG set? */
8093 /* We have children, but they did not exit
8094 * or stop yet (we saw no SIGCHLD) */
8095 return 0;
8096 }
8097 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8098 }
8099#endif
8100
8101/* Do we do this right?
8102 * bash-3.00# sleep 20 | false
8103 * <ctrl-Z pressed>
8104 * [3]+ Stopped sleep 20 | false
8105 * bash-3.00# echo $?
8106 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8107 * [hush 1.14.0: yes we do it right]
8108 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008109 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008110 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008111#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008112 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008113 i = G.count_SIGCHLD;
8114#endif
8115 childpid = waitpid(-1, &status, attributes);
8116 if (childpid <= 0) {
8117 if (childpid && errno != ECHILD)
8118 bb_perror_msg("waitpid");
8119#if ENABLE_HUSH_FAST
8120 else { /* Until next SIGCHLD, waitpid's are useless */
8121 G.we_have_children = (childpid == 0);
8122 G.handled_SIGCHLD = i;
8123//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8124 }
8125#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008126 /* ECHILD (no children), or 0 (no change in children status) */
8127 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008128 break;
8129 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008130 rcode = process_wait_result(fg_pipe, childpid, status);
8131 if (rcode >= 0) {
8132 /* fg_pipe exited or stopped */
8133 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008134 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008135 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008136 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008137 rcode = WEXITSTATUS(status);
8138 if (WIFSIGNALED(status))
8139 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008140 if (WIFSTOPPED(status))
8141 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8142 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008143 rcode++;
8144 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008145 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008146 /* This wasn't one of our processes, or */
8147 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008148 } /* while (waitpid succeeds)... */
8149
8150 return rcode;
8151}
8152
8153#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008154static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008155{
8156 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008157 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008158 if (G_saved_tty_pgrp) {
8159 /* Job finished, move the shell to the foreground */
8160 p = getpgrp(); /* our process group id */
8161 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8162 tcsetpgrp(G_interactive_fd, p);
8163 }
8164 return rcode;
8165}
8166#endif
8167
8168/* Start all the jobs, but don't wait for anything to finish.
8169 * See checkjobs().
8170 *
8171 * Return code is normally -1, when the caller has to wait for children
8172 * to finish to determine the exit status of the pipe. If the pipe
8173 * is a simple builtin command, however, the action is done by the
8174 * time run_pipe returns, and the exit code is provided as the
8175 * return value.
8176 *
8177 * Returns -1 only if started some children. IOW: we have to
8178 * mask out retvals of builtins etc with 0xff!
8179 *
8180 * The only case when we do not need to [v]fork is when the pipe
8181 * is single, non-backgrounded, non-subshell command. Examples:
8182 * cmd ; ... { list } ; ...
8183 * cmd && ... { list } && ...
8184 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008185 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008186 * or (if SH_STANDALONE) an applet, and we can run the { list }
8187 * with run_list. If it isn't one of these, we fork and exec cmd.
8188 *
8189 * Cases when we must fork:
8190 * non-single: cmd | cmd
8191 * backgrounded: cmd & { list } &
8192 * subshell: ( list ) [&]
8193 */
8194#if !ENABLE_HUSH_MODE_X
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008195#define redirect_and_varexp_helper(old_vars_p, command, squirrel, argv_expanded) \
8196 redirect_and_varexp_helper(old_vars_p, command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008197#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008198static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008199 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008200 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008201 char **argv_expanded)
8202{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008203 /* Assignments occur before redirects. Try:
8204 * a=`sleep 1` sleep 2 3>/qwe/rty
8205 */
8206
8207 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8208 dump_cmd_in_x_mode(new_env);
8209 dump_cmd_in_x_mode(argv_expanded);
8210 /* this takes ownership of new_env[i] elements, and frees new_env: */
8211 set_vars_and_save_old(new_env);
8212
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008213 /* setup_redirects acts on file descriptors, not FILEs.
8214 * This is perfect for work that comes after exec().
8215 * Is it really safe for inline use? Experimentally,
8216 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008217 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008218}
8219static NOINLINE int run_pipe(struct pipe *pi)
8220{
8221 static const char *const null_ptr = NULL;
8222
8223 int cmd_no;
8224 int next_infd;
8225 struct command *command;
8226 char **argv_expanded;
8227 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008228 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008229 int rcode;
8230
8231 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8232 debug_enter();
8233
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008234 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8235 * Result should be 3 lines: q w e, qwe, q w e
8236 */
8237 G.ifs = get_local_var_value("IFS");
8238 if (!G.ifs)
8239 G.ifs = defifs;
8240
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008241 IF_HUSH_JOB(pi->pgrp = -1;)
8242 pi->stopped_cmds = 0;
8243 command = &pi->cmds[0];
8244 argv_expanded = NULL;
8245
8246 if (pi->num_cmds != 1
8247 || pi->followup == PIPE_BG
8248 || command->cmd_type == CMD_SUBSHELL
8249 ) {
8250 goto must_fork;
8251 }
8252
8253 pi->alive_cmds = 1;
8254
8255 debug_printf_exec(": group:%p argv:'%s'\n",
8256 command->group, command->argv ? command->argv[0] : "NONE");
8257
8258 if (command->group) {
8259#if ENABLE_HUSH_FUNCTIONS
8260 if (command->cmd_type == CMD_FUNCDEF) {
8261 /* "executing" func () { list } */
8262 struct function *funcp;
8263
8264 funcp = new_function(command->argv[0]);
8265 /* funcp->name is already set to argv[0] */
8266 funcp->body = command->group;
8267# if !BB_MMU
8268 funcp->body_as_string = command->group_as_string;
8269 command->group_as_string = NULL;
8270# endif
8271 command->group = NULL;
8272 command->argv[0] = NULL;
8273 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8274 funcp->parent_cmd = command;
8275 command->child_func = funcp;
8276
8277 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8278 debug_leave();
8279 return EXIT_SUCCESS;
8280 }
8281#endif
8282 /* { list } */
8283 debug_printf("non-subshell group\n");
8284 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008285 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008286 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008287//FIXME: we need to pass squirrel down into run_list()
8288//for SH_STANDALONE case, or else this construct:
8289// { find /proc/self/fd; true; } >FILE; cmd2
8290//has no way of closing saved fd#1 for "find",
8291//and in SH_STANDALONE mode, "find" is not execed,
8292//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008293 rcode = run_list(command->group) & 0xff;
8294 }
8295 restore_redirects(squirrel);
8296 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8297 debug_leave();
8298 debug_printf_exec("run_pipe: return %d\n", rcode);
8299 return rcode;
8300 }
8301
8302 argv = command->argv ? command->argv : (char **) &null_ptr;
8303 {
8304 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008305 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8306 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008307 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008308 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008309
Denys Vlasenko5807e182018-02-08 19:19:04 +01008310#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008311 if (G.lineno_var)
8312 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8313#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008314
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008315 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008316 /* Assignments, but no command.
8317 * Ensure redirects take effect (that is, create files).
8318 * Try "a=t >file"
8319 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008320 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008321 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008322 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008323 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008324 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008325
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008326 /* Set shell variables */
8327 if (G_x_mode)
8328 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008329 i = 0;
8330 while (i < command->assignment_cnt) {
8331 char *p = expand_string_to_string(argv[i], /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008332 if (G_x_mode)
8333 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008334 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008335 if (set_local_var(p, /*flag:*/ 0)) {
8336 /* assignment to readonly var / putenv error? */
8337 rcode = 1;
8338 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008339 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008340 }
8341 if (G_x_mode)
8342 bb_putchar_stderr('\n');
8343 /* Redirect error sets $? to 1. Otherwise,
8344 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008345 * Else, clear $?:
8346 * false; q=`exit 2`; echo $? - should print 2
8347 * false; x=1; echo $? - should print 0
8348 * Because of the 2nd case, we can't just use G.last_exitcode.
8349 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008350 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008351 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008352 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8353 debug_leave();
8354 debug_printf_exec("run_pipe: return %d\n", rcode);
8355 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356 }
8357
8358 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008359#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008360 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008361 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008362 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008363#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008364 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008365
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008366 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008367 if (!argv_expanded[0]) {
8368 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008369 /* `false` still has to set exitcode 1 */
8370 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008371 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008372 }
8373
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008374 old_vars = NULL;
8375 sv_shadowed = G.shadowed_vars_pp;
8376
Denys Vlasenko75481d32017-07-31 05:27:09 +02008377 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008378 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8379 IF_HUSH_FUNCTIONS(x = NULL;)
8380 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008381 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008382 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008383 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8384 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008385 /*
8386 * Variable assignments are executed, but then "forgotten":
8387 * a=`sleep 1;echo A` exec 3>&-; echo $a
8388 * sleeps, but prints nothing.
8389 */
8390 enter_var_nest_level();
8391 G.shadowed_vars_pp = &old_vars;
8392 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8393 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008394 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008395
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008396 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008397 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008398
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008399 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008400 * a=b true; env | grep ^a=
8401 */
8402 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008403 /* Collect all variables "shadowed" by helper
8404 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8405 * into old_vars list:
8406 */
8407 G.shadowed_vars_pp = &old_vars;
8408 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008409 if (rcode == 0) {
8410 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008411 /* Do not collect *to old_vars list* vars shadowed
8412 * by e.g. "local VAR" builtin (collect them
8413 * in the previously nested list instead):
8414 * don't want them to be restored immediately
8415 * after "local" completes.
8416 */
8417 G.shadowed_vars_pp = sv_shadowed;
8418
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008419 debug_printf_exec(": builtin '%s' '%s'...\n",
8420 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008421 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008422 rcode = x->b_function(argv_expanded) & 0xff;
8423 fflush_all();
8424 }
8425#if ENABLE_HUSH_FUNCTIONS
8426 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008427 debug_printf_exec(": function '%s' '%s'...\n",
8428 funcp->name, argv_expanded[1]);
8429 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008430 /*
8431 * But do collect *to old_vars list* vars shadowed
8432 * within function execution. To that end, restore
8433 * this pointer _after_ function run:
8434 */
8435 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008436 }
8437#endif
8438 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008439 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008440 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008441 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008442 if (n < 0 || !APPLET_IS_NOFORK(n))
8443 goto must_fork;
8444
8445 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008446 /* Collect all variables "shadowed" by helper into old_vars list */
8447 G.shadowed_vars_pp = &old_vars;
8448 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8449 G.shadowed_vars_pp = sv_shadowed;
8450
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008451 if (rcode == 0) {
8452 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8453 argv_expanded[0], argv_expanded[1]);
8454 /*
8455 * Note: signals (^C) can't interrupt here.
8456 * We remember them and they will be acted upon
8457 * after applet returns.
8458 * This makes applets which can run for a long time
8459 * and/or wait for user input ineligible for NOFORK:
8460 * for example, "yes" or "rm" (rm -i waits for input).
8461 */
8462 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008463 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008464 } else
8465 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008466
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008467 restore_redirects(squirrel);
8468 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008469 leave_var_nest_level();
8470 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008471
8472 /*
8473 * Try "usleep 99999999" + ^C + "echo $?"
8474 * with FEATURE_SH_NOFORK=y.
8475 */
8476 if (!funcp) {
8477 /* It was builtin or nofork.
8478 * if this would be a real fork/execed program,
8479 * it should have died if a fatal sig was received.
8480 * But OTOH, there was no separate process,
8481 * the sig was sent to _shell_, not to non-existing
8482 * child.
8483 * Let's just handle ^C only, this one is obvious:
8484 * we aren't ok with exitcode 0 when ^C was pressed
8485 * during builtin/nofork.
8486 */
8487 if (sigismember(&G.pending_set, SIGINT))
8488 rcode = 128 + SIGINT;
8489 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008490 free(argv_expanded);
8491 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8492 debug_leave();
8493 debug_printf_exec("run_pipe return %d\n", rcode);
8494 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008495 }
8496
8497 must_fork:
8498 /* NB: argv_expanded may already be created, and that
8499 * might include `cmd` runs! Do not rerun it! We *must*
8500 * use argv_expanded if it's non-NULL */
8501
8502 /* Going to fork a child per each pipe member */
8503 pi->alive_cmds = 0;
8504 next_infd = 0;
8505
8506 cmd_no = 0;
8507 while (cmd_no < pi->num_cmds) {
8508 struct fd_pair pipefds;
8509#if !BB_MMU
8510 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008511 nommu_save.old_vars = NULL;
8512 nommu_save.argv = NULL;
8513 nommu_save.argv_from_re_execing = NULL;
8514#endif
8515 command = &pi->cmds[cmd_no];
8516 cmd_no++;
8517 if (command->argv) {
8518 debug_printf_exec(": pipe member '%s' '%s'...\n",
8519 command->argv[0], command->argv[1]);
8520 } else {
8521 debug_printf_exec(": pipe member with no argv\n");
8522 }
8523
8524 /* pipes are inserted between pairs of commands */
8525 pipefds.rd = 0;
8526 pipefds.wr = 1;
8527 if (cmd_no < pi->num_cmds)
8528 xpiped_pair(pipefds);
8529
Denys Vlasenko5807e182018-02-08 19:19:04 +01008530#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008531 if (G.lineno_var)
8532 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8533#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008534
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008535 command->pid = BB_MMU ? fork() : vfork();
8536 if (!command->pid) { /* child */
8537#if ENABLE_HUSH_JOB
8538 disable_restore_tty_pgrp_on_exit();
8539 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8540
8541 /* Every child adds itself to new process group
8542 * with pgid == pid_of_first_child_in_pipe */
8543 if (G.run_list_level == 1 && G_interactive_fd) {
8544 pid_t pgrp;
8545 pgrp = pi->pgrp;
8546 if (pgrp < 0) /* true for 1st process only */
8547 pgrp = getpid();
8548 if (setpgid(0, pgrp) == 0
8549 && pi->followup != PIPE_BG
8550 && G_saved_tty_pgrp /* we have ctty */
8551 ) {
8552 /* We do it in *every* child, not just first,
8553 * to avoid races */
8554 tcsetpgrp(G_interactive_fd, pgrp);
8555 }
8556 }
8557#endif
8558 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8559 /* 1st cmd in backgrounded pipe
8560 * should have its stdin /dev/null'ed */
8561 close(0);
8562 if (open(bb_dev_null, O_RDONLY))
8563 xopen("/", O_RDONLY);
8564 } else {
8565 xmove_fd(next_infd, 0);
8566 }
8567 xmove_fd(pipefds.wr, 1);
8568 if (pipefds.rd > 1)
8569 close(pipefds.rd);
8570 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008571 * and the pipe fd (fd#1) is available for dup'ing:
8572 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8573 * of cmd1 goes into pipe.
8574 */
8575 if (setup_redirects(command, NULL)) {
8576 /* Happens when redir file can't be opened:
8577 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8578 * FOO
8579 * hush: can't open '/qwe/rty': No such file or directory
8580 * BAZ
8581 * (echo BAR is not executed, it hits _exit(1) below)
8582 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008583 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008584 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008585
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008586 /* Stores to nommu_save list of env vars putenv'ed
8587 * (NOMMU, on MMU we don't need that) */
8588 /* cast away volatility... */
8589 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8590 /* pseudo_exec() does not return */
8591 }
8592
8593 /* parent or error */
8594#if ENABLE_HUSH_FAST
8595 G.count_SIGCHLD++;
8596//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8597#endif
8598 enable_restore_tty_pgrp_on_exit();
8599#if !BB_MMU
8600 /* Clean up after vforked child */
8601 free(nommu_save.argv);
8602 free(nommu_save.argv_from_re_execing);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008603 add_vars(nommu_save.old_vars);
8604#endif
8605 free(argv_expanded);
8606 argv_expanded = NULL;
8607 if (command->pid < 0) { /* [v]fork failed */
8608 /* Clearly indicate, was it fork or vfork */
8609 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8610 } else {
8611 pi->alive_cmds++;
8612#if ENABLE_HUSH_JOB
8613 /* Second and next children need to know pid of first one */
8614 if (pi->pgrp < 0)
8615 pi->pgrp = command->pid;
8616#endif
8617 }
8618
8619 if (cmd_no > 1)
8620 close(next_infd);
8621 if (cmd_no < pi->num_cmds)
8622 close(pipefds.wr);
8623 /* Pass read (output) pipe end to next iteration */
8624 next_infd = pipefds.rd;
8625 }
8626
8627 if (!pi->alive_cmds) {
8628 debug_leave();
8629 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8630 return 1;
8631 }
8632
8633 debug_leave();
8634 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8635 return -1;
8636}
8637
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008638/* NB: called by pseudo_exec, and therefore must not modify any
8639 * global data until exec/_exit (we can be a child after vfork!) */
8640static int run_list(struct pipe *pi)
8641{
8642#if ENABLE_HUSH_CASE
8643 char *case_word = NULL;
8644#endif
8645#if ENABLE_HUSH_LOOPS
8646 struct pipe *loop_top = NULL;
8647 char **for_lcur = NULL;
8648 char **for_list = NULL;
8649#endif
8650 smallint last_followup;
8651 smalluint rcode;
8652#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8653 smalluint cond_code = 0;
8654#else
8655 enum { cond_code = 0 };
8656#endif
8657#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008658 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008659 smallint last_rword; /* ditto */
8660#endif
8661
8662 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8663 debug_enter();
8664
8665#if ENABLE_HUSH_LOOPS
8666 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008667 {
8668 struct pipe *cpipe;
8669 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8670 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8671 continue;
8672 /* current word is FOR or IN (BOLD in comments below) */
8673 if (cpipe->next == NULL) {
8674 syntax_error("malformed for");
8675 debug_leave();
8676 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8677 return 1;
8678 }
8679 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8680 if (cpipe->next->res_word == RES_DO)
8681 continue;
8682 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8683 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8684 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8685 ) {
8686 syntax_error("malformed for");
8687 debug_leave();
8688 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8689 return 1;
8690 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008691 }
8692 }
8693#endif
8694
8695 /* Past this point, all code paths should jump to ret: label
8696 * in order to return, no direct "return" statements please.
8697 * This helps to ensure that no memory is leaked. */
8698
8699#if ENABLE_HUSH_JOB
8700 G.run_list_level++;
8701#endif
8702
8703#if HAS_KEYWORDS
8704 rword = RES_NONE;
8705 last_rword = RES_XXXX;
8706#endif
8707 last_followup = PIPE_SEQ;
8708 rcode = G.last_exitcode;
8709
8710 /* Go through list of pipes, (maybe) executing them. */
8711 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008712 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008713 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008714
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008715 if (G.flag_SIGINT)
8716 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008717 if (G_flag_return_in_progress == 1)
8718 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008719
8720 IF_HAS_KEYWORDS(rword = pi->res_word;)
8721 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8722 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008723
8724 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008725 if (
8726#if ENABLE_HUSH_IF
8727 rword == RES_IF || rword == RES_ELIF ||
8728#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008729 pi->followup != PIPE_SEQ
8730 ) {
8731 G.errexit_depth++;
8732 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008733#if ENABLE_HUSH_LOOPS
8734 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8735 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8736 ) {
8737 /* start of a loop: remember where loop starts */
8738 loop_top = pi;
8739 G.depth_of_loop++;
8740 }
8741#endif
8742 /* Still in the same "if...", "then..." or "do..." branch? */
8743 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8744 if ((rcode == 0 && last_followup == PIPE_OR)
8745 || (rcode != 0 && last_followup == PIPE_AND)
8746 ) {
8747 /* It is "<true> || CMD" or "<false> && CMD"
8748 * and we should not execute CMD */
8749 debug_printf_exec("skipped cmd because of || or &&\n");
8750 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008751 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008752 }
8753 }
8754 last_followup = pi->followup;
8755 IF_HAS_KEYWORDS(last_rword = rword;)
8756#if ENABLE_HUSH_IF
8757 if (cond_code) {
8758 if (rword == RES_THEN) {
8759 /* if false; then ... fi has exitcode 0! */
8760 G.last_exitcode = rcode = EXIT_SUCCESS;
8761 /* "if <false> THEN cmd": skip cmd */
8762 continue;
8763 }
8764 } else {
8765 if (rword == RES_ELSE || rword == RES_ELIF) {
8766 /* "if <true> then ... ELSE/ELIF cmd":
8767 * skip cmd and all following ones */
8768 break;
8769 }
8770 }
8771#endif
8772#if ENABLE_HUSH_LOOPS
8773 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8774 if (!for_lcur) {
8775 /* first loop through for */
8776
8777 static const char encoded_dollar_at[] ALIGN1 = {
8778 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8779 }; /* encoded representation of "$@" */
8780 static const char *const encoded_dollar_at_argv[] = {
8781 encoded_dollar_at, NULL
8782 }; /* argv list with one element: "$@" */
8783 char **vals;
8784
8785 vals = (char**)encoded_dollar_at_argv;
8786 if (pi->next->res_word == RES_IN) {
8787 /* if no variable values after "in" we skip "for" */
8788 if (!pi->next->cmds[0].argv) {
8789 G.last_exitcode = rcode = EXIT_SUCCESS;
8790 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8791 break;
8792 }
8793 vals = pi->next->cmds[0].argv;
8794 } /* else: "for var; do..." -> assume "$@" list */
8795 /* create list of variable values */
8796 debug_print_strings("for_list made from", vals);
8797 for_list = expand_strvec_to_strvec(vals);
8798 for_lcur = for_list;
8799 debug_print_strings("for_list", for_list);
8800 }
8801 if (!*for_lcur) {
8802 /* "for" loop is over, clean up */
8803 free(for_list);
8804 for_list = NULL;
8805 for_lcur = NULL;
8806 break;
8807 }
8808 /* Insert next value from for_lcur */
8809 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008810 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008811 continue;
8812 }
8813 if (rword == RES_IN) {
8814 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8815 }
8816 if (rword == RES_DONE) {
8817 continue; /* "done" has no cmds too */
8818 }
8819#endif
8820#if ENABLE_HUSH_CASE
8821 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008822 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02008823 case_word = expand_string_to_string(pi->cmds->argv[0], 1);
8824 debug_printf_exec("CASE word1:'%s'\n", case_word);
8825 //unbackslash(case_word);
8826 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008827 continue;
8828 }
8829 if (rword == RES_MATCH) {
8830 char **argv;
8831
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008832 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008833 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8834 break;
8835 /* all prev words didn't match, does this one match? */
8836 argv = pi->cmds->argv;
8837 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008838 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008839 /* TODO: which FNM_xxx flags to use? */
8840 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008841 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008842 free(pattern);
8843 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008844 free(case_word);
8845 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008846 break;
8847 }
8848 argv++;
8849 }
8850 continue;
8851 }
8852 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008853 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008854 if (cond_code != 0)
8855 continue; /* not matched yet, skip this pipe */
8856 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008857 if (rword == RES_ESAC) {
8858 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8859 if (case_word) {
8860 /* "case" did not match anything: still set $? (to 0) */
8861 G.last_exitcode = rcode = EXIT_SUCCESS;
8862 }
8863 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008864#endif
8865 /* Just pressing <enter> in shell should check for jobs.
8866 * OTOH, in non-interactive shell this is useless
8867 * and only leads to extra job checks */
8868 if (pi->num_cmds == 0) {
8869 if (G_interactive_fd)
8870 goto check_jobs_and_continue;
8871 continue;
8872 }
8873
8874 /* After analyzing all keywords and conditions, we decided
8875 * to execute this pipe. NB: have to do checkjobs(NULL)
8876 * after run_pipe to collect any background children,
8877 * even if list execution is to be stopped. */
8878 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008879#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008880 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008881#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008882 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8883 if (r != -1) {
8884 /* We ran a builtin, function, or group.
8885 * rcode is already known
8886 * and we don't need to wait for anything. */
8887 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8888 G.last_exitcode = rcode;
8889 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008890#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008891 /* Was it "break" or "continue"? */
8892 if (G.flag_break_continue) {
8893 smallint fbc = G.flag_break_continue;
8894 /* We might fall into outer *loop*,
8895 * don't want to break it too */
8896 if (loop_top) {
8897 G.depth_break_continue--;
8898 if (G.depth_break_continue == 0)
8899 G.flag_break_continue = 0;
8900 /* else: e.g. "continue 2" should *break* once, *then* continue */
8901 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8902 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008903 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008904 break;
8905 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008906 /* "continue": simulate end of loop */
8907 rword = RES_DONE;
8908 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008909 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008910#endif
8911 if (G_flag_return_in_progress == 1) {
8912 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8913 break;
8914 }
8915 } else if (pi->followup == PIPE_BG) {
8916 /* What does bash do with attempts to background builtins? */
8917 /* even bash 3.2 doesn't do that well with nested bg:
8918 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8919 * I'm NOT treating inner &'s as jobs */
8920#if ENABLE_HUSH_JOB
8921 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008922 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008923#endif
8924 /* Last command's pid goes to $! */
8925 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008926 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008927 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008928/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008929 rcode = EXIT_SUCCESS;
8930 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008931 } else {
8932#if ENABLE_HUSH_JOB
8933 if (G.run_list_level == 1 && G_interactive_fd) {
8934 /* Waits for completion, then fg's main shell */
8935 rcode = checkjobs_and_fg_shell(pi);
8936 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008937 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008938 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008939#endif
8940 /* This one just waits for completion */
8941 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8942 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8943 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008944 G.last_exitcode = rcode;
8945 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008946 }
8947
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008948 /* Handle "set -e" */
8949 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8950 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8951 if (G.errexit_depth == 0)
8952 hush_exit(rcode);
8953 }
8954 G.errexit_depth = sv_errexit_depth;
8955
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008956 /* Analyze how result affects subsequent commands */
8957#if ENABLE_HUSH_IF
8958 if (rword == RES_IF || rword == RES_ELIF)
8959 cond_code = rcode;
8960#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008961 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008962 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008963 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008964#if ENABLE_HUSH_LOOPS
8965 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008966 if (pi->next
8967 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008968 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008969 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008970 if (rword == RES_WHILE) {
8971 if (rcode) {
8972 /* "while false; do...done" - exitcode 0 */
8973 G.last_exitcode = rcode = EXIT_SUCCESS;
8974 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008975 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008976 }
8977 }
8978 if (rword == RES_UNTIL) {
8979 if (!rcode) {
8980 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008981 break;
8982 }
8983 }
8984 }
8985#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008986 } /* for (pi) */
8987
8988#if ENABLE_HUSH_JOB
8989 G.run_list_level--;
8990#endif
8991#if ENABLE_HUSH_LOOPS
8992 if (loop_top)
8993 G.depth_of_loop--;
8994 free(for_list);
8995#endif
8996#if ENABLE_HUSH_CASE
8997 free(case_word);
8998#endif
8999 debug_leave();
9000 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9001 return rcode;
9002}
9003
9004/* Select which version we will use */
9005static int run_and_free_list(struct pipe *pi)
9006{
9007 int rcode = 0;
9008 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009009 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009010 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9011 rcode = run_list(pi);
9012 }
9013 /* free_pipe_list has the side effect of clearing memory.
9014 * In the long run that function can be merged with run_list,
9015 * but doing that now would hobble the debugging effort. */
9016 free_pipe_list(pi);
9017 debug_printf_exec("run_and_free_list return %d\n", rcode);
9018 return rcode;
9019}
9020
9021
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009022static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009023{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009024 sighandler_t old_handler;
9025 unsigned sig = 0;
9026 while ((mask >>= 1) != 0) {
9027 sig++;
9028 if (!(mask & 1))
9029 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009030 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009031 /* POSIX allows shell to re-enable SIGCHLD
9032 * even if it was SIG_IGN on entry.
9033 * Therefore we skip IGN check for it:
9034 */
9035 if (sig == SIGCHLD)
9036 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009037 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9038 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9039 */
9040 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009041 if (old_handler == SIG_IGN) {
9042 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009043 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009044#if ENABLE_HUSH_TRAP
9045 if (!G_traps)
9046 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9047 free(G_traps[sig]);
9048 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9049#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009050 }
9051 }
9052}
9053
9054/* Called a few times only (or even once if "sh -c") */
9055static void install_special_sighandlers(void)
9056{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009057 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009058
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009059 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009060 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009061 if (G_interactive_fd) {
9062 mask |= SPECIAL_INTERACTIVE_SIGS;
9063 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009064 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009065 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009066 /* Careful, do not re-install handlers we already installed */
9067 if (G.special_sig_mask != mask) {
9068 unsigned diff = mask & ~G.special_sig_mask;
9069 G.special_sig_mask = mask;
9070 install_sighandlers(diff);
9071 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009072}
9073
9074#if ENABLE_HUSH_JOB
9075/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009076/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009077static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009078{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009079 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009080
9081 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009082 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009083 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9084 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009085 + (1 << SIGBUS ) * HUSH_DEBUG
9086 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009087 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009088 + (1 << SIGABRT)
9089 /* bash 3.2 seems to handle these just like 'fatal' ones */
9090 + (1 << SIGPIPE)
9091 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009092 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009093 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009094 * we never want to restore pgrp on exit, and this fn is not called
9095 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009096 /*+ (1 << SIGHUP )*/
9097 /*+ (1 << SIGTERM)*/
9098 /*+ (1 << SIGINT )*/
9099 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009100 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009101
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009102 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009103}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009104#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009105
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009106static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009107{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009108 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009109 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009110 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009111 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009112 break;
9113 case 'x':
9114 IF_HUSH_MODE_X(G_x_mode = state;)
9115 break;
9116 case 'o':
9117 if (!o_opt) {
9118 /* "set -+o" without parameter.
9119 * in bash, set -o produces this output:
9120 * pipefail off
9121 * and set +o:
9122 * set +o pipefail
9123 * We always use the second form.
9124 */
9125 const char *p = o_opt_strings;
9126 idx = 0;
9127 while (*p) {
9128 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9129 idx++;
9130 p += strlen(p) + 1;
9131 }
9132 break;
9133 }
9134 idx = index_in_strings(o_opt_strings, o_opt);
9135 if (idx >= 0) {
9136 G.o_opt[idx] = state;
9137 break;
9138 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009139 case 'e':
9140 G.o_opt[OPT_O_ERREXIT] = state;
9141 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009142 default:
9143 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009144 }
9145 return EXIT_SUCCESS;
9146}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009147
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009148int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009149int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009150{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009151 enum {
9152 OPT_login = (1 << 0),
9153 };
9154 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00009155 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009156 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009157 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009158 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009159 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009160
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009161 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009162 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009163 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009164
Denys Vlasenko10c01312011-05-11 11:49:21 +02009165#if ENABLE_HUSH_FAST
9166 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9167#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009168#if !BB_MMU
9169 G.argv0_for_re_execing = argv[0];
9170#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009171
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009172 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009173 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9174 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009175 shell_ver = xzalloc(sizeof(*shell_ver));
9176 shell_ver->flg_export = 1;
9177 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009178 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009179 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009180 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009181
Denys Vlasenko605067b2010-09-06 12:10:51 +02009182 /* Create shell local variables from the values
9183 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009184 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009185 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009186 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009187 if (e) while (*e) {
9188 char *value = strchr(*e, '=');
9189 if (value) { /* paranoia */
9190 cur_var->next = xzalloc(sizeof(*cur_var));
9191 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009192 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009193 cur_var->max_len = strlen(*e);
9194 cur_var->flg_export = 1;
9195 }
9196 e++;
9197 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009198 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009199 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9200 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009201
9202 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009203 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009204
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009205#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009206 /* Set (but not export) HOSTNAME unless already set */
9207 if (!get_local_var_value("HOSTNAME")) {
9208 struct utsname uts;
9209 uname(&uts);
9210 set_local_var_from_halves("HOSTNAME", uts.nodename);
9211 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009212 /* bash also exports SHLVL and _,
9213 * and sets (but doesn't export) the following variables:
9214 * BASH=/bin/bash
9215 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9216 * BASH_VERSION='3.2.0(1)-release'
9217 * HOSTTYPE=i386
9218 * MACHTYPE=i386-pc-linux-gnu
9219 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009220 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009221 * EUID=<NNNNN>
9222 * UID=<NNNNN>
9223 * GROUPS=()
9224 * LINES=<NNN>
9225 * COLUMNS=<NNN>
9226 * BASH_ARGC=()
9227 * BASH_ARGV=()
9228 * BASH_LINENO=()
9229 * BASH_SOURCE=()
9230 * DIRSTACK=()
9231 * PIPESTATUS=([0]="0")
9232 * HISTFILE=/<xxx>/.bash_history
9233 * HISTFILESIZE=500
9234 * HISTSIZE=500
9235 * MAILCHECK=60
9236 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9237 * SHELL=/bin/bash
9238 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9239 * TERM=dumb
9240 * OPTERR=1
9241 * OPTIND=1
9242 * IFS=$' \t\n'
9243 * PS1='\s-\v\$ '
9244 * PS2='> '
9245 * PS4='+ '
9246 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009247#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009248
Denys Vlasenko5807e182018-02-08 19:19:04 +01009249#if ENABLE_HUSH_LINENO_VAR
9250 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009251 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9252 set_local_var(p, /*flags*/ 0);
9253 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9254 }
9255#endif
9256
Denis Vlasenko38f63192007-01-22 09:03:07 +00009257#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009258 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009259#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009260
Eric Andersen94ac2442001-05-22 19:05:18 +00009261 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009262 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009263
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009264 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009265
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009266 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009267 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009268 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009269 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009270 * in order to intercept (more) signals.
9271 */
9272
9273 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009274 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009275 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009276 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009277 while (1) {
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009278 opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009279#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009280 "<:$:R:V:"
9281# if ENABLE_HUSH_FUNCTIONS
9282 "F:"
9283# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009284#endif
9285 );
9286 if (opt <= 0)
9287 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009288 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009289 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009290 /* Possibilities:
9291 * sh ... -c 'script'
9292 * sh ... -c 'script' ARG0 [ARG1...]
9293 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009294 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009295 * "" needs to be replaced with NULL
9296 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009297 * Note: the form without ARG0 never happens:
9298 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009299 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009300 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009301 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009302 G.root_ppid = getppid();
9303 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009304 G.global_argv = argv + optind;
9305 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009306 if (builtin_argc) {
9307 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9308 const struct built_in_command *x;
9309
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009310 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009311 x = find_builtin(optarg);
9312 if (x) { /* paranoia */
9313 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9314 G.global_argv += builtin_argc;
9315 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009316 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009317 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009318 }
9319 goto final_return;
9320 }
9321 if (!G.global_argv[0]) {
9322 /* -c 'script' (no params): prevent empty $0 */
9323 G.global_argv--; /* points to argv[i] of 'script' */
9324 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009325 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009326 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009327 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009328 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009329 goto final_return;
9330 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009331 /* Well, we cannot just declare interactiveness,
9332 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009333 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009334 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009335 case 's':
9336 /* "-s" means "read from stdin", but this is how we always
9337 * operate, so simply do nothing here. */
9338 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009339 case 'l':
9340 flags |= OPT_login;
9341 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009342#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009343 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009344 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009345 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009346 case '$': {
9347 unsigned long long empty_trap_mask;
9348
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009349 G.root_pid = bb_strtou(optarg, &optarg, 16);
9350 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009351 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9352 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009353 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9354 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009355 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009356 optarg++;
9357 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009358 optarg++;
9359 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9360 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009361 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009362 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009363# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009364 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009365 for (sig = 1; sig < NSIG; sig++) {
9366 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009367 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009368 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009369 }
9370 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009371# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009372 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009373# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009374 optarg++;
9375 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009376# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009377 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009378 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009379 case 'R':
9380 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009381 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009382 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009383# if ENABLE_HUSH_FUNCTIONS
9384 case 'F': {
9385 struct function *funcp = new_function(optarg);
9386 /* funcp->name is already set to optarg */
9387 /* funcp->body is set to NULL. It's a special case. */
9388 funcp->body_as_string = argv[optind];
9389 optind++;
9390 break;
9391 }
9392# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009393#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009394 case 'n':
9395 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009396 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009397 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009398 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009399 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009400#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009401 fprintf(stderr, "Usage: sh [FILE]...\n"
9402 " or: sh -c command [args]...\n\n");
9403 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009404#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009405 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009406#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009407 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009408 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009409
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009410 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9411 G.global_argc = argc - (optind - 1);
9412 G.global_argv = argv + (optind - 1);
9413 G.global_argv[0] = argv[0];
9414
Denys Vlasenkodea47882009-10-09 15:40:49 +02009415 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009416 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009417 G.root_ppid = getppid();
9418 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009419
9420 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009421 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009422 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009423 debug_printf("sourcing /etc/profile\n");
9424 input = fopen_for_read("/etc/profile");
9425 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009426 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009427 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009428 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009429 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009430 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009431 /* bash: after sourcing /etc/profile,
9432 * tries to source (in the given order):
9433 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009434 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009435 * bash also sources ~/.bash_logout on exit.
9436 * If called as sh, skips .bash_XXX files.
9437 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009438 }
9439
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009440 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009441 FILE *input;
9442 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009443 * "bash <script>" (which is never interactive (unless -i?))
9444 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009445 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009446 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009447 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009448 G.global_argc--;
9449 G.global_argv++;
9450 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009451 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009452 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009453 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009454 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009455 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009456 parse_and_run_file(input);
9457#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009458 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009459#endif
9460 goto final_return;
9461 }
9462
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009463 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009464 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009465 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009466
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009467 /* A shell is interactive if the '-i' flag was given,
9468 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009469 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009470 * no arguments remaining or the -s flag given
9471 * standard input is a terminal
9472 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009473 * Refer to Posix.2, the description of the 'sh' utility.
9474 */
9475#if ENABLE_HUSH_JOB
9476 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009477 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9478 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9479 if (G_saved_tty_pgrp < 0)
9480 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009481
9482 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009483 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009484 if (G_interactive_fd < 0) {
9485 /* try to dup to any fd */
9486 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009487 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009488 /* give up */
9489 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009490 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009491 }
9492 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009493// TODO: track & disallow any attempts of user
9494// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009495 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009496 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009497 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009498 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009499
Mike Frysinger38478a62009-05-20 04:48:06 -04009500 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009501 /* If we were run as 'hush &', sleep until we are
9502 * in the foreground (tty pgrp == our pgrp).
9503 * If we get started under a job aware app (like bash),
9504 * make sure we are now in charge so we don't fight over
9505 * who gets the foreground */
9506 while (1) {
9507 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009508 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9509 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009510 break;
9511 /* send TTIN to ourself (should stop us) */
9512 kill(- shell_pgrp, SIGTTIN);
9513 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009514 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009515
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009516 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009517 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009518
Mike Frysinger38478a62009-05-20 04:48:06 -04009519 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009520 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009521 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009522 /* Put ourselves in our own process group
9523 * (bash, too, does this only if ctty is available) */
9524 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9525 /* Grab control of the terminal */
9526 tcsetpgrp(G_interactive_fd, getpid());
9527 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009528 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009529
9530# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9531 {
9532 const char *hp = get_local_var_value("HISTFILE");
9533 if (!hp) {
9534 hp = get_local_var_value("HOME");
9535 if (hp)
9536 hp = concat_path_file(hp, ".hush_history");
9537 } else {
9538 hp = xstrdup(hp);
9539 }
9540 if (hp) {
9541 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009542 //set_local_var(xasprintf("HISTFILE=%s", ...));
9543 }
9544# if ENABLE_FEATURE_SH_HISTFILESIZE
9545 hp = get_local_var_value("HISTFILESIZE");
9546 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9547# endif
9548 }
9549# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009550 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009551 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009552 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009553#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009554 /* No job control compiled in, only prompt/line editing */
9555 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009556 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009557 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009558 /* try to dup to any fd */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009559 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009560 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009561 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009562 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009563 }
9564 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009565 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009566 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009567 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009568 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009569#else
9570 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009571 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009572#endif
9573 /* bash:
9574 * if interactive but not a login shell, sources ~/.bashrc
9575 * (--norc turns this off, --rcfile <file> overrides)
9576 */
9577
9578 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009579 /* note: ash and hush share this string */
9580 printf("\n\n%s %s\n"
9581 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9582 "\n",
9583 bb_banner,
9584 "hush - the humble shell"
9585 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009586 }
9587
Denis Vlasenkof9375282009-04-05 19:13:39 +00009588 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009589
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009590 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009591 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009592}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009593
9594
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009595/*
9596 * Built-ins
9597 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009598static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009599{
9600 return 0;
9601}
9602
Denys Vlasenko265062d2017-01-10 15:13:30 +01009603#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009604static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009605{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009606 int argc = string_array_len(argv);
9607 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009608}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009609#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009610#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009611static int FAST_FUNC builtin_test(char **argv)
9612{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009613 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009614}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009615#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009616#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009617static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009618{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009619 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009620}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009621#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009622#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009623static int FAST_FUNC builtin_printf(char **argv)
9624{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009625 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009626}
9627#endif
9628
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009629#if ENABLE_HUSH_HELP
9630static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9631{
9632 const struct built_in_command *x;
9633
9634 printf(
9635 "Built-in commands:\n"
9636 "------------------\n");
9637 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9638 if (x->b_descr)
9639 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9640 }
9641 return EXIT_SUCCESS;
9642}
9643#endif
9644
9645#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9646static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9647{
9648 show_history(G.line_input_state);
9649 return EXIT_SUCCESS;
9650}
9651#endif
9652
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009653static char **skip_dash_dash(char **argv)
9654{
9655 argv++;
9656 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9657 argv++;
9658 return argv;
9659}
9660
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009661static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009662{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009663 const char *newdir;
9664
9665 argv = skip_dash_dash(argv);
9666 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009667 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009668 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009669 * bash says "bash: cd: HOME not set" and does nothing
9670 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009671 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009672 const char *home = get_local_var_value("HOME");
9673 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009674 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009675 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009676 /* Mimic bash message exactly */
9677 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009678 return EXIT_FAILURE;
9679 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009680 /* Read current dir (get_cwd(1) is inside) and set PWD.
9681 * Note: do not enforce exporting. If PWD was unset or unexported,
9682 * set it again, but do not export. bash does the same.
9683 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009684 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009685 return EXIT_SUCCESS;
9686}
9687
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009688static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9689{
9690 puts(get_cwd(0));
9691 return EXIT_SUCCESS;
9692}
9693
9694static int FAST_FUNC builtin_eval(char **argv)
9695{
9696 int rcode = EXIT_SUCCESS;
9697
9698 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009699 if (argv[0]) {
9700 char *str = NULL;
9701
9702 if (argv[1]) {
9703 /* "The eval utility shall construct a command by
9704 * concatenating arguments together, separating
9705 * each with a <space> character."
9706 */
9707 char *p;
9708 unsigned len = 0;
9709 char **pp = argv;
9710 do
9711 len += strlen(*pp) + 1;
9712 while (*++pp);
9713 str = p = xmalloc(len);
9714 pp = argv;
9715 do {
9716 p = stpcpy(p, *pp);
9717 *p++ = ' ';
9718 } while (*++pp);
9719 p[-1] = '\0';
9720 }
9721
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009722 /* bash:
9723 * eval "echo Hi; done" ("done" is syntax error):
9724 * "echo Hi" will not execute too.
9725 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009726 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009727 free(str);
9728 rcode = G.last_exitcode;
9729 }
9730 return rcode;
9731}
9732
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009733static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009734{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009735 argv = skip_dash_dash(argv);
9736 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009737 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009738
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009739 /* Careful: we can end up here after [v]fork. Do not restore
9740 * tty pgrp then, only top-level shell process does that */
9741 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9742 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9743
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009744 /* Saved-redirect fds, script fds and G_interactive_fd are still
9745 * open here. However, they are all CLOEXEC, and execv below
9746 * closes them. Try interactive "exec ls -l /proc/self/fd",
9747 * it should show no extra open fds in the "ls" process.
9748 * If we'd try to run builtins/NOEXECs, this would need improving.
9749 */
9750 //close_saved_fds_and_FILE_fds();
9751
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009752 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009753 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009754 * and tcsetpgrp, and this is inherently racy.
9755 */
9756 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009757}
9758
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009759static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009760{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009761 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009762
9763 /* interactive bash:
9764 * # trap "echo EEE" EXIT
9765 * # exit
9766 * exit
9767 * There are stopped jobs.
9768 * (if there are _stopped_ jobs, running ones don't count)
9769 * # exit
9770 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009771 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009772 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009773 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009774 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009775
9776 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009777 argv = skip_dash_dash(argv);
9778 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009779 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009780 /* mimic bash: exit 123abc == exit 255 + error msg */
9781 xfunc_error_retval = 255;
9782 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009783 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009784}
9785
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009786#if ENABLE_HUSH_TYPE
9787/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9788static int FAST_FUNC builtin_type(char **argv)
9789{
9790 int ret = EXIT_SUCCESS;
9791
9792 while (*++argv) {
9793 const char *type;
9794 char *path = NULL;
9795
9796 if (0) {} /* make conditional compile easier below */
9797 /*else if (find_alias(*argv))
9798 type = "an alias";*/
9799#if ENABLE_HUSH_FUNCTIONS
9800 else if (find_function(*argv))
9801 type = "a function";
9802#endif
9803 else if (find_builtin(*argv))
9804 type = "a shell builtin";
9805 else if ((path = find_in_path(*argv)) != NULL)
9806 type = path;
9807 else {
9808 bb_error_msg("type: %s: not found", *argv);
9809 ret = EXIT_FAILURE;
9810 continue;
9811 }
9812
9813 printf("%s is %s\n", *argv, type);
9814 free(path);
9815 }
9816
9817 return ret;
9818}
9819#endif
9820
9821#if ENABLE_HUSH_READ
9822/* Interruptibility of read builtin in bash
9823 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9824 *
9825 * Empty trap makes read ignore corresponding signal, for any signal.
9826 *
9827 * SIGINT:
9828 * - terminates non-interactive shell;
9829 * - interrupts read in interactive shell;
9830 * if it has non-empty trap:
9831 * - executes trap and returns to command prompt in interactive shell;
9832 * - executes trap and returns to read in non-interactive shell;
9833 * SIGTERM:
9834 * - is ignored (does not interrupt) read in interactive shell;
9835 * - terminates non-interactive shell;
9836 * if it has non-empty trap:
9837 * - executes trap and returns to read;
9838 * SIGHUP:
9839 * - terminates shell (regardless of interactivity);
9840 * if it has non-empty trap:
9841 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009842 * SIGCHLD from children:
9843 * - does not interrupt read regardless of interactivity:
9844 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009845 */
9846static int FAST_FUNC builtin_read(char **argv)
9847{
9848 const char *r;
9849 char *opt_n = NULL;
9850 char *opt_p = NULL;
9851 char *opt_t = NULL;
9852 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009853 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009854 const char *ifs;
9855 int read_flags;
9856
9857 /* "!": do not abort on errors.
9858 * Option string must start with "sr" to match BUILTIN_READ_xxx
9859 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009860 read_flags = getopt32(argv,
9861#if BASH_READ_D
9862 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9863#else
9864 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9865#endif
9866 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009867 if (read_flags == (uint32_t)-1)
9868 return EXIT_FAILURE;
9869 argv += optind;
9870 ifs = get_local_var_value("IFS"); /* can be NULL */
9871
9872 again:
9873 r = shell_builtin_read(set_local_var_from_halves,
9874 argv,
9875 ifs,
9876 read_flags,
9877 opt_n,
9878 opt_p,
9879 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009880 opt_u,
9881 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009882 );
9883
9884 if ((uintptr_t)r == 1 && errno == EINTR) {
9885 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009886 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009887 goto again;
9888 }
9889
9890 if ((uintptr_t)r > 1) {
9891 bb_error_msg("%s", r);
9892 r = (char*)(uintptr_t)1;
9893 }
9894
9895 return (uintptr_t)r;
9896}
9897#endif
9898
9899#if ENABLE_HUSH_UMASK
9900static int FAST_FUNC builtin_umask(char **argv)
9901{
9902 int rc;
9903 mode_t mask;
9904
9905 rc = 1;
9906 mask = umask(0);
9907 argv = skip_dash_dash(argv);
9908 if (argv[0]) {
9909 mode_t old_mask = mask;
9910
9911 /* numeric umasks are taken as-is */
9912 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9913 if (!isdigit(argv[0][0]))
9914 mask ^= 0777;
9915 mask = bb_parse_mode(argv[0], mask);
9916 if (!isdigit(argv[0][0]))
9917 mask ^= 0777;
9918 if ((unsigned)mask > 0777) {
9919 mask = old_mask;
9920 /* bash messages:
9921 * bash: umask: 'q': invalid symbolic mode operator
9922 * bash: umask: 999: octal number out of range
9923 */
9924 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9925 rc = 0;
9926 }
9927 } else {
9928 /* Mimic bash */
9929 printf("%04o\n", (unsigned) mask);
9930 /* fall through and restore mask which we set to 0 */
9931 }
9932 umask(mask);
9933
9934 return !rc; /* rc != 0 - success */
9935}
9936#endif
9937
Denys Vlasenko41ade052017-01-08 18:56:24 +01009938#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009939static void print_escaped(const char *s)
9940{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009941 if (*s == '\'')
9942 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009943 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009944 const char *p = strchrnul(s, '\'');
9945 /* print 'xxxx', possibly just '' */
9946 printf("'%.*s'", (int)(p - s), s);
9947 if (*p == '\0')
9948 break;
9949 s = p;
9950 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009951 /* s points to '; print "'''...'''" */
9952 putchar('"');
9953 do putchar('\''); while (*++s == '\'');
9954 putchar('"');
9955 } while (*s);
9956}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009957#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009958
Denys Vlasenko1e660422017-07-17 21:10:50 +02009959#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009960static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009961{
9962 do {
9963 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009964 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009965
9966 /* So far we do not check that name is valid (TODO?) */
9967
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009968 if (*name_end == '\0') {
9969 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009970
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009971 vpp = get_ptr_to_local_var(name, name_end - name);
9972 var = vpp ? *vpp : NULL;
9973
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009974 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009975 /* export -n NAME (without =VALUE) */
9976 if (var) {
9977 var->flg_export = 0;
9978 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9979 unsetenv(name);
9980 } /* else: export -n NOT_EXISTING_VAR: no-op */
9981 continue;
9982 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009983 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009984 /* export NAME (without =VALUE) */
9985 if (var) {
9986 var->flg_export = 1;
9987 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9988 putenv(var->varstr);
9989 continue;
9990 }
9991 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009992 if (flags & SETFLAG_MAKE_RO) {
9993 /* readonly NAME (without =VALUE) */
9994 if (var) {
9995 var->flg_read_only = 1;
9996 continue;
9997 }
9998 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009999# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010000 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010001 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010002 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10003 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010004 /* "local x=abc; ...; local x" - ignore second local decl */
10005 continue;
10006 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010007 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010008# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010009 /* Exporting non-existing variable.
10010 * bash does not put it in environment,
10011 * but remembers that it is exported,
10012 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010013 * We just set it to "" and export.
10014 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010015 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010016 * bash sets the value to "".
10017 */
10018 /* Or, it's "readonly NAME" (without =VALUE).
10019 * bash remembers NAME and disallows its creation
10020 * in the future.
10021 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010022 name = xasprintf("%s=", name);
10023 } else {
10024 /* (Un)exporting/making local NAME=VALUE */
10025 name = xstrdup(name);
10026 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010027 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010028 if (set_local_var(name, flags))
10029 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010030 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010031 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010032}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010033#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010034
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010035#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010036static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010037{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010038 unsigned opt_unexport;
10039
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010040#if ENABLE_HUSH_EXPORT_N
10041 /* "!": do not abort on errors */
10042 opt_unexport = getopt32(argv, "!n");
10043 if (opt_unexport == (uint32_t)-1)
10044 return EXIT_FAILURE;
10045 argv += optind;
10046#else
10047 opt_unexport = 0;
10048 argv++;
10049#endif
10050
10051 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010052 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010053 if (e) {
10054 while (*e) {
10055#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010056 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010057#else
10058 /* ash emits: export VAR='VAL'
10059 * bash: declare -x VAR="VAL"
10060 * we follow ash example */
10061 const char *s = *e++;
10062 const char *p = strchr(s, '=');
10063
10064 if (!p) /* wtf? take next variable */
10065 continue;
10066 /* export var= */
10067 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010068 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010069 putchar('\n');
10070#endif
10071 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010072 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010073 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010074 return EXIT_SUCCESS;
10075 }
10076
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010077 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010078}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010079#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010080
Denys Vlasenko295fef82009-06-03 12:47:26 +020010081#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010082static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010083{
10084 if (G.func_nest_level == 0) {
10085 bb_error_msg("%s: not in a function", argv[0]);
10086 return EXIT_FAILURE; /* bash compat */
10087 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010088 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010089 /* Since all builtins run in a nested variable level,
10090 * need to use level - 1 here. Or else the variable will be removed at once
10091 * after builtin returns.
10092 */
10093 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010094}
10095#endif
10096
Denys Vlasenko1e660422017-07-17 21:10:50 +020010097#if ENABLE_HUSH_READONLY
10098static int FAST_FUNC builtin_readonly(char **argv)
10099{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010100 argv++;
10101 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010102 /* bash: readonly [-p]: list all readonly VARs
10103 * (-p has no effect in bash)
10104 */
10105 struct variable *e;
10106 for (e = G.top_var; e; e = e->next) {
10107 if (e->flg_read_only) {
10108//TODO: quote value: readonly VAR='VAL'
10109 printf("readonly %s\n", e->varstr);
10110 }
10111 }
10112 return EXIT_SUCCESS;
10113 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010114 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010115}
10116#endif
10117
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010118#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010119/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10120static int FAST_FUNC builtin_unset(char **argv)
10121{
10122 int ret;
10123 unsigned opts;
10124
10125 /* "!": do not abort on errors */
10126 /* "+": stop at 1st non-option */
10127 opts = getopt32(argv, "!+vf");
10128 if (opts == (unsigned)-1)
10129 return EXIT_FAILURE;
10130 if (opts == 3) {
10131 bb_error_msg("unset: -v and -f are exclusive");
10132 return EXIT_FAILURE;
10133 }
10134 argv += optind;
10135
10136 ret = EXIT_SUCCESS;
10137 while (*argv) {
10138 if (!(opts & 2)) { /* not -f */
10139 if (unset_local_var(*argv)) {
10140 /* unset <nonexistent_var> doesn't fail.
10141 * Error is when one tries to unset RO var.
10142 * Message was printed by unset_local_var. */
10143 ret = EXIT_FAILURE;
10144 }
10145 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010146# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010147 else {
10148 unset_func(*argv);
10149 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010150# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010151 argv++;
10152 }
10153 return ret;
10154}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010155#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010156
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010157#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010158/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10159 * built-in 'set' handler
10160 * SUSv3 says:
10161 * set [-abCefhmnuvx] [-o option] [argument...]
10162 * set [+abCefhmnuvx] [+o option] [argument...]
10163 * set -- [argument...]
10164 * set -o
10165 * set +o
10166 * Implementations shall support the options in both their hyphen and
10167 * plus-sign forms. These options can also be specified as options to sh.
10168 * Examples:
10169 * Write out all variables and their values: set
10170 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10171 * Turn on the -x and -v options: set -xv
10172 * Unset all positional parameters: set --
10173 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10174 * Set the positional parameters to the expansion of x, even if x expands
10175 * with a leading '-' or '+': set -- $x
10176 *
10177 * So far, we only support "set -- [argument...]" and some of the short names.
10178 */
10179static int FAST_FUNC builtin_set(char **argv)
10180{
10181 int n;
10182 char **pp, **g_argv;
10183 char *arg = *++argv;
10184
10185 if (arg == NULL) {
10186 struct variable *e;
10187 for (e = G.top_var; e; e = e->next)
10188 puts(e->varstr);
10189 return EXIT_SUCCESS;
10190 }
10191
10192 do {
10193 if (strcmp(arg, "--") == 0) {
10194 ++argv;
10195 goto set_argv;
10196 }
10197 if (arg[0] != '+' && arg[0] != '-')
10198 break;
10199 for (n = 1; arg[n]; ++n) {
10200 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10201 goto error;
10202 if (arg[n] == 'o' && argv[1])
10203 argv++;
10204 }
10205 } while ((arg = *++argv) != NULL);
10206 /* Now argv[0] is 1st argument */
10207
10208 if (arg == NULL)
10209 return EXIT_SUCCESS;
10210 set_argv:
10211
10212 /* NB: G.global_argv[0] ($0) is never freed/changed */
10213 g_argv = G.global_argv;
10214 if (G.global_args_malloced) {
10215 pp = g_argv;
10216 while (*++pp)
10217 free(*pp);
10218 g_argv[1] = NULL;
10219 } else {
10220 G.global_args_malloced = 1;
10221 pp = xzalloc(sizeof(pp[0]) * 2);
10222 pp[0] = g_argv[0]; /* retain $0 */
10223 g_argv = pp;
10224 }
10225 /* This realloc's G.global_argv */
10226 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10227
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010228 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010229
10230 return EXIT_SUCCESS;
10231
10232 /* Nothing known, so abort */
10233 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010234 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010235 return EXIT_FAILURE;
10236}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010237#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010238
10239static int FAST_FUNC builtin_shift(char **argv)
10240{
10241 int n = 1;
10242 argv = skip_dash_dash(argv);
10243 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010244 n = bb_strtou(argv[0], NULL, 10);
10245 if (errno || n < 0) {
10246 /* shared string with ash.c */
10247 bb_error_msg("Illegal number: %s", argv[0]);
10248 /*
10249 * ash aborts in this case.
10250 * bash prints error message and set $? to 1.
10251 * Interestingly, for "shift 99999" bash does not
10252 * print error message, but does set $? to 1
10253 * (and does no shifting at all).
10254 */
10255 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010256 }
10257 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010258 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010259 int m = 1;
10260 while (m <= n)
10261 free(G.global_argv[m++]);
10262 }
10263 G.global_argc -= n;
10264 memmove(&G.global_argv[1], &G.global_argv[n+1],
10265 G.global_argc * sizeof(G.global_argv[0]));
10266 return EXIT_SUCCESS;
10267 }
10268 return EXIT_FAILURE;
10269}
10270
Denys Vlasenko74d40582017-08-11 01:32:46 +020010271#if ENABLE_HUSH_GETOPTS
10272static int FAST_FUNC builtin_getopts(char **argv)
10273{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010274/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10275
Denys Vlasenko74d40582017-08-11 01:32:46 +020010276TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010277If a required argument is not found, and getopts is not silent,
10278a question mark (?) is placed in VAR, OPTARG is unset, and a
10279diagnostic message is printed. If getopts is silent, then a
10280colon (:) is placed in VAR and OPTARG is set to the option
10281character found.
10282
10283Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010284
10285"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010286*/
10287 char cbuf[2];
10288 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010289 int c, n, exitcode, my_opterr;
10290 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010291
10292 optstring = *++argv;
10293 if (!optstring || !(var = *++argv)) {
10294 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10295 return EXIT_FAILURE;
10296 }
10297
Denys Vlasenko238ff982017-08-29 13:38:30 +020010298 if (argv[1])
10299 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10300 else
10301 argv = G.global_argv;
10302 cbuf[1] = '\0';
10303
10304 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010305 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010306 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010307 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010308 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010309 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010310
10311 /* getopts stops on first non-option. Add "+" to force that */
10312 /*if (optstring[0] != '+')*/ {
10313 char *s = alloca(strlen(optstring) + 2);
10314 sprintf(s, "+%s", optstring);
10315 optstring = s;
10316 }
10317
Denys Vlasenko238ff982017-08-29 13:38:30 +020010318 /* Naively, now we should just
10319 * cp = get_local_var_value("OPTIND");
10320 * optind = cp ? atoi(cp) : 0;
10321 * optarg = NULL;
10322 * opterr = my_opterr;
10323 * c = getopt(string_array_len(argv), argv, optstring);
10324 * and be done? Not so fast...
10325 * Unlike normal getopt() usage in C programs, here
10326 * each successive call will (usually) have the same argv[] CONTENTS,
10327 * but not the ADDRESSES. Worse yet, it's possible that between
10328 * invocations of "getopts", there will be calls to shell builtins
10329 * which use getopt() internally. Example:
10330 * while getopts "abc" RES -a -bc -abc de; do
10331 * unset -ff func
10332 * done
10333 * This would not work correctly: getopt() call inside "unset"
10334 * modifies internal libc state which is tracking position in
10335 * multi-option strings ("-abc"). At best, it can skip options
10336 * or return the same option infinitely. With glibc implementation
10337 * of getopt(), it would use outright invalid pointers and return
10338 * garbage even _without_ "unset" mangling internal state.
10339 *
10340 * We resort to resetting getopt() state and calling it N times,
10341 * until we get Nth result (or failure).
10342 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10343 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010344 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010345 count = 0;
10346 n = string_array_len(argv);
10347 do {
10348 optarg = NULL;
10349 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10350 c = getopt(n, argv, optstring);
10351 if (c < 0)
10352 break;
10353 count++;
10354 } while (count <= G.getopt_count);
10355
10356 /* Set OPTIND. Prevent resetting of the magic counter! */
10357 set_local_var_from_halves("OPTIND", utoa(optind));
10358 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010359 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010360
10361 /* Set OPTARG */
10362 /* Always set or unset, never left as-is, even on exit/error:
10363 * "If no option was found, or if the option that was found
10364 * does not have an option-argument, OPTARG shall be unset."
10365 */
10366 cp = optarg;
10367 if (c == '?') {
10368 /* If ":optstring" and unknown option is seen,
10369 * it is stored to OPTARG.
10370 */
10371 if (optstring[1] == ':') {
10372 cbuf[0] = optopt;
10373 cp = cbuf;
10374 }
10375 }
10376 if (cp)
10377 set_local_var_from_halves("OPTARG", cp);
10378 else
10379 unset_local_var("OPTARG");
10380
10381 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010382 exitcode = EXIT_SUCCESS;
10383 if (c < 0) { /* -1: end of options */
10384 exitcode = EXIT_FAILURE;
10385 c = '?';
10386 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010387
Denys Vlasenko238ff982017-08-29 13:38:30 +020010388 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010389 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010390 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010391
Denys Vlasenko74d40582017-08-11 01:32:46 +020010392 return exitcode;
10393}
10394#endif
10395
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010396static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010397{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010398 char *arg_path, *filename;
10399 FILE *input;
10400 save_arg_t sv;
10401 char *args_need_save;
10402#if ENABLE_HUSH_FUNCTIONS
10403 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010404#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010405
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010406 argv = skip_dash_dash(argv);
10407 filename = argv[0];
10408 if (!filename) {
10409 /* bash says: "bash: .: filename argument required" */
10410 return 2; /* bash compat */
10411 }
10412 arg_path = NULL;
10413 if (!strchr(filename, '/')) {
10414 arg_path = find_in_path(filename);
10415 if (arg_path)
10416 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010417 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010418 errno = ENOENT;
10419 bb_simple_perror_msg(filename);
10420 return EXIT_FAILURE;
10421 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010422 }
10423 input = remember_FILE(fopen_or_warn(filename, "r"));
10424 free(arg_path);
10425 if (!input) {
10426 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10427 /* POSIX: non-interactive shell should abort here,
10428 * not merely fail. So far no one complained :)
10429 */
10430 return EXIT_FAILURE;
10431 }
10432
10433#if ENABLE_HUSH_FUNCTIONS
10434 sv_flg = G_flag_return_in_progress;
10435 /* "we are inside sourced file, ok to use return" */
10436 G_flag_return_in_progress = -1;
10437#endif
10438 args_need_save = argv[1]; /* used as a boolean variable */
10439 if (args_need_save)
10440 save_and_replace_G_args(&sv, argv);
10441
10442 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10443 G.last_exitcode = 0;
10444 parse_and_run_file(input);
10445 fclose_and_forget(input);
10446
10447 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10448 restore_G_args(&sv, argv);
10449#if ENABLE_HUSH_FUNCTIONS
10450 G_flag_return_in_progress = sv_flg;
10451#endif
10452
10453 return G.last_exitcode;
10454}
10455
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010456#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010457static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010458{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010459 int sig;
10460 char *new_cmd;
10461
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010462 if (!G_traps)
10463 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010464
10465 argv++;
10466 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010467 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010468 /* No args: print all trapped */
10469 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010470 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010471 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010472 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010473 /* note: bash adds "SIG", but only if invoked
10474 * as "bash". If called as "sh", or if set -o posix,
10475 * then it prints short signal names.
10476 * We are printing short names: */
10477 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010478 }
10479 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010480 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010481 return EXIT_SUCCESS;
10482 }
10483
10484 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010485 /* If first arg is a number: reset all specified signals */
10486 sig = bb_strtou(*argv, NULL, 10);
10487 if (errno == 0) {
10488 int ret;
10489 process_sig_list:
10490 ret = EXIT_SUCCESS;
10491 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010492 sighandler_t handler;
10493
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010494 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010495 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010496 ret = EXIT_FAILURE;
10497 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010498 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010499 continue;
10500 }
10501
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010502 free(G_traps[sig]);
10503 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010504
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010505 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010506 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010507
10508 /* There is no signal for 0 (EXIT) */
10509 if (sig == 0)
10510 continue;
10511
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010512 if (new_cmd)
10513 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10514 else
10515 /* We are removing trap handler */
10516 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010517 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010518 }
10519 return ret;
10520 }
10521
10522 if (!argv[1]) { /* no second arg */
10523 bb_error_msg("trap: invalid arguments");
10524 return EXIT_FAILURE;
10525 }
10526
10527 /* First arg is "-": reset all specified to default */
10528 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10529 /* Everything else: set arg as signal handler
10530 * (includes "" case, which ignores signal) */
10531 if (argv[0][0] == '-') {
10532 if (argv[0][1] == '\0') { /* "-" */
10533 /* new_cmd remains NULL: "reset these sigs" */
10534 goto reset_traps;
10535 }
10536 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10537 argv++;
10538 }
10539 /* else: "-something", no special meaning */
10540 }
10541 new_cmd = *argv;
10542 reset_traps:
10543 argv++;
10544 goto process_sig_list;
10545}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010546#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010547
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010548#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010549static struct pipe *parse_jobspec(const char *str)
10550{
10551 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010552 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010553
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010554 if (sscanf(str, "%%%u", &jobnum) != 1) {
10555 if (str[0] != '%'
10556 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10557 ) {
10558 bb_error_msg("bad argument '%s'", str);
10559 return NULL;
10560 }
10561 /* It is "%%", "%+" or "%" - current job */
10562 jobnum = G.last_jobid;
10563 if (jobnum == 0) {
10564 bb_error_msg("no current job");
10565 return NULL;
10566 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010567 }
10568 for (pi = G.job_list; pi; pi = pi->next) {
10569 if (pi->jobid == jobnum) {
10570 return pi;
10571 }
10572 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010573 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010574 return NULL;
10575}
10576
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010577static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10578{
10579 struct pipe *job;
10580 const char *status_string;
10581
10582 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10583 for (job = G.job_list; job; job = job->next) {
10584 if (job->alive_cmds == job->stopped_cmds)
10585 status_string = "Stopped";
10586 else
10587 status_string = "Running";
10588
10589 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10590 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010591
10592 clean_up_last_dead_job();
10593
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010594 return EXIT_SUCCESS;
10595}
10596
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010597/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010598static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010599{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010600 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010601 struct pipe *pi;
10602
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010603 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010604 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010605
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010606 /* If they gave us no args, assume they want the last backgrounded task */
10607 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010608 for (pi = G.job_list; pi; pi = pi->next) {
10609 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010610 goto found;
10611 }
10612 }
10613 bb_error_msg("%s: no current job", argv[0]);
10614 return EXIT_FAILURE;
10615 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010616
10617 pi = parse_jobspec(argv[1]);
10618 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010619 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010620 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010621 /* TODO: bash prints a string representation
10622 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010623 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010624 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010625 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010626 }
10627
10628 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010629 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10630 for (i = 0; i < pi->num_cmds; i++) {
10631 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010632 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010633 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010634
10635 i = kill(- pi->pgrp, SIGCONT);
10636 if (i < 0) {
10637 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010638 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010639 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010640 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010641 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010642 }
10643
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010644 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010645 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010646 return checkjobs_and_fg_shell(pi);
10647 }
10648 return EXIT_SUCCESS;
10649}
10650#endif
10651
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010652#if ENABLE_HUSH_KILL
10653static int FAST_FUNC builtin_kill(char **argv)
10654{
10655 int ret = 0;
10656
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010657# if ENABLE_HUSH_JOB
10658 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10659 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010660
10661 do {
10662 struct pipe *pi;
10663 char *dst;
10664 int j, n;
10665
10666 if (argv[i][0] != '%')
10667 continue;
10668 /*
10669 * "kill %N" - job kill
10670 * Converting to pgrp / pid kill
10671 */
10672 pi = parse_jobspec(argv[i]);
10673 if (!pi) {
10674 /* Eat bad jobspec */
10675 j = i;
10676 do {
10677 j++;
10678 argv[j - 1] = argv[j];
10679 } while (argv[j]);
10680 ret = 1;
10681 i--;
10682 continue;
10683 }
10684 /*
10685 * In jobs started under job control, we signal
10686 * entire process group by kill -PGRP_ID.
10687 * This happens, f.e., in interactive shell.
10688 *
10689 * Otherwise, we signal each child via
10690 * kill PID1 PID2 PID3.
10691 * Testcases:
10692 * sh -c 'sleep 1|sleep 1 & kill %1'
10693 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10694 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10695 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010696 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010697 dst = alloca(n * sizeof(int)*4);
10698 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010699 if (G_interactive_fd)
10700 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010701 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010702 struct command *cmd = &pi->cmds[j];
10703 /* Skip exited members of the job */
10704 if (cmd->pid == 0)
10705 continue;
10706 /*
10707 * kill_main has matching code to expect
10708 * leading space. Needed to not confuse
10709 * negative pids with "kill -SIGNAL_NO" syntax
10710 */
10711 dst += sprintf(dst, " %u", (int)cmd->pid);
10712 }
10713 *dst = '\0';
10714 } while (argv[++i]);
10715 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010716# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010717
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010718 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010719 ret = run_applet_main(argv, kill_main);
10720 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010721 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010722 return ret;
10723}
10724#endif
10725
10726#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010727/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010728#if !ENABLE_HUSH_JOB
10729# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10730#endif
10731static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010732{
10733 int ret = 0;
10734 for (;;) {
10735 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010736 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010737
Denys Vlasenko830ea352016-11-08 04:59:11 +010010738 if (!sigisemptyset(&G.pending_set))
10739 goto check_sig;
10740
Denys Vlasenko7e675362016-10-28 21:57:31 +020010741 /* waitpid is not interruptible by SA_RESTARTed
10742 * signals which we use. Thus, this ugly dance:
10743 */
10744
10745 /* Make sure possible SIGCHLD is stored in kernel's
10746 * pending signal mask before we call waitpid.
10747 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010748 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010749 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010750 sigfillset(&oldset); /* block all signals, remember old set */
10751 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010752
10753 if (!sigisemptyset(&G.pending_set)) {
10754 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010755 goto restore;
10756 }
10757
10758 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010759/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010760 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010761 debug_printf_exec("checkjobs:%d\n", ret);
10762#if ENABLE_HUSH_JOB
10763 if (waitfor_pipe) {
10764 int rcode = job_exited_or_stopped(waitfor_pipe);
10765 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10766 if (rcode >= 0) {
10767 ret = rcode;
10768 sigprocmask(SIG_SETMASK, &oldset, NULL);
10769 break;
10770 }
10771 }
10772#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010773 /* if ECHILD, there are no children (ret is -1 or 0) */
10774 /* if ret == 0, no children changed state */
10775 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010776 if (errno == ECHILD || ret) {
10777 ret--;
10778 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010779 ret = 0;
10780 sigprocmask(SIG_SETMASK, &oldset, NULL);
10781 break;
10782 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010783 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010784 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10785 /* Note: sigsuspend invokes signal handler */
10786 sigsuspend(&oldset);
10787 restore:
10788 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010789 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010790 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010791 sig = check_and_run_traps();
10792 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010793 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010794 ret = 128 + sig;
10795 break;
10796 }
10797 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10798 }
10799 return ret;
10800}
10801
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010802static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010803{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010804 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010805 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010806
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010807 argv = skip_dash_dash(argv);
10808 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010809 /* Don't care about wait results */
10810 /* Note 1: must wait until there are no more children */
10811 /* Note 2: must be interruptible */
10812 /* Examples:
10813 * $ sleep 3 & sleep 6 & wait
10814 * [1] 30934 sleep 3
10815 * [2] 30935 sleep 6
10816 * [1] Done sleep 3
10817 * [2] Done sleep 6
10818 * $ sleep 3 & sleep 6 & wait
10819 * [1] 30936 sleep 3
10820 * [2] 30937 sleep 6
10821 * [1] Done sleep 3
10822 * ^C <-- after ~4 sec from keyboard
10823 * $
10824 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010825 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010826 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010827
Denys Vlasenko7e675362016-10-28 21:57:31 +020010828 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010829 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010830 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010831#if ENABLE_HUSH_JOB
10832 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010833 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010834 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010835 wait_pipe = parse_jobspec(*argv);
10836 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010837 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010838 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010839 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010840 } else {
10841 /* waiting on "last dead job" removes it */
10842 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010843 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010844 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010845 /* else: parse_jobspec() already emitted error msg */
10846 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010847 }
10848#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010849 /* mimic bash message */
10850 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010851 ret = EXIT_FAILURE;
10852 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010853 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010854
Denys Vlasenko7e675362016-10-28 21:57:31 +020010855 /* Do we have such child? */
10856 ret = waitpid(pid, &status, WNOHANG);
10857 if (ret < 0) {
10858 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010859 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010860 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010861 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010862 /* "wait $!" but last bg task has already exited. Try:
10863 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10864 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010865 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010866 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010867 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010868 } else {
10869 /* Example: "wait 1". mimic bash message */
10870 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010871 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010872 } else {
10873 /* ??? */
10874 bb_perror_msg("wait %s", *argv);
10875 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010876 continue; /* bash checks all argv[] */
10877 }
10878 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010879 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010880 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010881 } else {
10882 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010883 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010884 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010885 if (WIFSIGNALED(status))
10886 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010887 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010888 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010889
10890 return ret;
10891}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010892#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010893
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010894#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10895static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10896{
10897 if (argv[1]) {
10898 def = bb_strtou(argv[1], NULL, 10);
10899 if (errno || def < def_min || argv[2]) {
10900 bb_error_msg("%s: bad arguments", argv[0]);
10901 def = UINT_MAX;
10902 }
10903 }
10904 return def;
10905}
10906#endif
10907
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010908#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010909static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010910{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010911 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010912 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010913 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010914 /* if we came from builtin_continue(), need to undo "= 1" */
10915 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010916 return EXIT_SUCCESS; /* bash compat */
10917 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010918 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010919
10920 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10921 if (depth == UINT_MAX)
10922 G.flag_break_continue = BC_BREAK;
10923 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010924 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010925
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010926 return EXIT_SUCCESS;
10927}
10928
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010929static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010930{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010931 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10932 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010933}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010934#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010935
10936#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010937static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010938{
10939 int rc;
10940
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010941 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010942 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10943 return EXIT_FAILURE; /* bash compat */
10944 }
10945
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010946 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010947
10948 /* bash:
10949 * out of range: wraps around at 256, does not error out
10950 * non-numeric param:
10951 * f() { false; return qwe; }; f; echo $?
10952 * bash: return: qwe: numeric argument required <== we do this
10953 * 255 <== we also do this
10954 */
10955 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10956 return rc;
10957}
10958#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010959
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010960#if ENABLE_HUSH_TIMES
10961static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10962{
10963 static const uint8_t times_tbl[] ALIGN1 = {
10964 ' ', offsetof(struct tms, tms_utime),
10965 '\n', offsetof(struct tms, tms_stime),
10966 ' ', offsetof(struct tms, tms_cutime),
10967 '\n', offsetof(struct tms, tms_cstime),
10968 0
10969 };
10970 const uint8_t *p;
10971 unsigned clk_tck;
10972 struct tms buf;
10973
10974 clk_tck = bb_clk_tck();
10975
10976 times(&buf);
10977 p = times_tbl;
10978 do {
10979 unsigned sec, frac;
10980 unsigned long t;
10981 t = *(clock_t *)(((char *) &buf) + p[1]);
10982 sec = t / clk_tck;
10983 frac = t % clk_tck;
10984 printf("%um%u.%03us%c",
10985 sec / 60, sec % 60,
10986 (frac * 1000) / clk_tck,
10987 p[0]);
10988 p += 2;
10989 } while (*p);
10990
10991 return EXIT_SUCCESS;
10992}
10993#endif
10994
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010995#if ENABLE_HUSH_MEMLEAK
10996static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10997{
10998 void *p;
10999 unsigned long l;
11000
11001# ifdef M_TRIM_THRESHOLD
11002 /* Optional. Reduces probability of false positives */
11003 malloc_trim(0);
11004# endif
11005 /* Crude attempt to find where "free memory" starts,
11006 * sans fragmentation. */
11007 p = malloc(240);
11008 l = (unsigned long)p;
11009 free(p);
11010 p = malloc(3400);
11011 if (l < (unsigned long)p) l = (unsigned long)p;
11012 free(p);
11013
11014
11015# if 0 /* debug */
11016 {
11017 struct mallinfo mi = mallinfo();
11018 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11019 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11020 }
11021# endif
11022
11023 if (!G.memleak_value)
11024 G.memleak_value = l;
11025
11026 l -= G.memleak_value;
11027 if ((long)l < 0)
11028 l = 0;
11029 l /= 1024;
11030 if (l > 127)
11031 l = 127;
11032
11033 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11034 return l;
11035}
11036#endif