blob: ac8467fb44a8852d6088283679b25a40c5e19b9d [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200360#ifndef O_CLOEXEC
361# define O_CLOEXEC 0
362#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100363#ifndef F_DUPFD_CLOEXEC
364# define F_DUPFD_CLOEXEC F_DUPFD
365#endif
366#ifndef PIPE_BUF
367# define PIPE_BUF 4096 /* amount of buffering in a pipe */
368#endif
369
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000370
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100371/* So far, all bash compat is controlled by one config option */
372/* Separate defines document which part of code implements what */
373#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
374#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100375#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
376#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200377#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200378#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100379
380
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200381/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000382#define LEAK_HUNTING 0
383#define BUILD_AS_NOMMU 0
384/* Enable/disable sanity checks. Ok to enable in production,
385 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
386 * Keeping 1 for now even in released versions.
387 */
388#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200389/* Slightly bigger (+200 bytes), but faster hush.
390 * So far it only enables a trick with counting SIGCHLDs and forks,
391 * which allows us to do fewer waitpid's.
392 * (we can detect a case where neither forks were done nor SIGCHLDs happened
393 * and therefore waitpid will return the same result as last time)
394 */
395#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200396/* TODO: implement simplified code for users which do not need ${var%...} ops
397 * So far ${var%...} ops are always enabled:
398 */
399#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000400
401
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000402#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000403# undef BB_MMU
404# undef USE_FOR_NOMMU
405# undef USE_FOR_MMU
406# define BB_MMU 0
407# define USE_FOR_NOMMU(...) __VA_ARGS__
408# define USE_FOR_MMU(...)
409#endif
410
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200411#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100412#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000413/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000414# undef CONFIG_FEATURE_SH_STANDALONE
415# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100417# undef IF_NOT_FEATURE_SH_STANDALONE
418# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000419# define IF_FEATURE_SH_STANDALONE(...)
420# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000421#endif
422
Denis Vlasenko05743d72008-02-10 12:10:08 +0000423#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000424# undef ENABLE_FEATURE_EDITING
425# define ENABLE_FEATURE_EDITING 0
426# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
427# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200428# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
429# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000430#endif
431
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000432/* Do we support ANY keywords? */
433#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000434# define HAS_KEYWORDS 1
435# define IF_HAS_KEYWORDS(...) __VA_ARGS__
436# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000437#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000438# define HAS_KEYWORDS 0
439# define IF_HAS_KEYWORDS(...)
440# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000441#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000442
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000443/* If you comment out one of these below, it will be #defined later
444 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200445#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000446/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200447#define debug_printf_parse(...) do {} while (0)
448#define debug_printf_heredoc(...) do {} while (0)
449#define debug_print_tree(a, b) do {} while (0)
450#define debug_printf_exec(...) do {} while (0)
451#define debug_printf_env(...) do {} while (0)
452#define debug_printf_jobs(...) do {} while (0)
453#define debug_printf_expand(...) do {} while (0)
454#define debug_printf_varexp(...) do {} while (0)
455#define debug_printf_glob(...) do {} while (0)
456#define debug_printf_redir(...) do {} while (0)
457#define debug_printf_list(...) do {} while (0)
458#define debug_printf_subst(...) do {} while (0)
459#define debug_printf_prompt(...) do {} while (0)
460#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000461
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000462#define ERR_PTR ((void*)(long)1)
463
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100464#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000465
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200466#define _SPECIAL_VARS_STR "_*@$!?#"
467#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
468#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100469#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200470/* Support / and // replace ops */
471/* Note that // is stored as \ in "encoded" string representation */
472# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
473# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
474# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
475#else
476# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
477# define VAR_SUBST_OPS "%#:-=+?"
478# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
479#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200480
Denys Vlasenko932b9972018-01-11 12:39:48 +0100481#define SPECIAL_VAR_SYMBOL_STR "\3"
482#define SPECIAL_VAR_SYMBOL 3
483/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
484#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000485
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200486struct variable;
487
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
489
490/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000491 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 */
493#if !BB_MMU
494typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200495 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000496 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000497 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000498} nommu_save_t;
499#endif
500
Denys Vlasenko9b782552010-09-08 13:33:26 +0200501enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000502 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000503#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000504 RES_IF ,
505 RES_THEN ,
506 RES_ELIF ,
507 RES_ELSE ,
508 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000509#endif
510#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000511 RES_FOR ,
512 RES_WHILE ,
513 RES_UNTIL ,
514 RES_DO ,
515 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000516#endif
517#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000518 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000519#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000520#if ENABLE_HUSH_CASE
521 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200522 /* three pseudo-keywords support contrived "case" syntax: */
523 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
524 RES_MATCH , /* "word)" */
525 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000526 RES_ESAC ,
527#endif
528 RES_XXXX ,
529 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200530};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000531
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000532typedef struct o_string {
533 char *data;
534 int length; /* position where data is appended */
535 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200536 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000537 /* At least some part of the string was inside '' or "",
538 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200539 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000540 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200541 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542} o_string;
543enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200544 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
545 EXP_FLAG_GLOB = 0x2,
546 /* Protect newly added chars against globbing
547 * by prepending \ to *, ?, [, \ */
548 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
549};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000550/* Used for initialization: o_string foo = NULL_O_STRING; */
551#define NULL_O_STRING { NULL }
552
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200553#ifndef debug_printf_parse
554static const char *const assignment_flag[] = {
555 "MAYBE_ASSIGNMENT",
556 "DEFINITELY_ASSIGNMENT",
557 "NOT_ASSIGNMENT",
558 "WORD_IS_KEYWORD",
559};
560#endif
561
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200562/* We almost can use standard FILE api, but we need an ability to move
563 * its fd when redirects coincide with it. No api exists for that
564 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
565 * HFILE is our internal alternative. Only supports reading.
566 * Since we now can, we incorporate linked list of all opened HFILEs
567 * into the struct (used to be a separate mini-list).
568 */
569typedef struct HFILE {
570 char *cur;
571 char *end;
572 struct HFILE *next_hfile;
573 int is_stdin;
574 int fd;
575 char buf[1024];
576} HFILE;
577
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000578typedef struct in_str {
579 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200580 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200581 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200582 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000583} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000584
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200585/* The descrip member of this structure is only used to make
586 * debugging output pretty */
587static const struct {
588 int mode;
589 signed char default_fd;
590 char descrip[3];
591} redir_table[] = {
592 { O_RDONLY, 0, "<" },
593 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
594 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
595 { O_CREAT|O_RDWR, 1, "<>" },
596 { O_RDONLY, 0, "<<" },
597/* Should not be needed. Bogus default_fd helps in debugging */
598/* { O_RDONLY, 77, "<<" }, */
599};
600
Eric Andersen25f27032001-04-26 23:22:31 +0000601struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000602 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000603 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000604 int rd_fd; /* fd to redirect */
605 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
606 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000607 smallint rd_type; /* (enum redir_type) */
608 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000609 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200610 * bit 0: do we need to trim leading tabs?
611 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000612 */
Eric Andersen25f27032001-04-26 23:22:31 +0000613};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000614typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200615 REDIRECT_INPUT = 0,
616 REDIRECT_OVERWRITE = 1,
617 REDIRECT_APPEND = 2,
618 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000619 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200620 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000621
622 REDIRFD_CLOSE = -3,
623 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000624 REDIRFD_TO_FILE = -1,
625 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000626
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000627 HEREDOC_SKIPTABS = 1,
628 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000629} redir_type;
630
Eric Andersen25f27032001-04-26 23:22:31 +0000631
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000632struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000633 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200634 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100635#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100636 unsigned lineno;
637#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200638 smallint cmd_type; /* CMD_xxx */
639#define CMD_NORMAL 0
640#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200641#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
642/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
643 * "export v=t*"
644 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200645# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200647#if ENABLE_HUSH_FUNCTIONS
648# define CMD_FUNCDEF 3
649#endif
650
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100651 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200652 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
653 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000654#if !BB_MMU
655 char *group_as_string;
656#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000657#if ENABLE_HUSH_FUNCTIONS
658 struct function *child_func;
659/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200660 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 * When we execute "f1() {a;}" cmd, we create new function and clear
662 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200663 * When we execute "f1() {b;}", we notice that f1 exists,
664 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000665 * we put those fields back into cmd->xxx
666 * (struct function has ->parent_cmd ptr to facilitate that).
667 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
668 * Without this trick, loop would execute a;b;b;b;...
669 * instead of correct sequence a;b;a;b;...
670 * When command is freed, it severs the link
671 * (sets ->child_func->parent_cmd to NULL).
672 */
673#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000674 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000675/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
676 * and on execution these are substituted with their values.
677 * Substitution can make _several_ words out of one argv[n]!
678 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000679 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000680 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000681 struct redir_struct *redirects; /* I/O redirections */
682};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000683/* Is there anything in this command at all? */
684#define IS_NULL_CMD(cmd) \
685 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
686
Eric Andersen25f27032001-04-26 23:22:31 +0000687struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000688 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000689 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000690 int alive_cmds; /* number of commands running (not exited) */
691 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000692#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100693 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000694 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000695 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000696#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000697 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000698 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000699 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
700 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000701};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000702typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100703 PIPE_SEQ = 0,
704 PIPE_AND = 1,
705 PIPE_OR = 2,
706 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000707} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000708/* Is there anything in this pipe at all? */
709#define IS_NULL_PIPE(pi) \
710 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000711
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000712/* This holds pointers to the various results of parsing */
713struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000716 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000717 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000718 /* last command in pipe (being constructed right now) */
719 struct command *command;
720 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000721 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200722 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000723#if !BB_MMU
724 o_string as_string;
725#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000727#if HAS_KEYWORDS
728 smallint ctx_res_w;
729 smallint ctx_inverted; /* "! cmd | cmd" */
730#if ENABLE_HUSH_CASE
731 smallint ctx_dsemicolon; /* ";;" seen */
732#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000733 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
734 int old_flag;
735 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000736 * example: "if pipe1; pipe2; then pipe3; fi"
737 * when we see "if" or "then", we malloc and copy current context,
738 * and make ->stack point to it. then we parse pipeN.
739 * when closing "then" / fi" / whatever is found,
740 * we move list_head into ->stack->command->group,
741 * copy ->stack into current context, and delete ->stack.
742 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000743 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000744 struct parse_context *stack;
745#endif
746};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200747enum {
748 MAYBE_ASSIGNMENT = 0,
749 DEFINITELY_ASSIGNMENT = 1,
750 NOT_ASSIGNMENT = 2,
751 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
752 WORD_IS_KEYWORD = 3,
753};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000754
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000755/* On program start, environ points to initial environment.
756 * putenv adds new pointers into it, unsetenv removes them.
757 * Neither of these (de)allocates the strings.
758 * setenv allocates new strings in malloc space and does putenv,
759 * and thus setenv is unusable (leaky) for shell's purposes */
760#define setenv(...) setenv_is_leaky_dont_use()
761struct variable {
762 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000763 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000764 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200765 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000767 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000768};
769
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000770enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000771 BC_BREAK = 1,
772 BC_CONTINUE = 2,
773};
774
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000775#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000776struct function {
777 struct function *next;
778 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000779 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000780 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200781# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000782 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200783# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000784};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000787
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100788/* set -/+o OPT support. (TODO: make it optional)
789 * bash supports the following opts:
790 * allexport off
791 * braceexpand on
792 * emacs on
793 * errexit off
794 * errtrace off
795 * functrace off
796 * hashall on
797 * histexpand off
798 * history on
799 * ignoreeof off
800 * interactive-comments on
801 * keyword off
802 * monitor on
803 * noclobber off
804 * noexec off
805 * noglob off
806 * nolog off
807 * notify off
808 * nounset off
809 * onecmd off
810 * physical off
811 * pipefail off
812 * posix off
813 * privileged off
814 * verbose off
815 * vi off
816 * xtrace off
817 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800818static const char o_opt_strings[] ALIGN1 =
819 "pipefail\0"
820 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200821 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800822#if ENABLE_HUSH_MODE_X
823 "xtrace\0"
824#endif
825 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100826enum {
827 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800828 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200829 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800830#if ENABLE_HUSH_MODE_X
831 OPT_O_XTRACE,
832#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100833 NUM_OPT_O
834};
835
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000836/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837/* Sorted roughly by size (smaller offsets == smaller code) */
838struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000839 /* interactive_fd != 0 means we are an interactive shell.
840 * If we are, then saved_tty_pgrp can also be != 0, meaning
841 * that controlling tty is available. With saved_tty_pgrp == 0,
842 * job control still works, but terminal signals
843 * (^C, ^Z, ^Y, ^\) won't work at all, and background
844 * process groups can only be created with "cmd &".
845 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
846 * to give tty to the foreground process group,
847 * and will take it back when the group is stopped (^Z)
848 * or killed (^C).
849 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850#if ENABLE_HUSH_INTERACTIVE
851 /* 'interactive_fd' is a fd# open to ctty, if we have one
852 * _AND_ if we decided to act interactively */
853 int interactive_fd;
854 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200855 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000856# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000857#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000858# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000859#endif
860#if ENABLE_FEATURE_EDITING
861 line_input_t *line_input_state;
862#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000863 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200864 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000865 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200866#if ENABLE_HUSH_RANDOM_SUPPORT
867 random_t random_gen;
868#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000869#if ENABLE_HUSH_JOB
870 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100871 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000872 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000873 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400874# define G_saved_tty_pgrp (G.saved_tty_pgrp)
875#else
876# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000877#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200878 /* How deeply are we in context where "set -e" is ignored */
879 int errexit_depth;
880 /* "set -e" rules (do we follow them correctly?):
881 * Exit if pipe, list, or compound command exits with a non-zero status.
882 * Shell does not exit if failed command is part of condition in
883 * if/while, part of && or || list except the last command, any command
884 * in a pipe but the last, or if the command's return value is being
885 * inverted with !. If a compound command other than a subshell returns a
886 * non-zero status because a command failed while -e was being ignored, the
887 * shell does not exit. A trap on ERR, if set, is executed before the shell
888 * exits [ERR is a bashism].
889 *
890 * If a compound command or function executes in a context where -e is
891 * ignored, none of the commands executed within are affected by the -e
892 * setting. If a compound command or function sets -e while executing in a
893 * context where -e is ignored, that setting does not have any effect until
894 * the compound command or the command containing the function call completes.
895 */
896
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100897 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100898#if ENABLE_HUSH_MODE_X
899# define G_x_mode (G.o_opt[OPT_O_XTRACE])
900#else
901# define G_x_mode 0
902#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200903#if ENABLE_HUSH_INTERACTIVE
904 smallint promptmode; /* 0: PS1, 1: PS2 */
905#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000906 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000907#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000908 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000909#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000910#if ENABLE_HUSH_FUNCTIONS
911 /* 0: outside of a function (or sourced file)
912 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000913 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000914 */
915 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200916# define G_flag_return_in_progress (G.flag_return_in_progress)
917#else
918# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000919#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000920 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200921 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000922 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200923 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200924 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100925#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000927 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928# define G_global_args_malloced (G.global_args_malloced)
929#else
930# define G_global_args_malloced 0
931#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000932 /* how many non-NULL argv's we have. NB: $# + 1 */
933 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000935#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000936 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000937#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000938#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000939 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000940 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000941#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200942#if ENABLE_HUSH_GETOPTS
943 unsigned getopt_count;
944#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000945 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200946 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000947 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200948 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200949 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200950 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200951 unsigned var_nest_level;
952#if ENABLE_HUSH_FUNCTIONS
953# if ENABLE_HUSH_LOCAL
954 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200955# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200956 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000957#endif
Denys Vlasenko9dda9272018-07-27 14:12:05 +0200958#if ENABLE_HUSH_MODE_X
959 unsigned x_mode_depth;
960#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000961 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200962#if ENABLE_HUSH_FAST
963 unsigned count_SIGCHLD;
964 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200965 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200966#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100967#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100968 unsigned lineno;
969 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100970#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200971 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200972 /* Which signals have non-DFL handler (even with no traps set)?
973 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200974 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200975 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200976 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200977 * Other than these two times, never modified.
978 */
979 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200980#if ENABLE_HUSH_JOB
981 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100982# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200983#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200984# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200985#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100986#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000987 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100988# define G_traps G.traps
989#else
990# define G_traps ((char**)NULL)
991#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200992 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100993#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000994 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100995#endif
996#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000997 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000998#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200999 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +02001000#if ENABLE_FEATURE_EDITING
1001 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1002#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001003};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001004#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001005/* Not #defining name to G.name - this quickly gets unwieldy
1006 * (too many defines). Also, I actually prefer to see when a variable
1007 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001008#define INIT_G() do { \
1009 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001010 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1011 sigfillset(&G.sa.sa_mask); \
1012 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001013} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001014
1015
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001017static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001018#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001019static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001020#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_eval(char **argv) FAST_FUNC;
1022static int builtin_exec(char **argv) FAST_FUNC;
1023static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001024#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001025static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001026#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001027#if ENABLE_HUSH_READONLY
1028static int builtin_readonly(char **argv) FAST_FUNC;
1029#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001030#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001031static int builtin_fg_bg(char **argv) FAST_FUNC;
1032static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001033#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001034#if ENABLE_HUSH_GETOPTS
1035static int builtin_getopts(char **argv) FAST_FUNC;
1036#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001037#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001039#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001040#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001041static int builtin_history(char **argv) FAST_FUNC;
1042#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001043#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001045#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001046#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001048#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001049#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001050static int builtin_printf(char **argv) FAST_FUNC;
1051#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001053#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001055#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001056#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001057static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001058#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_shift(char **argv) FAST_FUNC;
1060static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001061#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001063#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001064#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001066#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001067#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001068static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001069#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001070#if ENABLE_HUSH_TIMES
1071static int builtin_times(char **argv) FAST_FUNC;
1072#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001074#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001076#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001077#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001078static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001079#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001080#if ENABLE_HUSH_KILL
1081static int builtin_kill(char **argv) FAST_FUNC;
1082#endif
1083#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001084static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001085#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001086#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001087static int builtin_break(char **argv) FAST_FUNC;
1088static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001090#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001091static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001092#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001093
1094/* Table of built-in functions. They can be forked or not, depending on
1095 * context: within pipes, they fork. As simple commands, they do not.
1096 * When used in non-forking context, they can change global variables
1097 * in the parent shell process. If forked, of course they cannot.
1098 * For example, 'unset foo | whatever' will parse and run, but foo will
1099 * still be set at the end. */
1100struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001101 const char *b_cmd;
1102 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001104 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001105# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001107# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001108#endif
1109};
1110
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001111static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001112 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001113 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001114#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001115 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#endif
1117#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001118 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001120 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001122 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001124 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1125 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001126 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001127#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001129#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001130#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001131 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001132#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001133#if ENABLE_HUSH_GETOPTS
1134 BLTIN("getopts" , builtin_getopts , NULL),
1135#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001139#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001140 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001141#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001142#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001144#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001145#if ENABLE_HUSH_KILL
1146 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1147#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001148#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001150#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001151#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001153#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001154#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001156#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001157#if ENABLE_HUSH_READONLY
1158 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1159#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001160#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001161 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001162#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001163#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001164 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001165#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001166 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001167#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001168 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001169#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001170#if ENABLE_HUSH_TIMES
1171 BLTIN("times" , builtin_times , NULL),
1172#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001173#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001174 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001175#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001176 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001178 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001179#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001180#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001181 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001182#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001183#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001185#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001186#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001188#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001189#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001190 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001191#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001192};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001193/* These builtins won't be used if we are on NOMMU and need to re-exec
1194 * (it's cheaper to run an external program in this case):
1195 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001196static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001197#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001198 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001199#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001200#if BASH_TEST2
1201 BLTIN("[[" , builtin_test , NULL),
1202#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001203#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001204 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001205#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001206#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001207 BLTIN("printf" , builtin_printf , NULL),
1208#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001209 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001210#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001211 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001212#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001213};
1214
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001215
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001216/* Debug printouts.
1217 */
1218#if HUSH_DEBUG
1219/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001220# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001221# define debug_enter() (G.debug_indent++)
1222# define debug_leave() (G.debug_indent--)
1223#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001224# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225# define debug_enter() ((void)0)
1226# define debug_leave() ((void)0)
1227#endif
1228
1229#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001230# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001231#endif
1232
1233#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001234# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001235#endif
1236
Denys Vlasenko3675c372018-07-23 16:31:21 +02001237#ifndef debug_printf_heredoc
1238# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1239#endif
1240
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001241#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001242#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001243#endif
1244
1245#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247#endif
1248
1249#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251# define DEBUG_JOBS 1
1252#else
1253# define DEBUG_JOBS 0
1254#endif
1255
1256#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001257# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258# define DEBUG_EXPAND 1
1259#else
1260# define DEBUG_EXPAND 0
1261#endif
1262
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001263#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001265#endif
1266
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001267#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001268# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269# define DEBUG_GLOB 1
1270#else
1271# define DEBUG_GLOB 0
1272#endif
1273
Denys Vlasenko2db74612017-07-07 22:07:28 +02001274#ifndef debug_printf_redir
1275# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1276#endif
1277
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001278#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001279# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001280#endif
1281
1282#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284#endif
1285
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001286#ifndef debug_printf_prompt
1287# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1288#endif
1289
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001291# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001292# define DEBUG_CLEAN 1
1293#else
1294# define DEBUG_CLEAN 0
1295#endif
1296
1297#if DEBUG_EXPAND
1298static void debug_print_strings(const char *prefix, char **vv)
1299{
1300 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001301 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001302 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001303 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001304}
1305#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001306# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001307#endif
1308
1309
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001310/* Leak hunting. Use hush_leaktool.sh for post-processing.
1311 */
1312#if LEAK_HUNTING
1313static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001314{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001315 void *ptr = xmalloc((size + 0xff) & ~0xff);
1316 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1317 return ptr;
1318}
1319static void *xxrealloc(int lineno, void *ptr, size_t size)
1320{
1321 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1322 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1323 return ptr;
1324}
1325static char *xxstrdup(int lineno, const char *str)
1326{
1327 char *ptr = xstrdup(str);
1328 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1329 return ptr;
1330}
1331static void xxfree(void *ptr)
1332{
1333 fdprintf(2, "free %p\n", ptr);
1334 free(ptr);
1335}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001336# define xmalloc(s) xxmalloc(__LINE__, s)
1337# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1338# define xstrdup(s) xxstrdup(__LINE__, s)
1339# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001340#endif
1341
1342
1343/* Syntax and runtime errors. They always abort scripts.
1344 * In interactive use they usually discard unparsed and/or unexecuted commands
1345 * and return to the prompt.
1346 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1347 */
1348#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001349# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001350# define syntax_error(lineno, msg) syntax_error(msg)
1351# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1352# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1353# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1354# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001355#endif
1356
Denys Vlasenko39701202017-08-02 19:44:05 +02001357static void die_if_script(void)
1358{
1359 if (!G_interactive_fd) {
1360 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1361 xfunc_error_retval = G.last_exitcode;
1362 xfunc_die();
1363 }
1364}
1365
1366static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001367{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001368 va_list p;
1369
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001370#if HUSH_DEBUG >= 2
1371 bb_error_msg("hush.c:%u", lineno);
1372#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001373 va_start(p, fmt);
1374 bb_verror_msg(fmt, p, NULL);
1375 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001376 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001377}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001378
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001379static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001380{
1381 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001382 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001383 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001384 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001385 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386}
1387
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001388static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001389{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001390 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001391 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001392}
1393
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001394static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001395{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001396 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001397//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1398// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001399}
1400
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001401static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001403 char msg[2] = { ch, '\0' };
1404 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001405}
1406
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001407static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001408{
1409 char msg[2];
1410 msg[0] = ch;
1411 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001412#if HUSH_DEBUG >= 2
1413 bb_error_msg("hush.c:%u", lineno);
1414#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001415 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001416 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001417}
1418
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001419#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001420# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001421# undef syntax_error
1422# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001423# undef syntax_error_unterm_ch
1424# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001425# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001426#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001427# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001428# define syntax_error(msg) syntax_error(__LINE__, msg)
1429# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1430# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1431# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1432# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001433#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001434
Denis Vlasenko552433b2009-04-04 19:29:21 +00001435
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001436#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001437static void cmdedit_update_prompt(void);
1438#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001439# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001440#endif
1441
1442
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001443/* Utility functions
1444 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001445/* Replace each \x with x in place, return ptr past NUL. */
1446static char *unbackslash(char *src)
1447{
Denys Vlasenko71885402009-09-24 01:44:13 +02001448 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001449 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001450 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001451 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001452 if (*src != '\0') {
1453 /* \x -> x */
1454 *dst++ = *src++;
1455 continue;
1456 }
1457 /* else: "\<nul>". Do not delete this backslash.
1458 * Testcase: eval 'echo ok\'
1459 */
1460 *dst++ = '\\';
1461 /* fallthrough */
1462 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001463 if ((*dst++ = *src++) == '\0')
1464 break;
1465 }
1466 return dst;
1467}
1468
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001469static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001470{
1471 int i;
1472 unsigned count1;
1473 unsigned count2;
1474 char **v;
1475
1476 v = strings;
1477 count1 = 0;
1478 if (v) {
1479 while (*v) {
1480 count1++;
1481 v++;
1482 }
1483 }
1484 count2 = 0;
1485 v = add;
1486 while (*v) {
1487 count2++;
1488 v++;
1489 }
1490 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1491 v[count1 + count2] = NULL;
1492 i = count2;
1493 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001494 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001495 return v;
1496}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001497#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001498static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1499{
1500 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1501 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1502 return ptr;
1503}
1504#define add_strings_to_strings(strings, add, need_to_dup) \
1505 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1506#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001508/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001509static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001510{
1511 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001512 v[0] = add;
1513 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001514 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001515}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001516#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001517static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1518{
1519 char **ptr = add_string_to_strings(strings, add);
1520 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1521 return ptr;
1522}
1523#define add_string_to_strings(strings, add) \
1524 xx_add_string_to_strings(__LINE__, strings, add)
1525#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001526
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001527static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001528{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001529 char **v;
1530
1531 if (!strings)
1532 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001533 v = strings;
1534 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001535 free(*v);
1536 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001537 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001538 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001539}
1540
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001541static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001542{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001543 int newfd;
1544 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001545 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1546 if (newfd >= 0) {
1547 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1548 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1549 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001550 if (errno == EBUSY)
1551 goto repeat;
1552 if (errno == EINTR)
1553 goto repeat;
1554 }
1555 return newfd;
1556}
1557
Denys Vlasenko657e9002017-07-30 23:34:04 +02001558static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001559{
1560 int newfd;
1561 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001562 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001563 if (newfd < 0) {
1564 if (errno == EBUSY)
1565 goto repeat;
1566 if (errno == EINTR)
1567 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568 /* fd was not open? */
1569 if (errno == EBADF)
1570 return fd;
1571 xfunc_die();
1572 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001573 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1574 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001575 close(fd);
1576 return newfd;
1577}
1578
1579
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001580/* Manipulating HFILEs */
1581static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001582{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001583 HFILE *fp;
1584 int fd;
1585
1586 fd = STDIN_FILENO;
1587 if (name) {
1588 fd = open(name, O_RDONLY | O_CLOEXEC);
1589 if (fd < 0)
1590 return NULL;
1591 if (O_CLOEXEC == 0) /* ancient libc */
1592 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001593 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001594
1595 fp = xmalloc(sizeof(*fp));
1596 fp->is_stdin = (name == NULL);
1597 fp->fd = fd;
1598 fp->cur = fp->end = fp->buf;
1599 fp->next_hfile = G.HFILE_list;
1600 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001601 return fp;
1602}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001603static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001604{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001605 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001606 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001607 HFILE *cur = *pp;
1608 if (cur == fp) {
1609 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001610 break;
1611 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001612 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001613 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001614 if (fp->fd >= 0)
1615 close(fp->fd);
1616 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001617}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001618static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001619{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620 int n;
1621
1622 if (fp->fd < 0) {
1623 /* Already saw EOF */
1624 return EOF;
1625 }
1626 /* Try to buffer more input */
1627 fp->cur = fp->buf;
1628 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1629 if (n < 0) {
1630 bb_perror_msg("read error");
1631 n = 0;
1632 }
1633 fp->end = fp->buf + n;
1634 if (n == 0) {
1635 /* EOF/error */
1636 close(fp->fd);
1637 fp->fd = -1;
1638 return EOF;
1639 }
1640 return (unsigned char)(*fp->cur++);
1641}
1642/* Inlined for common case of non-empty buffer.
1643 */
1644static ALWAYS_INLINE int hfgetc(HFILE *fp)
1645{
1646 if (fp->cur < fp->end)
1647 return (unsigned char)(*fp->cur++);
1648 /* Buffer empty */
1649 return refill_HFILE_and_getc(fp);
1650}
1651static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1652{
1653 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001654 while (fl) {
1655 if (fd == fl->fd) {
1656 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001657 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001658 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001659 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001660 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001661 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001662 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001663 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001664}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001665#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001666static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001667{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001668 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001669 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001670 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001671 * It is disastrous if we share memory with a vforked parent.
1672 * I'm not sure we never come here after vfork.
1673 * Therefore just close fd, nothing more.
1674 */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001675 /*hfclose(fl); - unsafe */
1676 if (fl->fd >= 0)
1677 close(fl->fd);
1678 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001679 }
1680}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001681#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001682static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001683{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001684 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001685 while (fl) {
1686 if (fl->fd == fd)
1687 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001688 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001689 }
1690 return 0;
1691}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001692
1693
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001694/* Helpers for setting new $n and restoring them back
1695 */
1696typedef struct save_arg_t {
1697 char *sv_argv0;
1698 char **sv_g_argv;
1699 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001700 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001701} save_arg_t;
1702
1703static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1704{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001705 sv->sv_argv0 = argv[0];
1706 sv->sv_g_argv = G.global_argv;
1707 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001708 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001709
1710 argv[0] = G.global_argv[0]; /* retain $0 */
1711 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001712 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001713
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001714 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001715}
1716
1717static void restore_G_args(save_arg_t *sv, char **argv)
1718{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001719#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001720 if (G.global_args_malloced) {
1721 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001722 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001723 while (*++pp) /* note: does not free $0 */
1724 free(*pp);
1725 free(G.global_argv);
1726 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001727#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001728 argv[0] = sv->sv_argv0;
1729 G.global_argv = sv->sv_g_argv;
1730 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001731 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001732}
1733
1734
Denis Vlasenkod5762932009-03-31 11:22:57 +00001735/* Basic theory of signal handling in shell
1736 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001737 * This does not describe what hush does, rather, it is current understanding
1738 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001739 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1740 *
1741 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1742 * is finished or backgrounded. It is the same in interactive and
1743 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001744 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001745 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001746 * backgrounds (i.e. stops) or kills all members of currently running
1747 * pipe.
1748 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001749 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001750 * or by SIGINT in interactive shell.
1751 *
1752 * Trap handlers will execute even within trap handlers. (right?)
1753 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001754 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1755 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001756 *
1757 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001758 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001759 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001760 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001761 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001762 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001763 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001764 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001765 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001766 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001767 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001768 *
1769 * SIGQUIT: ignore
1770 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001771 * SIGHUP (interactive):
1772 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001773 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001774 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1775 * that all pipe members are stopped. Try this in bash:
1776 * while :; do :; done - ^Z does not background it
1777 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001778 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001779 * of the command line, show prompt. NB: ^C does not send SIGINT
1780 * to interactive shell while shell is waiting for a pipe,
1781 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001782 * Example 1: this waits 5 sec, but does not execute ls:
1783 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1784 * Example 2: this does not wait and does not execute ls:
1785 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1786 * Example 3: this does not wait 5 sec, but executes ls:
1787 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001788 * Example 4: this does not wait and does not execute ls:
1789 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001790 *
1791 * (What happens to signals which are IGN on shell start?)
1792 * (What happens with signal mask on shell start?)
1793 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001794 * Old implementation
1795 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001796 * We use in-kernel pending signal mask to determine which signals were sent.
1797 * We block all signals which we don't want to take action immediately,
1798 * i.e. we block all signals which need to have special handling as described
1799 * above, and all signals which have traps set.
1800 * After each pipe execution, we extract any pending signals via sigtimedwait()
1801 * and act on them.
1802 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001803 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001804 * sigset_t blocked_set: current blocked signal set
1805 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001806 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001807 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001808 * "trap 'cmd' SIGxxx":
1809 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001810 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001811 * unblock signals with special interactive handling
1812 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001813 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001814 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001815 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001816 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001818 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001819 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001820 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001821 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001822 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001823 * Standard says "When a subshell is entered, traps that are not being ignored
1824 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001825 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001826 *
1827 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001828 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001829 * masked signals are not visible!
1830 *
1831 * New implementation
1832 * ==================
1833 * We record each signal we are interested in by installing signal handler
1834 * for them - a bit like emulating kernel pending signal mask in userspace.
1835 * We are interested in: signals which need to have special handling
1836 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001837 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001838 * After each pipe execution, we extract any pending signals
1839 * and act on them.
1840 *
1841 * unsigned special_sig_mask: a mask of shell-special signals.
1842 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1843 * char *traps[sig] if trap for sig is set (even if it's '').
1844 * sigset_t pending_set: set of sigs we received.
1845 *
1846 * "trap - SIGxxx":
1847 * if sig is in special_sig_mask, set handler back to:
1848 * record_pending_signo, or to IGN if it's a tty stop signal
1849 * if sig is in fatal_sig_mask, set handler back to sigexit.
1850 * else: set handler back to SIG_DFL
1851 * "trap 'cmd' SIGxxx":
1852 * set handler to record_pending_signo.
1853 * "trap '' SIGxxx":
1854 * set handler to SIG_IGN.
1855 * after [v]fork, if we plan to be a shell:
1856 * set signals with special interactive handling to SIG_DFL
1857 * (because child shell is not interactive),
1858 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1859 * after [v]fork, if we plan to exec:
1860 * POSIX says fork clears pending signal mask in child - no need to clear it.
1861 *
1862 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1863 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1864 *
1865 * Note (compat):
1866 * Standard says "When a subshell is entered, traps that are not being ignored
1867 * are set to the default actions". bash interprets it so that traps which
1868 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001869 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001870enum {
1871 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001872 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001873 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001874 | (1 << SIGHUP)
1875 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001876 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001877#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001878 | (1 << SIGTTIN)
1879 | (1 << SIGTTOU)
1880 | (1 << SIGTSTP)
1881#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001882 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001883};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001884
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001885static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001886{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001887 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001888#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001889 if (sig == SIGCHLD) {
1890 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001891//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 +02001892 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001893#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001894}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001895
Denys Vlasenko0806e402011-05-12 23:06:20 +02001896static sighandler_t install_sighandler(int sig, sighandler_t handler)
1897{
1898 struct sigaction old_sa;
1899
1900 /* We could use signal() to install handlers... almost:
1901 * except that we need to mask ALL signals while handlers run.
1902 * I saw signal nesting in strace, race window isn't small.
1903 * SA_RESTART is also needed, but in Linux, signal()
1904 * sets SA_RESTART too.
1905 */
1906 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1907 /* sigfillset(&G.sa.sa_mask); - already done */
1908 /* G.sa.sa_flags = SA_RESTART; - already done */
1909 G.sa.sa_handler = handler;
1910 sigaction(sig, &G.sa, &old_sa);
1911 return old_sa.sa_handler;
1912}
1913
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001914static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001915
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001916static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001917static void restore_ttypgrp_and__exit(void)
1918{
1919 /* xfunc has failed! die die die */
1920 /* no EXIT traps, this is an escape hatch! */
1921 G.exiting = 1;
1922 hush_exit(xfunc_error_retval);
1923}
1924
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001925#if ENABLE_HUSH_JOB
1926
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001927/* Needed only on some libc:
1928 * It was observed that on exit(), fgetc'ed buffered data
1929 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1930 * With the net effect that even after fork(), not vfork(),
1931 * exit() in NOEXECed applet in "sh SCRIPT":
1932 * noexec_applet_here
1933 * echo END_OF_SCRIPT
1934 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1935 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001936 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001937 * and in `cmd` handling.
1938 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1939 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001940static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001941static void fflush_and__exit(void)
1942{
1943 fflush_all();
1944 _exit(xfunc_error_retval);
1945}
1946
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001947/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001948# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001949/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001950# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001951
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001952/* Restores tty foreground process group, and exits.
1953 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001954 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001955 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001956 * We also call it if xfunc is exiting.
1957 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001958static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001959static void sigexit(int sig)
1960{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001961 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001962 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001963 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1964 /* Disable all signals: job control, SIGPIPE, etc.
1965 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1966 */
1967 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001968 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001969 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001970
1971 /* Not a signal, just exit */
1972 if (sig <= 0)
1973 _exit(- sig);
1974
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001975 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001976}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001977#else
1978
Denys Vlasenko8391c482010-05-22 17:50:43 +02001979# define disable_restore_tty_pgrp_on_exit() ((void)0)
1980# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001981
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001982#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001983
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001984static sighandler_t pick_sighandler(unsigned sig)
1985{
1986 sighandler_t handler = SIG_DFL;
1987 if (sig < sizeof(unsigned)*8) {
1988 unsigned sigmask = (1 << sig);
1989
1990#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001991 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001992 if (G_fatal_sig_mask & sigmask)
1993 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001994 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001995#endif
1996 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001997 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001998 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001999 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002000 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002001 * in an endless loop when we try to do some
2002 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002003 */
2004 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2005 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002006 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002007 }
2008 return handler;
2009}
2010
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002011/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002012static void hush_exit(int exitcode)
2013{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002014#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2015 save_history(G.line_input_state);
2016#endif
2017
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002018 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002019 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002020 char *argv[3];
2021 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002022 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002023 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002024 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002025 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002026 * "trap" will still show it, if executed
2027 * in the handler */
2028 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002029 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002030
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002031#if ENABLE_FEATURE_CLEAN_UP
2032 {
2033 struct variable *cur_var;
2034 if (G.cwd != bb_msg_unknown)
2035 free((char*)G.cwd);
2036 cur_var = G.top_var;
2037 while (cur_var) {
2038 struct variable *tmp = cur_var;
2039 if (!cur_var->max_len)
2040 free(cur_var->varstr);
2041 cur_var = cur_var->next;
2042 free(tmp);
2043 }
2044 }
2045#endif
2046
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002047 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002048#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002049 sigexit(- (exitcode & 0xff));
2050#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002051 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002052#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002053}
2054
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002055
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002056//TODO: return a mask of ALL handled sigs?
2057static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002059 int last_sig = 0;
2060
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002061 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002062 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002063
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002064 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002065 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002066 sig = 0;
2067 do {
2068 sig++;
2069 if (sigismember(&G.pending_set, sig)) {
2070 sigdelset(&G.pending_set, sig);
2071 goto got_sig;
2072 }
2073 } while (sig < NSIG);
2074 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002075 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002076 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002077 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002078 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002079 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002080 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002081 char *argv[3];
2082 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002083 argv[1] = xstrdup(G_traps[sig]);
2084 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002085 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002086 save_rcode = G.last_exitcode;
2087 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002088 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002089//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002090 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002091 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002092 } /* else: "" trap, ignoring signal */
2093 continue;
2094 }
2095 /* not a trap: special action */
2096 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002097 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002098 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002099 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002100 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002101 break;
2102#if ENABLE_HUSH_JOB
2103 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002104//TODO: why are we doing this? ash and dash don't do this,
2105//they have no handler for SIGHUP at all,
2106//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002107 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002108 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002109 /* bash is observed to signal whole process groups,
2110 * not individual processes */
2111 for (job = G.job_list; job; job = job->next) {
2112 if (job->pgrp <= 0)
2113 continue;
2114 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2115 if (kill(- job->pgrp, SIGHUP) == 0)
2116 kill(- job->pgrp, SIGCONT);
2117 }
2118 sigexit(SIGHUP);
2119 }
2120#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002121#if ENABLE_HUSH_FAST
2122 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002123 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002124 G.count_SIGCHLD++;
2125//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2126 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002127 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002128 * This simplifies wait builtin a bit.
2129 */
2130 break;
2131#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002132 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002133 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002134 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002135 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002136 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002137 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002138 * in interactive shell, because TERM is ignored.
2139 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002140 break;
2141 }
2142 }
2143 return last_sig;
2144}
2145
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002146
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002147static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002148{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002149 if (force || G.cwd == NULL) {
2150 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2151 * we must not try to free(bb_msg_unknown) */
2152 if (G.cwd == bb_msg_unknown)
2153 G.cwd = NULL;
2154 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2155 if (!G.cwd)
2156 G.cwd = bb_msg_unknown;
2157 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002158 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002159}
2160
Denis Vlasenko83506862007-11-23 13:11:42 +00002161
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002162/*
2163 * Shell and environment variable support
2164 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002165static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002166{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002167 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002169
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002170 pp = &G.top_var;
2171 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002172 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002173 return pp;
2174 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002175 }
2176 return NULL;
2177}
2178
Denys Vlasenko03dad222010-01-12 23:29:57 +01002179static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002180{
Denys Vlasenko29082232010-07-16 13:52:32 +02002181 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002182 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002183
2184 if (G.expanded_assignments) {
2185 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002186 while (*cpp) {
2187 char *cp = *cpp;
2188 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2189 return cp + len + 1;
2190 cpp++;
2191 }
2192 }
2193
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002194 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002195 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002196 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002197
Denys Vlasenkodea47882009-10-09 15:40:49 +02002198 if (strcmp(name, "PPID") == 0)
2199 return utoa(G.root_ppid);
2200 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002201#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002202 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002203 return utoa(next_random(&G.random_gen));
2204#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205 return NULL;
2206}
2207
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002208static void handle_changed_special_names(const char *name, unsigned name_len)
2209{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002210 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2211 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2212 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002213 cmdedit_update_prompt();
2214 return;
2215 }
2216
2217 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2218 && name_len == 6
2219 ) {
2220#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002221 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002222 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002223 return;
2224 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002225#endif
2226#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002227 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002228 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002229 return;
2230 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002231#endif
2232 }
2233}
2234
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002235/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002236 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002237 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002238#define SETFLAG_EXPORT (1 << 0)
2239#define SETFLAG_UNEXPORT (1 << 1)
2240#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002241#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002242static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243{
Denys Vlasenko61407802018-04-04 21:14:28 +02002244 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002245 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002246 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002247 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002249 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002250
Denis Vlasenko950bd722009-04-21 11:23:56 +00002251 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002252 if (HUSH_DEBUG && !eq_sign)
2253 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002254
Denis Vlasenko950bd722009-04-21 11:23:56 +00002255 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002256 cur_pp = &G.top_var;
2257 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002258 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002259 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002260 continue;
2261 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002262
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002263 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002264 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002265 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002267//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2268//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002269 return -1;
2270 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002271 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002272 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2273 *eq_sign = '\0';
2274 unsetenv(str);
2275 *eq_sign = '=';
2276 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002277 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002278 /* bash 3.2.33(1) and exported vars:
2279 * # export z=z
2280 * # f() { local z=a; env | grep ^z; }
2281 * # f
2282 * z=a
2283 * # env | grep ^z
2284 * z=z
2285 */
2286 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002287 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002288 /* New variable is local ("local VAR=VAL" or
2289 * "VAR=VAL cmd")
2290 * and existing one is global, or local
2291 * on a lower level that new one.
2292 * Remove it from global variable list:
2293 */
2294 *cur_pp = cur->next;
2295 if (G.shadowed_vars_pp) {
2296 /* Save in "shadowed" list */
2297 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2298 cur->flg_export ? "exported " : "",
2299 cur->varstr, cur->var_nest_level, str, local_lvl
2300 );
2301 cur->next = *G.shadowed_vars_pp;
2302 *G.shadowed_vars_pp = cur;
2303 } else {
2304 /* Came from pseudo_exec_argv(), no need to save: delete it */
2305 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2306 cur->flg_export ? "exported " : "",
2307 cur->varstr, cur->var_nest_level, str, local_lvl
2308 );
2309 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2310 free_me = cur->varstr; /* then free it later */
2311 free(cur);
2312 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002313 break;
2314 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002315
Denis Vlasenko950bd722009-04-21 11:23:56 +00002316 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002317 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002318 free_and_exp:
2319 free(str);
2320 goto exp;
2321 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002322
2323 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002324 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002325 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002326 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002327 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002328 strcpy(cur->varstr, str);
2329 goto free_and_exp;
2330 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002331 /* Can't reuse */
2332 cur->max_len = 0;
2333 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002334 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002335 /* max_len == 0 signifies "malloced" var, which we can
2336 * (and have to) free. But we can't free(cur->varstr) here:
2337 * if cur->flg_export is 1, it is in the environment.
2338 * We should either unsetenv+free, or wait until putenv,
2339 * then putenv(new)+free(old).
2340 */
2341 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002342 goto set_str_and_exp;
2343 }
2344
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002345 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002346 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002347 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002348 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002349 cur->next = *cur_pp;
2350 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002351
2352 set_str_and_exp:
2353 cur->varstr = str;
2354 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002355#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002356 if (flags & SETFLAG_MAKE_RO) {
2357 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002358 }
2359#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002360 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002361 cur->flg_export = 1;
2362 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002363 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002364 cur->flg_export = 0;
2365 /* unsetenv was already done */
2366 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002367 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002368 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002369 i = putenv(cur->varstr);
2370 /* only now we can free old exported malloced string */
2371 free(free_me);
2372 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002373 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002374 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002375 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002376
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002377 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002378
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002379 return 0;
2380}
2381
Denys Vlasenko6db47842009-09-05 20:15:17 +02002382/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002383static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002384{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002385 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002386}
2387
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002388#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002389static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002390{
2391 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002392 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002393
Denys Vlasenko61407802018-04-04 21:14:28 +02002394 cur_pp = &G.top_var;
2395 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002396 if (strncmp(cur->varstr, name, name_len) == 0
2397 && cur->varstr[name_len] == '='
2398 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002399 if (cur->flg_read_only) {
2400 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002401 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002402 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002403
Denys Vlasenko61407802018-04-04 21:14:28 +02002404 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002405 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2406 bb_unsetenv(cur->varstr);
2407 if (!cur->max_len)
2408 free(cur->varstr);
2409 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002410
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002411 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002412 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002413 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002414 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002415
2416 /* Handle "unset PS1" et al even if did not find the variable to unset */
2417 handle_changed_special_names(name, name_len);
2418
Mike Frysingerd690f682009-03-30 06:50:54 +00002419 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002420}
2421
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002422static int unset_local_var(const char *name)
2423{
2424 return unset_local_var_len(name, strlen(name));
2425}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002426#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002427
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002428#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2429 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002430static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002431{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002432 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002433 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002434}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002435#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002436
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002437
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002439 * Helpers for "var1=val1 var2=val2 cmd" feature
2440 */
2441static void add_vars(struct variable *var)
2442{
2443 struct variable *next;
2444
2445 while (var) {
2446 next = var->next;
2447 var->next = G.top_var;
2448 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002449 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002450 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002451 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002452 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002453 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002454 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002455 var = next;
2456 }
2457}
2458
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002459/* We put strings[i] into variable table and possibly putenv them.
2460 * If variable is read only, we can free the strings[i]
2461 * which attempts to overwrite it.
2462 * The strings[] vector itself is freed.
2463 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002464static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002465{
2466 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002467
2468 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002469 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002470
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002471 s = strings;
2472 while (*s) {
2473 struct variable *var_p;
2474 struct variable **var_pp;
2475 char *eq;
2476
2477 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002478 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002479 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002480 var_pp = get_ptr_to_local_var(*s, eq - *s);
2481 if (var_pp) {
2482 var_p = *var_pp;
2483 if (var_p->flg_read_only) {
2484 char **p;
2485 bb_error_msg("%s: readonly variable", *s);
2486 /*
2487 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2488 * If VAR is readonly, leaving it in the list
2489 * after asssignment error (msg above)
2490 * causes doubled error message later, on unset.
2491 */
2492 debug_printf_env("removing/freeing '%s' element\n", *s);
2493 free(*s);
2494 p = s;
2495 do { *p = p[1]; p++; } while (*p);
2496 goto next;
2497 }
2498 /* below, set_local_var() with nest level will
2499 * "shadow" (remove) this variable from
2500 * global linked list.
2501 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002502 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002503 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2504 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002505 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002506 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002507 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002508 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002509}
2510
2511
2512/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002513 * Unicode helper
2514 */
2515static void reinit_unicode_for_hush(void)
2516{
2517 /* Unicode support should be activated even if LANG is set
2518 * _during_ shell execution, not only if it was set when
2519 * shell was started. Therefore, re-check LANG every time:
2520 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002521 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2522 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002523 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002524 const char *s = get_local_var_value("LC_ALL");
2525 if (!s) s = get_local_var_value("LC_CTYPE");
2526 if (!s) s = get_local_var_value("LANG");
2527 reinit_unicode(s);
2528 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002529}
2530
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002531/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002532 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002533 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002534
2535#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002536/* To test correct lineedit/interactive behavior, type from command line:
2537 * echo $P\
2538 * \
2539 * AT\
2540 * H\
2541 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002542 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002543 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002544# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002545static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002546{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002547 G.PS1 = get_local_var_value("PS1");
2548 if (G.PS1 == NULL)
2549 G.PS1 = "";
2550 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002551 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002552 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002553}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002554# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002555static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556{
2557 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002558
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002559 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002560
2561 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2562 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002563 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002564 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2565 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002566 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002567 /* bash uses $PWD value, even if it is set by user.
2568 * It uses current dir only if PWD is unset.
2569 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002570 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002571 }
2572 prompt_str = G.PS1;
2573 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002574 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575 return prompt_str;
2576}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002577static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578{
2579 int r;
2580 const char *prompt_str;
2581
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002582 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002583# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002584 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002585 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002586 if (G.flag_SIGINT) {
2587 /* There was ^C'ed, make it look prettier: */
2588 bb_putchar('\n');
2589 G.flag_SIGINT = 0;
2590 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002591 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002592 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002593 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002594 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002595 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002596 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002597 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002598 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002599 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002600 if (r != 0 && !G.flag_SIGINT)
2601 break;
2602 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002603 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2604 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002605 G.last_exitcode = 128 + SIGINT;
2606 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002607 if (r < 0) {
2608 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002609 i->p = NULL;
2610 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002611 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002612 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002613 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002614 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002615# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002616 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002617 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002618 if (i->last_char == '\0' || i->last_char == '\n') {
2619 /* Why check_and_run_traps here? Try this interactively:
2620 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2621 * $ <[enter], repeatedly...>
2622 * Without check_and_run_traps, handler never runs.
2623 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002624 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002625 fputs(prompt_str, stdout);
2626 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002627 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002628//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002629 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002630 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2631 * no ^C masking happens during fgetc, no special code for ^C:
2632 * it generates SIGINT as usual.
2633 */
2634 check_and_run_traps();
2635 if (G.flag_SIGINT)
2636 G.last_exitcode = 128 + SIGINT;
2637 if (r != '\0')
2638 break;
2639 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002640 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002641# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002642}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643/* This is the magic location that prints prompts
2644 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002645static int fgetc_interactive(struct in_str *i)
2646{
2647 int ch;
2648 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002649 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002650 /* Returns first char (or EOF), the rest is in i->p[] */
2651 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002652 G.promptmode = 1; /* PS2 */
2653 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002654 } else {
2655 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002656 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002657 }
2658 return ch;
2659}
2660#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002661static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002662{
2663 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002664 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002665 return ch;
2666}
2667#endif /* INTERACTIVE */
2668
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002669static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002670{
2671 int ch;
2672
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002673 if (!i->file) {
2674 /* string-based in_str */
2675 ch = (unsigned char)*i->p;
2676 if (ch != '\0') {
2677 i->p++;
2678 i->last_char = ch;
2679 return ch;
2680 }
2681 return EOF;
2682 }
2683
2684 /* FILE-based in_str */
2685
Denys Vlasenko4074d492016-09-30 01:49:53 +02002686#if ENABLE_FEATURE_EDITING
2687 /* This can be stdin, check line editing char[] buffer */
2688 if (i->p && *i->p != '\0') {
2689 ch = (unsigned char)*i->p++;
2690 goto out;
2691 }
2692#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002693 /* peek_buf[] is an int array, not char. Can contain EOF. */
2694 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002695 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002696 int ch2 = i->peek_buf[1];
2697 i->peek_buf[0] = ch2;
2698 if (ch2 == 0) /* very likely, avoid redundant write */
2699 goto out;
2700 i->peek_buf[1] = 0;
2701 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002702 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002703
Denys Vlasenko4074d492016-09-30 01:49:53 +02002704 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002705 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002706 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002707 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002708#if ENABLE_HUSH_LINENO_VAR
2709 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002710 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002711 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2712 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002713#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002714 return ch;
2715}
2716
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002717static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002718{
2719 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002720
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002721 if (!i->file) {
2722 /* string-based in_str */
2723 /* Doesn't report EOF on NUL. None of the callers care. */
2724 return (unsigned char)*i->p;
2725 }
2726
2727 /* FILE-based in_str */
2728
Denys Vlasenko4074d492016-09-30 01:49:53 +02002729#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002730 /* This can be stdin, check line editing char[] buffer */
2731 if (i->p && *i->p != '\0')
2732 return (unsigned char)*i->p;
2733#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002734 /* peek_buf[] is an int array, not char. Can contain EOF. */
2735 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002736 if (ch != 0)
2737 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002738
Denys Vlasenko4074d492016-09-30 01:49:53 +02002739 /* Need to get a new char */
2740 ch = fgetc_interactive(i);
2741 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2742
2743 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2744#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2745 if (i->p) {
2746 i->p -= 1;
2747 return ch;
2748 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002749#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002750 i->peek_buf[0] = ch;
2751 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002752 return ch;
2753}
2754
Denys Vlasenko4074d492016-09-30 01:49:53 +02002755/* Only ever called if i_peek() was called, and did not return EOF.
2756 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2757 * not end-of-line. Therefore we never need to read a new editing line here.
2758 */
2759static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002760{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002761 int ch;
2762
2763 /* There are two cases when i->p[] buffer exists.
2764 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002765 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002766 * In both cases, we know that i->p[0] exists and not NUL, and
2767 * the peek2 result is in i->p[1].
2768 */
2769 if (i->p)
2770 return (unsigned char)i->p[1];
2771
2772 /* Now we know it is a file-based in_str. */
2773
2774 /* peek_buf[] is an int array, not char. Can contain EOF. */
2775 /* Is there 2nd char? */
2776 ch = i->peek_buf[1];
2777 if (ch == 0) {
2778 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002779 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002780 i->peek_buf[1] = ch;
2781 }
2782
2783 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2784 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002785}
2786
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002787static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2788{
2789 for (;;) {
2790 int ch, ch2;
2791
2792 ch = i_getch(input);
2793 if (ch != '\\')
2794 return ch;
2795 ch2 = i_peek(input);
2796 if (ch2 != '\n')
2797 return ch;
2798 /* backslash+newline, skip it */
2799 i_getch(input);
2800 }
2801}
2802
2803/* Note: this function _eats_ \<newline> pairs, safe to use plain
2804 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2805 */
2806static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2807{
2808 for (;;) {
2809 int ch, ch2;
2810
2811 ch = i_peek(input);
2812 if (ch != '\\')
2813 return ch;
2814 ch2 = i_peek2(input);
2815 if (ch2 != '\n')
2816 return ch;
2817 /* backslash+newline, skip it */
2818 i_getch(input);
2819 i_getch(input);
2820 }
2821}
2822
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002823static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002824{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002825 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002826 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002827 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002828}
2829
2830static void setup_string_in_str(struct in_str *i, const char *s)
2831{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002832 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002833 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002834 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002835}
2836
2837
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002838/*
2839 * o_string support
2840 */
2841#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002842
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002843static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002844{
2845 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002846 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002847 if (o->data)
2848 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002849}
2850
Denys Vlasenko18567402018-07-20 17:51:31 +02002851static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002852{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002853 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002854 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002855}
2856
Denys Vlasenko18567402018-07-20 17:51:31 +02002857static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002858{
2859 free(o->data);
2860}
2861
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002862static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002863{
2864 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002865 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002866 o->data = xrealloc(o->data, 1 + o->maxlen);
2867 }
2868}
2869
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002870static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002871{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002872 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002873 if (o->length < o->maxlen) {
2874 /* likely. avoid o_grow_by() call */
2875 add:
2876 o->data[o->length] = ch;
2877 o->length++;
2878 o->data[o->length] = '\0';
2879 return;
2880 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002881 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002882 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002883}
2884
Denys Vlasenko657086a2016-09-29 18:07:42 +02002885#if 0
2886/* Valid only if we know o_string is not empty */
2887static void o_delchr(o_string *o)
2888{
2889 o->length--;
2890 o->data[o->length] = '\0';
2891}
2892#endif
2893
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002894static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002895{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002896 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002897 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002898 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002899}
2900
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002901static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002902{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002903 o_addblock(o, str, strlen(str));
2904}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002905
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002906#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002907static void nommu_addchr(o_string *o, int ch)
2908{
2909 if (o)
2910 o_addchr(o, ch);
2911}
2912#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002913# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002914#endif
2915
2916static void o_addstr_with_NUL(o_string *o, const char *str)
2917{
2918 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002919}
2920
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002921/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002922 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002923 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2924 * Apparently, on unquoted $v bash still does globbing
2925 * ("v='*.txt'; echo $v" prints all .txt files),
2926 * but NOT brace expansion! Thus, there should be TWO independent
2927 * quoting mechanisms on $v expansion side: one protects
2928 * $v from brace expansion, and other additionally protects "$v" against globbing.
2929 * We have only second one.
2930 */
2931
Denys Vlasenko9e800222010-10-03 14:28:04 +02002932#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002933# define MAYBE_BRACES "{}"
2934#else
2935# define MAYBE_BRACES ""
2936#endif
2937
Eric Andersen25f27032001-04-26 23:22:31 +00002938/* My analysis of quoting semantics tells me that state information
2939 * is associated with a destination, not a source.
2940 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002941static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002942{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002943 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002944 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002945 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002946 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002947 o_grow_by(o, sz);
2948 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002949 o->data[o->length] = '\\';
2950 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002951 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002952 o->data[o->length] = ch;
2953 o->length++;
2954 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002955}
2956
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002957static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002958{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002959 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002960 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2961 && strchr("*?[\\" MAYBE_BRACES, ch)
2962 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002963 sz++;
2964 o->data[o->length] = '\\';
2965 o->length++;
2966 }
2967 o_grow_by(o, sz);
2968 o->data[o->length] = ch;
2969 o->length++;
2970 o->data[o->length] = '\0';
2971}
2972
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002973static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002974{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002975 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002976 char ch;
2977 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002978 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002979 if (ordinary_cnt > len) /* paranoia */
2980 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002981 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002982 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002983 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002984 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002985 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002986
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002987 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002988 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002989 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002990 sz++;
2991 o->data[o->length] = '\\';
2992 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002993 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002994 o_grow_by(o, sz);
2995 o->data[o->length] = ch;
2996 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002997 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002998 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002999}
3000
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003001static void o_addQblock(o_string *o, const char *str, int len)
3002{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003003 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003004 o_addblock(o, str, len);
3005 return;
3006 }
3007 o_addqblock(o, str, len);
3008}
3009
Denys Vlasenko38292b62010-09-05 14:49:40 +02003010static void o_addQstr(o_string *o, const char *str)
3011{
3012 o_addQblock(o, str, strlen(str));
3013}
3014
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003015/* A special kind of o_string for $VAR and `cmd` expansion.
3016 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003017 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003018 * list[i] contains an INDEX (int!) into this string data.
3019 * It means that if list[] needs to grow, data needs to be moved higher up
3020 * but list[i]'s need not be modified.
3021 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003022 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003023 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3024 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003025#if DEBUG_EXPAND || DEBUG_GLOB
3026static void debug_print_list(const char *prefix, o_string *o, int n)
3027{
3028 char **list = (char**)o->data;
3029 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3030 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003031
3032 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003033 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 +02003034 prefix, list, n, string_start, o->length, o->maxlen,
3035 !!(o->o_expflags & EXP_FLAG_GLOB),
3036 o->has_quoted_part,
3037 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003038 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003039 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003040 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3041 o->data + (int)(uintptr_t)list[i] + string_start,
3042 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003043 i++;
3044 }
3045 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003046 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003047 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003048 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003049 }
3050}
3051#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003052# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003053#endif
3054
3055/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3056 * in list[n] so that it points past last stored byte so far.
3057 * It returns n+1. */
3058static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003059{
3060 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003061 int string_start;
3062 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003063
3064 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003065 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3066 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003067 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003068 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003069 /* list[n] points to string_start, make space for 16 more pointers */
3070 o->maxlen += 0x10 * sizeof(list[0]);
3071 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003072 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003073 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003074 /*
3075 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3076 * check. (grep for -prev-ifs-check-).
3077 * Ensure that argv[-1][last] is not garbage
3078 * but zero bytes, to save index check there.
3079 */
3080 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003081 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003082 } else {
3083 debug_printf_list("list[%d]=%d string_start=%d\n",
3084 n, string_len, string_start);
3085 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003086 } else {
3087 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003088 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3089 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003090 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3091 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003092 o->has_empty_slot = 0;
3093 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003094 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003095 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003096 return n + 1;
3097}
3098
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003099/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003100static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003101{
3102 char **list = (char**)o->data;
3103 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3104
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003105 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003106}
3107
Denys Vlasenko9e800222010-10-03 14:28:04 +02003108#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003109/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3110 * first, it processes even {a} (no commas), second,
3111 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003112 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003113 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003114
3115/* Helper */
3116static int glob_needed(const char *s)
3117{
3118 while (*s) {
3119 if (*s == '\\') {
3120 if (!s[1])
3121 return 0;
3122 s += 2;
3123 continue;
3124 }
3125 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3126 return 1;
3127 s++;
3128 }
3129 return 0;
3130}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003131/* Return pointer to next closing brace or to comma */
3132static const char *next_brace_sub(const char *cp)
3133{
3134 unsigned depth = 0;
3135 cp++;
3136 while (*cp != '\0') {
3137 if (*cp == '\\') {
3138 if (*++cp == '\0')
3139 break;
3140 cp++;
3141 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003142 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003143 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003144 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003145 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003146 depth++;
3147 }
3148
3149 return *cp != '\0' ? cp : NULL;
3150}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003151/* Recursive brace globber. Note: may garble pattern[]. */
3152static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003153{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003154 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003155 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003156 const char *next;
3157 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003158 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003159 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003160
3161 debug_printf_glob("glob_brace('%s')\n", pattern);
3162
3163 begin = pattern;
3164 while (1) {
3165 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003166 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003167 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003168 /* Find the first sub-pattern and at the same time
3169 * find the rest after the closing brace */
3170 next = next_brace_sub(begin);
3171 if (next == NULL) {
3172 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003173 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003174 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003175 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003176 /* "{abc}" with no commas - illegal
3177 * brace expr, disregard and skip it */
3178 begin = next + 1;
3179 continue;
3180 }
3181 break;
3182 }
3183 if (*begin == '\\' && begin[1] != '\0')
3184 begin++;
3185 begin++;
3186 }
3187 debug_printf_glob("begin:%s\n", begin);
3188 debug_printf_glob("next:%s\n", next);
3189
3190 /* Now find the end of the whole brace expression */
3191 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003192 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003193 rest = next_brace_sub(rest);
3194 if (rest == NULL) {
3195 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003196 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003197 }
3198 debug_printf_glob("rest:%s\n", rest);
3199 }
3200 rest_len = strlen(++rest) + 1;
3201
3202 /* We are sure the brace expression is well-formed */
3203
3204 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003205 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003206
3207 /* We have a brace expression. BEGIN points to the opening {,
3208 * NEXT points past the terminator of the first element, and REST
3209 * points past the final }. We will accumulate result names from
3210 * recursive runs for each brace alternative in the buffer using
3211 * GLOB_APPEND. */
3212
3213 p = begin + 1;
3214 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003215 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003216 memcpy(
3217 mempcpy(
3218 mempcpy(new_pattern_buf,
3219 /* We know the prefix for all sub-patterns */
3220 pattern, begin - pattern),
3221 p, next - p),
3222 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003223
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003224 /* Note: glob_brace() may garble new_pattern_buf[].
3225 * That's why we re-copy prefix every time (1st memcpy above).
3226 */
3227 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003228 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003229 /* We saw the last entry */
3230 break;
3231 }
3232 p = next + 1;
3233 next = next_brace_sub(next);
3234 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003235 free(new_pattern_buf);
3236 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003237
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003238 simple_glob:
3239 {
3240 int gr;
3241 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003242
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003243 memset(&globdata, 0, sizeof(globdata));
3244 gr = glob(pattern, 0, NULL, &globdata);
3245 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3246 if (gr != 0) {
3247 if (gr == GLOB_NOMATCH) {
3248 globfree(&globdata);
3249 /* NB: garbles parameter */
3250 unbackslash(pattern);
3251 o_addstr_with_NUL(o, pattern);
3252 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3253 return o_save_ptr_helper(o, n);
3254 }
3255 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003256 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003257 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3258 * but we didn't specify it. Paranoia again. */
3259 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3260 }
3261 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3262 char **argv = globdata.gl_pathv;
3263 while (1) {
3264 o_addstr_with_NUL(o, *argv);
3265 n = o_save_ptr_helper(o, n);
3266 argv++;
3267 if (!*argv)
3268 break;
3269 }
3270 }
3271 globfree(&globdata);
3272 }
3273 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003274}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003275/* Performs globbing on last list[],
3276 * saving each result as a new list[].
3277 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003278static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003279{
3280 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003281
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003282 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003283 if (!o->data)
3284 return o_save_ptr_helper(o, n);
3285 pattern = o->data + o_get_last_ptr(o, n);
3286 debug_printf_glob("glob pattern '%s'\n", pattern);
3287 if (!glob_needed(pattern)) {
3288 /* unbackslash last string in o in place, fix length */
3289 o->length = unbackslash(pattern) - o->data;
3290 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3291 return o_save_ptr_helper(o, n);
3292 }
3293
3294 copy = xstrdup(pattern);
3295 /* "forget" pattern in o */
3296 o->length = pattern - o->data;
3297 n = glob_brace(copy, o, n);
3298 free(copy);
3299 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003300 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003301 return n;
3302}
3303
Denys Vlasenko238081f2010-10-03 14:26:26 +02003304#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003305
3306/* Helper */
3307static int glob_needed(const char *s)
3308{
3309 while (*s) {
3310 if (*s == '\\') {
3311 if (!s[1])
3312 return 0;
3313 s += 2;
3314 continue;
3315 }
3316 if (*s == '*' || *s == '[' || *s == '?')
3317 return 1;
3318 s++;
3319 }
3320 return 0;
3321}
3322/* Performs globbing on last list[],
3323 * saving each result as a new list[].
3324 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003325static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003326{
3327 glob_t globdata;
3328 int gr;
3329 char *pattern;
3330
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003331 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003332 if (!o->data)
3333 return o_save_ptr_helper(o, n);
3334 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003335 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003336 if (!glob_needed(pattern)) {
3337 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003338 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003339 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003340 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003341 return o_save_ptr_helper(o, n);
3342 }
3343
3344 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003345 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3346 * If we glob "*.\*" and don't find anything, we need
3347 * to fall back to using literal "*.*", but GLOB_NOCHECK
3348 * will return "*.\*"!
3349 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003350 gr = glob(pattern, 0, NULL, &globdata);
3351 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003352 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003353 if (gr == GLOB_NOMATCH) {
3354 globfree(&globdata);
3355 goto literal;
3356 }
3357 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003358 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003359 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3360 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003361 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003362 }
3363 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3364 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003365 /* "forget" pattern in o */
3366 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003367 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003368 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003369 n = o_save_ptr_helper(o, n);
3370 argv++;
3371 if (!*argv)
3372 break;
3373 }
3374 }
3375 globfree(&globdata);
3376 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003377 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003378 return n;
3379}
3380
Denys Vlasenko238081f2010-10-03 14:26:26 +02003381#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003382
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003383/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003384 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003385static int o_save_ptr(o_string *o, int n)
3386{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003387 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003388 /* If o->has_empty_slot, list[n] was already globbed
3389 * (if it was requested back then when it was filled)
3390 * so don't do that again! */
3391 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003392 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003393 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003394 return o_save_ptr_helper(o, n);
3395}
3396
3397/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003398static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003399{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003400 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003401 int string_start;
3402
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003403 if (DEBUG_EXPAND)
3404 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003405 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003406 list = (char**)o->data;
3407 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3408 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003409 while (n) {
3410 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003411 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003412 }
3413 return list;
3414}
3415
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003416static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003417
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003418/* Returns pi->next - next pipe in the list */
3419static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003420{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003421 struct pipe *next;
3422 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003423
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003424 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003425 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003426 struct command *command;
3427 struct redir_struct *r, *rnext;
3428
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003429 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003430 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003431 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003432 if (DEBUG_CLEAN) {
3433 int a;
3434 char **p;
3435 for (a = 0, p = command->argv; *p; a++, p++) {
3436 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3437 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003438 }
3439 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003440 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003441 }
3442 /* not "else if": on syntax error, we may have both! */
3443 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003444 debug_printf_clean(" begin group (cmd_type:%d)\n",
3445 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003446 free_pipe_list(command->group);
3447 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003448 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003449 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003450 /* else is crucial here.
3451 * If group != NULL, child_func is meaningless */
3452#if ENABLE_HUSH_FUNCTIONS
3453 else if (command->child_func) {
3454 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3455 command->child_func->parent_cmd = NULL;
3456 }
3457#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003458#if !BB_MMU
3459 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003460 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003461#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003462 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003463 debug_printf_clean(" redirect %d%s",
3464 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003465 /* guard against the case >$FOO, where foo is unset or blank */
3466 if (r->rd_filename) {
3467 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3468 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003469 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003470 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003471 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003472 rnext = r->next;
3473 free(r);
3474 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003475 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003476 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003477 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003478 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003479#if ENABLE_HUSH_JOB
3480 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003481 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003482#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003483
3484 next = pi->next;
3485 free(pi);
3486 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003487}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003488
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003489static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003490{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003491 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003492#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003493 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003494#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003495 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003496 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003497 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003498}
3499
3500
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003501/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003502
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003503#ifndef debug_print_tree
3504static void debug_print_tree(struct pipe *pi, int lvl)
3505{
3506 static const char *const PIPE[] = {
3507 [PIPE_SEQ] = "SEQ",
3508 [PIPE_AND] = "AND",
3509 [PIPE_OR ] = "OR" ,
3510 [PIPE_BG ] = "BG" ,
3511 };
3512 static const char *RES[] = {
3513 [RES_NONE ] = "NONE" ,
3514# if ENABLE_HUSH_IF
3515 [RES_IF ] = "IF" ,
3516 [RES_THEN ] = "THEN" ,
3517 [RES_ELIF ] = "ELIF" ,
3518 [RES_ELSE ] = "ELSE" ,
3519 [RES_FI ] = "FI" ,
3520# endif
3521# if ENABLE_HUSH_LOOPS
3522 [RES_FOR ] = "FOR" ,
3523 [RES_WHILE] = "WHILE",
3524 [RES_UNTIL] = "UNTIL",
3525 [RES_DO ] = "DO" ,
3526 [RES_DONE ] = "DONE" ,
3527# endif
3528# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3529 [RES_IN ] = "IN" ,
3530# endif
3531# if ENABLE_HUSH_CASE
3532 [RES_CASE ] = "CASE" ,
3533 [RES_CASE_IN ] = "CASE_IN" ,
3534 [RES_MATCH] = "MATCH",
3535 [RES_CASE_BODY] = "CASE_BODY",
3536 [RES_ESAC ] = "ESAC" ,
3537# endif
3538 [RES_XXXX ] = "XXXX" ,
3539 [RES_SNTX ] = "SNTX" ,
3540 };
3541 static const char *const CMDTYPE[] = {
3542 "{}",
3543 "()",
3544 "[noglob]",
3545# if ENABLE_HUSH_FUNCTIONS
3546 "func()",
3547# endif
3548 };
3549
3550 int pin, prn;
3551
3552 pin = 0;
3553 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003554 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3555 lvl*2, "",
3556 pin,
3557 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3558 RES[pi->res_word],
3559 pi->followup, PIPE[pi->followup]
3560 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003561 prn = 0;
3562 while (prn < pi->num_cmds) {
3563 struct command *command = &pi->cmds[prn];
3564 char **argv = command->argv;
3565
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003566 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003567 lvl*2, "", prn,
3568 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003569#if ENABLE_HUSH_LINENO_VAR
3570 fdprintf(2, " LINENO:%u", command->lineno);
3571#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003572 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003573 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003574 CMDTYPE[command->cmd_type],
3575 argv
3576# if !BB_MMU
3577 , " group_as_string:", command->group_as_string
3578# else
3579 , "", ""
3580# endif
3581 );
3582 debug_print_tree(command->group, lvl+1);
3583 prn++;
3584 continue;
3585 }
3586 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003587 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003588 argv++;
3589 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003590 if (command->redirects)
3591 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003592 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003593 prn++;
3594 }
3595 pi = pi->next;
3596 pin++;
3597 }
3598}
3599#endif /* debug_print_tree */
3600
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003601static struct pipe *new_pipe(void)
3602{
Eric Andersen25f27032001-04-26 23:22:31 +00003603 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003604 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003605 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003606 return pi;
3607}
3608
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003609/* Command (member of a pipe) is complete, or we start a new pipe
3610 * if ctx->command is NULL.
3611 * No errors possible here.
3612 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003613static int done_command(struct parse_context *ctx)
3614{
3615 /* The command is really already in the pipe structure, so
3616 * advance the pipe counter and make a new, null command. */
3617 struct pipe *pi = ctx->pipe;
3618 struct command *command = ctx->command;
3619
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003620#if 0 /* Instead we emit error message at run time */
3621 if (ctx->pending_redirect) {
3622 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003623 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003624 ctx->pending_redirect = NULL;
3625 }
3626#endif
3627
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003628 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003629 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003630 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003631 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003632 }
3633 pi->num_cmds++;
3634 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003635 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003636 } else {
3637 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3638 }
3639
3640 /* Only real trickiness here is that the uncommitted
3641 * command structure is not counted in pi->num_cmds. */
3642 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003643 ctx->command = command = &pi->cmds[pi->num_cmds];
3644 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003645 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003646#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003647 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003648 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003649#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003650 return pi->num_cmds; /* used only for 0/nonzero check */
3651}
3652
3653static void done_pipe(struct parse_context *ctx, pipe_style type)
3654{
3655 int not_null;
3656
3657 debug_printf_parse("done_pipe entered, followup %d\n", type);
3658 /* Close previous command */
3659 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003660#if HAS_KEYWORDS
3661 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3662 ctx->ctx_inverted = 0;
3663 ctx->pipe->res_word = ctx->ctx_res_w;
3664#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003665 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3666 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003667 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3668 * in a backgrounded subshell.
3669 */
3670 struct pipe *pi;
3671 struct command *command;
3672
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003673 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003674 pi = ctx->list_head;
3675 while (pi != ctx->pipe) {
3676 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3677 goto no_conv;
3678 pi = pi->next;
3679 }
3680
3681 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3682 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3683 pi = xzalloc(sizeof(*pi));
3684 pi->followup = PIPE_BG;
3685 pi->num_cmds = 1;
3686 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3687 command = &pi->cmds[0];
3688 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3689 command->cmd_type = CMD_NORMAL;
3690 command->group = ctx->list_head;
3691#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003692 command->group_as_string = xstrndup(
3693 ctx->as_string.data,
3694 ctx->as_string.length - 1 /* do not copy last char, "&" */
3695 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003696#endif
3697 /* Replace all pipes in ctx with one newly created */
3698 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003699 } else {
3700 no_conv:
3701 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003702 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003703
3704 /* Without this check, even just <enter> on command line generates
3705 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003706 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003707 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003708#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003709 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003710#endif
3711#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003712 || ctx->ctx_res_w == RES_DONE
3713 || ctx->ctx_res_w == RES_FOR
3714 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003715#endif
3716#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003717 || ctx->ctx_res_w == RES_ESAC
3718#endif
3719 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003720 struct pipe *new_p;
3721 debug_printf_parse("done_pipe: adding new pipe: "
3722 "not_null:%d ctx->ctx_res_w:%d\n",
3723 not_null, ctx->ctx_res_w);
3724 new_p = new_pipe();
3725 ctx->pipe->next = new_p;
3726 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003727 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003728 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003729 * This is used to control execution.
3730 * RES_FOR and RES_IN are NOT sticky (needed to support
3731 * cases where variable or value happens to match a keyword):
3732 */
3733#if ENABLE_HUSH_LOOPS
3734 if (ctx->ctx_res_w == RES_FOR
3735 || ctx->ctx_res_w == RES_IN)
3736 ctx->ctx_res_w = RES_NONE;
3737#endif
3738#if ENABLE_HUSH_CASE
3739 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003740 ctx->ctx_res_w = RES_CASE_BODY;
3741 if (ctx->ctx_res_w == RES_CASE)
3742 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003743#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003744 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003745 /* Create the memory for command, roughly:
3746 * ctx->pipe->cmds = new struct command;
3747 * ctx->command = &ctx->pipe->cmds[0];
3748 */
3749 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003750 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003751 }
3752 debug_printf_parse("done_pipe return\n");
3753}
3754
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003755static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003756{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003757 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003758 if (MAYBE_ASSIGNMENT != 0)
3759 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003760 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003761 /* Create the memory for command, roughly:
3762 * ctx->pipe->cmds = new struct command;
3763 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003764 */
3765 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003766}
3767
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003768/* If a reserved word is found and processed, parse context is modified
3769 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003770 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003771#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003772struct reserved_combo {
3773 char literal[6];
3774 unsigned char res;
3775 unsigned char assignment_flag;
3776 int flag;
3777};
3778enum {
3779 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003780# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003781 FLAG_IF = (1 << RES_IF ),
3782 FLAG_THEN = (1 << RES_THEN ),
3783 FLAG_ELIF = (1 << RES_ELIF ),
3784 FLAG_ELSE = (1 << RES_ELSE ),
3785 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003786# endif
3787# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003788 FLAG_FOR = (1 << RES_FOR ),
3789 FLAG_WHILE = (1 << RES_WHILE),
3790 FLAG_UNTIL = (1 << RES_UNTIL),
3791 FLAG_DO = (1 << RES_DO ),
3792 FLAG_DONE = (1 << RES_DONE ),
3793 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003794# endif
3795# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003796 FLAG_MATCH = (1 << RES_MATCH),
3797 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003798# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003799 FLAG_START = (1 << RES_XXXX ),
3800};
3801
3802static const struct reserved_combo* match_reserved_word(o_string *word)
3803{
Eric Andersen25f27032001-04-26 23:22:31 +00003804 /* Mostly a list of accepted follow-up reserved words.
3805 * FLAG_END means we are done with the sequence, and are ready
3806 * to turn the compound list into a command.
3807 * FLAG_START means the word must start a new compound list.
3808 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003809 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003810# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003811 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3812 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3813 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3814 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3815 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3816 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003817# endif
3818# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003819 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3820 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3821 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3822 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3823 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3824 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003825# endif
3826# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003827 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3828 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003829# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003830 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003831 const struct reserved_combo *r;
3832
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003833 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003834 if (strcmp(word->data, r->literal) == 0)
3835 return r;
3836 }
3837 return NULL;
3838}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003839/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003840 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003841static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003842{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003843# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003844 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003845 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003846 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003847# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003848 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003849
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003850 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003851 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003852 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003853 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003854 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003855
3856 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003857# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003858 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3859 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003860 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003861 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003862# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003863 if (r->flag == 0) { /* '!' */
3864 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003865 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003866 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003867 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003868 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003869 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003870 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003871 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003872 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003873
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003874 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003875 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003876 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003877 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003878 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003879 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003880 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003881 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003882 } else {
3883 /* "{...} fi" is ok. "{...} if" is not
3884 * Example:
3885 * if { echo foo; } then { echo bar; } fi */
3886 if (ctx->command->group)
3887 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003888 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003889
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003890 ctx->ctx_res_w = r->res;
3891 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003892 ctx->is_assignment = r->assignment_flag;
3893 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003894
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003895 if (ctx->old_flag & FLAG_END) {
3896 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003897
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003898 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003899 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003900 old = ctx->stack;
3901 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003902 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003903# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003904 /* At this point, the compound command's string is in
3905 * ctx->as_string... except for the leading keyword!
3906 * Consider this example: "echo a | if true; then echo a; fi"
3907 * ctx->as_string will contain "true; then echo a; fi",
3908 * with "if " remaining in old->as_string!
3909 */
3910 {
3911 char *str;
3912 int len = old->as_string.length;
3913 /* Concatenate halves */
3914 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003915 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003916 /* Find where leading keyword starts in first half */
3917 str = old->as_string.data + len;
3918 if (str > old->as_string.data)
3919 str--; /* skip whitespace after keyword */
3920 while (str > old->as_string.data && isalpha(str[-1]))
3921 str--;
3922 /* Ugh, we're done with this horrid hack */
3923 old->command->group_as_string = xstrdup(str);
3924 debug_printf_parse("pop, remembering as:'%s'\n",
3925 old->command->group_as_string);
3926 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003927# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003928 *ctx = *old; /* physical copy */
3929 free(old);
3930 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003931 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003932}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003933#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003934
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003935/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003936 * Normal return is 0. Syntax errors return 1.
3937 * Note: on return, word is reset, but not o_free'd!
3938 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003939static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003940{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003941 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003942
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003943 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3944 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003945 debug_printf_parse("done_word return 0: true null, ignored\n");
3946 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003947 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003948
Eric Andersen25f27032001-04-26 23:22:31 +00003949 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003950 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3951 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003952 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003953 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003954 * If the redirection operator is "<<" or "<<-", the word
3955 * that follows the redirection operator shall be
3956 * subjected to quote removal; it is unspecified whether
3957 * any of the other expansions occur. For the other
3958 * redirection operators, the word that follows the
3959 * redirection operator shall be subjected to tilde
3960 * expansion, parameter expansion, command substitution,
3961 * arithmetic expansion, and quote removal.
3962 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003963 * on the word by a non-interactive shell; an interactive
3964 * shell may perform it, but shall do so only when
3965 * the expansion would result in one word."
3966 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003967//bash does not do parameter/command substitution or arithmetic expansion
3968//for _heredoc_ redirection word: these constructs look for exact eof marker
3969// as written:
3970// <<EOF$t
3971// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003972// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3973
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003974 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003975 /* Cater for >\file case:
3976 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3977 * Same with heredocs:
3978 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3979 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003980 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3981 unbackslash(ctx->pending_redirect->rd_filename);
3982 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003983 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003984 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3985 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003986 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003987 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003988 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003989 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003990#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003991# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003992 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003993 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003994 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003995 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003996 /* ctx->ctx_res_w = RES_MATCH; */
3997 ctx->ctx_dsemicolon = 0;
3998 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003999# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004000 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004001# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004002 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4003 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004004# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004005# if ENABLE_HUSH_CASE
4006 && ctx->ctx_res_w != RES_CASE
4007# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004008 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004009 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004010 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004011 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004012 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004013# if ENABLE_HUSH_LINENO_VAR
4014/* Case:
4015 * "while ...; do
4016 * cmd ..."
4017 * If we don't close the pipe _now_, immediately after "do", lineno logic
4018 * sees "cmd" as starting at "do" - i.e., at the previous line.
4019 */
4020 if (0
4021 IF_HUSH_IF(|| reserved->res == RES_THEN)
4022 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4023 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4024 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4025 ) {
4026 done_pipe(ctx, PIPE_SEQ);
4027 }
4028# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004030 debug_printf_parse("done_word return %d\n",
4031 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004032 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004033 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004034# if defined(CMD_SINGLEWORD_NOGLOB)
4035 if (0
4036# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004037 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004038# endif
4039 /* In bash, local/export/readonly are special, args
4040 * are assignments and therefore expansion of them
4041 * should be "one-word" expansion:
4042 * $ export i=`echo 'a b'` # one arg: "i=a b"
4043 * compare with:
4044 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4045 * ls: cannot access i=a: No such file or directory
4046 * ls: cannot access b: No such file or directory
4047 * Note: bash 3.2.33(1) does this only if export word
4048 * itself is not quoted:
4049 * $ export i=`echo 'aaa bbb'`; echo "$i"
4050 * aaa bbb
4051 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4052 * aaa
4053 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004054 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4055 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4056 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004057 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004058 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4059 }
4060 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004061# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004062 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004063#endif /* HAS_KEYWORDS */
4064
Denis Vlasenkobb929512009-04-16 10:59:40 +00004065 if (command->group) {
4066 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004067 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004068 debug_printf_parse("done_word return 1: syntax error, "
4069 "groups and arglists don't mix\n");
4070 return 1;
4071 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004072
4073 /* If this word wasn't an assignment, next ones definitely
4074 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004075 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4076 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004077 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004078 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004079 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004080 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004081 command->assignment_cnt++;
4082 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4083 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004084 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4085 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004086 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004087 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4088 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004089 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004090 }
Eric Andersen25f27032001-04-26 23:22:31 +00004091
Denis Vlasenko06810332007-05-21 23:30:54 +00004092#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004093 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004094 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004095 || !is_well_formed_var_name(command->argv[0], '\0')
4096 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004097 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004098 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004099 return 1;
4100 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004101 /* Force FOR to have just one word (variable name) */
4102 /* NB: basically, this makes hush see "for v in ..."
4103 * syntax as if it is "for v; in ...". FOR and IN become
4104 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004105 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004106 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004107#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004108#if ENABLE_HUSH_CASE
4109 /* Force CASE to have just one word */
4110 if (ctx->ctx_res_w == RES_CASE) {
4111 done_pipe(ctx, PIPE_SEQ);
4112 }
4113#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004114
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004115 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004116
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004117 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004118 return 0;
4119}
4120
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004121
4122/* Peek ahead in the input to find out if we have a "&n" construct,
4123 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004124 * Return:
4125 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4126 * REDIRFD_SYNTAX_ERR if syntax error,
4127 * REDIRFD_TO_FILE if no & was seen,
4128 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004129 */
4130#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004131#define parse_redir_right_fd(as_string, input) \
4132 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004134static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004135{
4136 int ch, d, ok;
4137
4138 ch = i_peek(input);
4139 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004140 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004141
4142 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004143 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 ch = i_peek(input);
4145 if (ch == '-') {
4146 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004147 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004148 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004149 }
4150 d = 0;
4151 ok = 0;
4152 while (ch != EOF && isdigit(ch)) {
4153 d = d*10 + (ch-'0');
4154 ok = 1;
4155 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004156 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157 ch = i_peek(input);
4158 }
4159 if (ok) return d;
4160
4161//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4162
4163 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004164 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004165}
4166
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004167/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004168 */
4169static int parse_redirect(struct parse_context *ctx,
4170 int fd,
4171 redir_type style,
4172 struct in_str *input)
4173{
4174 struct command *command = ctx->command;
4175 struct redir_struct *redir;
4176 struct redir_struct **redirp;
4177 int dup_num;
4178
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004179 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004180 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004181 /* Check for a '>&1' type redirect */
4182 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4183 if (dup_num == REDIRFD_SYNTAX_ERR)
4184 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004185 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004186 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004187 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004188 if (dup_num) { /* <<-... */
4189 ch = i_getch(input);
4190 nommu_addchr(&ctx->as_string, ch);
4191 ch = i_peek(input);
4192 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004193 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004194
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004195 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004196 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004197 if (ch == '|') {
4198 /* >|FILE redirect ("clobbering" >).
4199 * Since we do not support "set -o noclobber" yet,
4200 * >| and > are the same for now. Just eat |.
4201 */
4202 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004203 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004204 }
4205 }
4206
4207 /* Create a new redir_struct and append it to the linked list */
4208 redirp = &command->redirects;
4209 while ((redir = *redirp) != NULL) {
4210 redirp = &(redir->next);
4211 }
4212 *redirp = redir = xzalloc(sizeof(*redir));
4213 /* redir->next = NULL; */
4214 /* redir->rd_filename = NULL; */
4215 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004216 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004217
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004218 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4219 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004220
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004221 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004222 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004223 /* Erik had a check here that the file descriptor in question
4224 * is legit; I postpone that to "run time"
4225 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004226 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4227 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004228 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004229#if 0 /* Instead we emit error message at run time */
4230 if (ctx->pending_redirect) {
4231 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004232 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004233 }
4234#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004235 /* Set ctx->pending_redirect, so we know what to do at the
4236 * end of the next parsed word. */
4237 ctx->pending_redirect = redir;
4238 }
4239 return 0;
4240}
4241
Eric Andersen25f27032001-04-26 23:22:31 +00004242/* If a redirect is immediately preceded by a number, that number is
4243 * supposed to tell which file descriptor to redirect. This routine
4244 * looks for such preceding numbers. In an ideal world this routine
4245 * needs to handle all the following classes of redirects...
4246 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4247 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4248 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4249 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250 *
4251 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4252 * "2.7 Redirection
4253 * ... If n is quoted, the number shall not be recognized as part of
4254 * the redirection expression. For example:
4255 * echo \2>a
4256 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004257 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004258 *
4259 * A -1 return means no valid number was found,
4260 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004261 */
4262static int redirect_opt_num(o_string *o)
4263{
4264 int num;
4265
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004267 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004268 num = bb_strtou(o->data, NULL, 10);
4269 if (errno || num < 0)
4270 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004271 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004272 return num;
4273}
4274
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004275#if BB_MMU
4276#define fetch_till_str(as_string, input, word, skip_tabs) \
4277 fetch_till_str(input, word, skip_tabs)
4278#endif
4279static char *fetch_till_str(o_string *as_string,
4280 struct in_str *input,
4281 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004282 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004283{
4284 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004285 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004286 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004287 int ch;
4288
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004289 /* Starting with "" is necessary for this case:
4290 * cat <<EOF
4291 *
4292 * xxx
4293 * EOF
4294 */
4295 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4296
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004297 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004298
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004299 while (1) {
4300 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004301 if (ch != EOF)
4302 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004303 if (ch == '\n' || ch == EOF) {
4304 check_heredoc_end:
4305 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004306 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004307 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4308 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004309 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004310 return heredoc.data;
4311 }
4312 if (ch == '\n') {
4313 /* This is a new line.
4314 * Remember position and backslash-escaping status.
4315 */
4316 o_addchr(&heredoc, ch);
4317 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004318 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004319 past_EOL = heredoc.length;
4320 /* Get 1st char of next line, possibly skipping leading tabs */
4321 do {
4322 ch = i_getch(input);
4323 if (ch != EOF)
4324 nommu_addchr(as_string, ch);
4325 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4326 /* If this immediately ended the line,
4327 * go back to end-of-line checks.
4328 */
4329 if (ch == '\n')
4330 goto check_heredoc_end;
4331 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004332 } else {
4333 /* Backslash-line continuation in an unquoted
4334 * heredoc. This does not need special handling
4335 * for heredoc body (unquoted heredocs are
4336 * expanded on "execution" and that would take
4337 * care of this case too), but not the case
4338 * of line continuation *in terminator*:
4339 * cat <<EOF
4340 * Ok1
4341 * EO\
4342 * F
4343 */
4344 heredoc.data[--heredoc.length] = '\0';
4345 prev = 0; /* not '\' */
4346 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004347 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004348 }
4349 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004350 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004351 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004352 }
4353 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004354 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004355 if (prev == '\\' && ch == '\\')
4356 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004357 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004358 else
4359 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004360 }
4361}
4362
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004363/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4364 * and load them all. There should be exactly heredoc_cnt of them.
4365 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004366#if BB_MMU
4367#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4368 fetch_heredocs(pi, heredoc_cnt, input)
4369#endif
4370static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004371{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004372 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004373 int i;
4374 struct command *cmd = pi->cmds;
4375
Denys Vlasenko3675c372018-07-23 16:31:21 +02004376 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004377 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004378 cmd->argv ? cmd->argv[0] : "NONE"
4379 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004380 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004381 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004382
Denys Vlasenko3675c372018-07-23 16:31:21 +02004383 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004384 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004385 while (redir) {
4386 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004387 char *p;
4388
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004389 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004390 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004391 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004392 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004393 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004394 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004395 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004396 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004397 free(redir->rd_filename);
4398 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004399 heredoc_cnt--;
4400 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004401 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004402 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004403 if (cmd->group) {
4404 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4405 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4406 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4407 if (heredoc_cnt < 0)
4408 return heredoc_cnt; /* error */
4409 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004410 cmd++;
4411 }
4412 pi = pi->next;
4413 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004414 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004415}
4416
4417
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004418static int run_list(struct pipe *pi);
4419#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004420#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4421 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004422#endif
4423static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004424 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004425 struct in_str *input,
4426 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004427
Denys Vlasenko474cb202018-07-24 13:03:03 +02004428/* Returns number of heredocs not yet consumed,
4429 * or -1 on error.
4430 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004431static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004432 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004433{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004434 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004435 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004436 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004437#if BB_MMU
4438# define as_string NULL
4439#else
4440 char *as_string = NULL;
4441#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004442 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004443 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004444 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004445 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004446
4447 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004448#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004449 if (ch == '(' && !ctx->word.has_quoted_part) {
4450 if (ctx->word.length)
4451 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004452 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004453 if (!command->argv)
4454 goto skip; /* (... */
4455 if (command->argv[1]) { /* word word ... (... */
4456 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004457 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004458 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004459 /* it is "word(..." or "word (..." */
4460 do
4461 ch = i_getch(input);
4462 while (ch == ' ' || ch == '\t');
4463 if (ch != ')') {
4464 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004465 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004466 }
4467 nommu_addchr(&ctx->as_string, ch);
4468 do
4469 ch = i_getch(input);
4470 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004471 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004472 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004473 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004474 }
4475 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004476 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004477 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004478 }
4479#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004480
4481#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004482 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004483 || ctx->word.length /* word{... */
4484 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004485 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004486 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004487 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004488 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004489 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004490 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004491#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004492
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004493 IF_HUSH_FUNCTIONS(skip:)
4494
Denis Vlasenko240c2552009-04-03 03:45:05 +00004495 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004496 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004497 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004498 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4499 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004500 } else {
4501 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004502 ch = i_peek(input);
4503 if (ch != ' ' && ch != '\t' && ch != '\n'
4504 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4505 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004506 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004507 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004508 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004509 if (ch != '(') {
4510 ch = i_getch(input);
4511 nommu_addchr(&ctx->as_string, ch);
4512 }
Eric Andersen25f27032001-04-26 23:22:31 +00004513 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004514
Denys Vlasenko474cb202018-07-24 13:03:03 +02004515 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4516 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4517 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004518#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004519 if (as_string)
4520 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004521#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004522
4523 /* empty ()/{} or parse error? */
4524 if (!pipe_list || pipe_list == ERR_PTR) {
4525 /* parse_stream already emitted error msg */
4526 if (!BB_MMU)
4527 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004528 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004529 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004530 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004531 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004532#if !BB_MMU
4533 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4534 command->group_as_string = as_string;
4535 debug_printf_parse("end of group, remembering as:'%s'\n",
4536 command->group_as_string);
4537#endif
4538
4539#if ENABLE_HUSH_FUNCTIONS
4540 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4541 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4542 struct command *cmd2;
4543
4544 cmd2 = xzalloc(sizeof(*cmd2));
4545 cmd2->cmd_type = CMD_SUBSHELL;
4546 cmd2->group = pipe_list;
4547# if !BB_MMU
4548//UNTESTED!
4549 cmd2->group_as_string = command->group_as_string;
4550 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4551# endif
4552
4553 pipe_list = new_pipe();
4554 pipe_list->cmds = cmd2;
4555 pipe_list->num_cmds = 1;
4556 }
4557#endif
4558
4559 command->group = pipe_list;
4560
Denys Vlasenko474cb202018-07-24 13:03:03 +02004561 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4562 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004563 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004564#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004565}
4566
Denys Vlasenko0b883582016-12-23 16:49:07 +01004567#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004569/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004570static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571{
4572 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004573 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004574 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004575 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004576 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004577 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004578 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004579 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004580 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004581 }
4582}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004583static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4584{
4585 while (1) {
4586 int ch = i_getch(input);
4587 if (ch == EOF) {
4588 syntax_error_unterm_ch('\'');
4589 return 0;
4590 }
4591 if (ch == '\'')
4592 return 1;
4593 o_addqchr(dest, ch);
4594 }
4595}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004596/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004597static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004598static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004599{
4600 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004601 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004602 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004603 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004604 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004605 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004606 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004607 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004608 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004609 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004610 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004611 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004612 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004613 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004614 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4615 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004616 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004617 continue;
4618 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004619 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004620 }
4621}
4622/* Process `cmd` - copy contents until "`" is seen. Complicated by
4623 * \` quoting.
4624 * "Within the backquoted style of command substitution, backslash
4625 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4626 * The search for the matching backquote shall be satisfied by the first
4627 * backquote found without a preceding backslash; during this search,
4628 * if a non-escaped backquote is encountered within a shell comment,
4629 * a here-document, an embedded command substitution of the $(command)
4630 * form, or a quoted string, undefined results occur. A single-quoted
4631 * or double-quoted string that begins, but does not end, within the
4632 * "`...`" sequence produces undefined results."
4633 * Example Output
4634 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4635 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004636static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004637{
4638 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004639 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004640 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004641 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004642 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004643 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4644 ch = i_getch(input);
4645 if (ch != '`'
4646 && ch != '$'
4647 && ch != '\\'
4648 && (!in_dquote || ch != '"')
4649 ) {
4650 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004651 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004652 }
4653 if (ch == EOF) {
4654 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004655 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004656 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004657 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004658 }
4659}
4660/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4661 * quoting and nested ()s.
4662 * "With the $(command) style of command substitution, all characters
4663 * following the open parenthesis to the matching closing parenthesis
4664 * constitute the command. Any valid shell script can be used for command,
4665 * except a script consisting solely of redirections which produces
4666 * unspecified results."
4667 * Example Output
4668 * echo $(echo '(TEST)' BEST) (TEST) BEST
4669 * echo $(echo 'TEST)' BEST) TEST) BEST
4670 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004671 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004672 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004673 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004674 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4675 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004676 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004677#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004678static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004679{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004680 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004681 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004682# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004683 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004684# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004685 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4686
Denys Vlasenko817a2022018-06-26 15:35:17 +02004687#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004688 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004689#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004690 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4691
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004692 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004693 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004694 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004695 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004696 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004697 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004698 if (ch == end_ch
4699# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004700 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004701# endif
4702 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004703 if (!dbl)
4704 break;
4705 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004706 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004707 i_getch(input); /* eat second ')' */
4708 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004709 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004710 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004711 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004712 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004713 if (ch == '(' || ch == '{') {
4714 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004715 if (!add_till_closing_bracket(dest, input, ch))
4716 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004717 o_addchr(dest, ch);
4718 continue;
4719 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004720 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004721 if (!add_till_single_quote(dest, input))
4722 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004723 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004724 continue;
4725 }
4726 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004727 if (!add_till_double_quote(dest, input))
4728 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004729 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004730 continue;
4731 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004732 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004733 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4734 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004735 o_addchr(dest, ch);
4736 continue;
4737 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004738 if (ch == '\\') {
4739 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004740 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004741 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004742 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004743 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004744 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004745#if 0
4746 if (ch == '\n') {
4747 /* "backslash+newline", ignore both */
4748 o_delchr(dest); /* undo insertion of '\' */
4749 continue;
4750 }
4751#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004752 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004753 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004754 continue;
4755 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004756 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004757 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004758 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004759}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004760#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004761
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004762/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004763#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004764#define parse_dollar(as_string, dest, input, quote_mask) \
4765 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004766#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004767#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004768static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004769 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004770 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004771{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004772 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004773
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004774 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004775 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004776 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004777 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004778 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004779 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004780 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004781 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004782 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004783 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004784 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004785 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004786 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004787 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004788 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004789 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004790 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004791 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004792 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004793 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004794 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004795 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004796 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004797 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004798 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004799 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004800 o_addchr(dest, ch | quote_mask);
4801 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004802 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004803 case '$': /* pid */
4804 case '!': /* last bg pid */
4805 case '?': /* last exit code */
4806 case '#': /* number of args */
4807 case '*': /* args */
4808 case '@': /* args */
4809 goto make_one_char_var;
4810 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004811 char len_single_ch;
4812
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004813 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4814
Denys Vlasenko74369502010-05-21 19:52:01 +02004815 ch = i_getch(input); /* eat '{' */
4816 nommu_addchr(as_string, ch);
4817
Denys Vlasenko46e64982016-09-29 19:50:55 +02004818 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004819 /* It should be ${?}, or ${#var},
4820 * or even ${?+subst} - operator acting on a special variable,
4821 * or the beginning of variable name.
4822 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004823 if (ch == EOF
4824 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4825 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004826 bad_dollar_syntax:
4827 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004828 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4829 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004830 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004831 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004832 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004833 ch |= quote_mask;
4834
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004835 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004836 * However, this regresses some of our testsuite cases
4837 * which check invalid constructs like ${%}.
4838 * Oh well... let's check that the var name part is fine... */
4839
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004840 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004841 unsigned pos;
4842
Denys Vlasenko74369502010-05-21 19:52:01 +02004843 o_addchr(dest, ch);
4844 debug_printf_parse(": '%c'\n", ch);
4845
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004846 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004847 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004848 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004849 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004850
Denys Vlasenko74369502010-05-21 19:52:01 +02004851 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004852 unsigned end_ch;
4853 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004854 /* handle parameter expansions
4855 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4856 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004857 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4858 if (len_single_ch != '#'
4859 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4860 || i_peek(input) != '}'
4861 ) {
4862 goto bad_dollar_syntax;
4863 }
4864 /* else: it's "length of C" ${#C} op,
4865 * where C is a single char
4866 * special var name, e.g. ${#!}.
4867 */
4868 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004869 /* Eat everything until closing '}' (or ':') */
4870 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004871 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004872 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004873 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004874 ) {
4875 /* It's ${var:N[:M]} thing */
4876 end_ch = '}' * 0x100 + ':';
4877 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004878 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004879 && ch == '/'
4880 ) {
4881 /* It's ${var/[/]pattern[/repl]} thing */
4882 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4883 i_getch(input);
4884 nommu_addchr(as_string, '/');
4885 ch = '\\';
4886 }
4887 end_ch = '}' * 0x100 + '/';
4888 }
4889 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004890 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004891 if (!BB_MMU)
4892 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004893#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004894 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004895 if (last_ch == 0) /* error? */
4896 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004897#else
4898#error Simple code to only allow ${var} is not implemented
4899#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004900 if (as_string) {
4901 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004902 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004903 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004904
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004905 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4906 && (end_ch & 0xff00)
4907 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004908 /* close the first block: */
4909 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004910 /* while parsing N from ${var:N[:M]}
4911 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004912 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004913 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004914 end_ch = '}';
4915 goto again;
4916 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004917 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004918 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004919 /* it's ${var:N} - emulate :999999999 */
4920 o_addstr(dest, "999999999");
4921 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004922 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004923 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004924 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004925 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004926 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004927 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4928 break;
4929 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004930#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004931 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004932 unsigned pos;
4933
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004934 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004935 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004936# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004937 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004938 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004939 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004940 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4941 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004942 if (!BB_MMU)
4943 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004944 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4945 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004946 if (as_string) {
4947 o_addstr(as_string, dest->data + pos);
4948 o_addchr(as_string, ')');
4949 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004950 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004951 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004952 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004953 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004954# endif
4955# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004956 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4957 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004958 if (!BB_MMU)
4959 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004960 if (!add_till_closing_bracket(dest, input, ')'))
4961 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004962 if (as_string) {
4963 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004964 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004965 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004966 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004967# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004968 break;
4969 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004970#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004971 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004972 goto make_var;
4973#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004974 /* TODO: $_ and $-: */
4975 /* $_ Shell or shell script name; or last argument of last command
4976 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4977 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004978 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004979 ch = i_getch(input);
4980 nommu_addchr(as_string, ch);
4981 ch = i_peek_and_eat_bkslash_nl(input);
4982 if (isalnum(ch)) { /* it's $_name or $_123 */
4983 ch = '_';
4984 goto make_var1;
4985 }
4986 /* else: it's $_ */
4987#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004988 default:
4989 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004990 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004991 debug_printf_parse("parse_dollar return 1 (ok)\n");
4992 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004993#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004994}
4995
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004996#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004997#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004998 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004999#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005000#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005001static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005002 o_string *dest,
5003 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005004 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005005{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005006 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005007 int next;
5008
5009 again:
5010 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005011 if (ch != EOF)
5012 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005013 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005014 debug_printf_parse("encode_string return 1 (ok)\n");
5015 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005016 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005017 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005018 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005019 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005020 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005021 }
5022 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005023 if (ch != '\n') {
5024 next = i_peek(input);
5025 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005026 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005027 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005028 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005029 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005030 /* Testcase: in interactive shell a file with
5031 * echo "unterminated string\<eof>
5032 * is sourced.
5033 */
5034 syntax_error_unterm_ch('"');
5035 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005036 }
5037 /* bash:
5038 * "The backslash retains its special meaning [in "..."]
5039 * only when followed by one of the following characters:
5040 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005041 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005042 * NB: in (unquoted) heredoc, above does not apply to ",
5043 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005044 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005045 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005046 ch = i_getch(input); /* eat next */
5047 if (ch == '\n')
5048 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005049 } /* else: ch remains == '\\', and we double it below: */
5050 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005051 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005052 goto again;
5053 }
5054 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005055 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5056 debug_printf_parse("encode_string return 0: "
5057 "parse_dollar returned 0 (error)\n");
5058 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005059 }
5060 goto again;
5061 }
5062#if ENABLE_HUSH_TICK
5063 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005064 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005065 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5066 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005067 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5068 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005069 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5070 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005071 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005072 }
5073#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005074 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005075 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005076#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005077}
5078
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005079/*
5080 * Scan input until EOF or end_trigger char.
5081 * Return a list of pipes to execute, or NULL on EOF
5082 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005083 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005084 * reset parsing machinery and start parsing anew,
5085 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005086 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005087static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005088 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005089 struct in_str *input,
5090 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005091{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005092 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005093 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005094
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005095 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005096 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005097 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005098 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005099 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005100 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005101
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005102 initialize_context(&ctx);
5103
5104 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5105 * Preventing this:
5106 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005107 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005108
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005109 /* We used to separate words on $IFS here. This was wrong.
5110 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005111 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005112 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005113
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005114 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005115 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005116 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005117 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005118 int ch;
5119 int next;
5120 int redir_fd;
5121 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005122
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005123 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005124 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005125 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005126 if (ch == EOF) {
5127 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005128
5129 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005130 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005131 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005132 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005133 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005134 syntax_error_unterm_ch('(');
5135 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005136 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005137 if (end_trigger == '}') {
5138 syntax_error_unterm_ch('{');
5139 goto parse_error;
5140 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005141
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005142 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005143 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005144 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005145 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005146 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005147 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005148 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005149 /* (this makes bare "&" cmd a no-op.
5150 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005151 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005152 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005153 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005154 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005155 pi = NULL;
5156 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005157#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005158 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005159 if (pstring)
5160 *pstring = ctx.as_string.data;
5161 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005162 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005163#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005164 // heredoc_cnt must be 0 here anyway
5165 //if (heredoc_cnt_ptr)
5166 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005167 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005168 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005169 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005170 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005171 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005172
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005173 /* Handle "'" and "\" first, as they won't play nice with
5174 * i_peek_and_eat_bkslash_nl() anyway:
5175 * echo z\\
5176 * and
5177 * echo '\
5178 * '
5179 * would break.
5180 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005181 if (ch == '\\') {
5182 ch = i_getch(input);
5183 if (ch == '\n')
5184 continue; /* drop \<newline>, get next char */
5185 nommu_addchr(&ctx.as_string, '\\');
5186 o_addchr(&ctx.word, '\\');
5187 if (ch == EOF) {
5188 /* Testcase: eval 'echo Ok\' */
5189 /* bash-4.3.43 was removing backslash,
5190 * but 4.4.19 retains it, most other shells too
5191 */
5192 continue; /* get next char */
5193 }
5194 /* Example: echo Hello \2>file
5195 * we need to know that word 2 is quoted
5196 */
5197 ctx.word.has_quoted_part = 1;
5198 nommu_addchr(&ctx.as_string, ch);
5199 o_addchr(&ctx.word, ch);
5200 continue; /* get next char */
5201 }
5202 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005203 if (ch == '\'') {
5204 ctx.word.has_quoted_part = 1;
5205 next = i_getch(input);
5206 if (next == '\'' && !ctx.pending_redirect)
5207 goto insert_empty_quoted_str_marker;
5208
5209 ch = next;
5210 while (1) {
5211 if (ch == EOF) {
5212 syntax_error_unterm_ch('\'');
5213 goto parse_error;
5214 }
5215 nommu_addchr(&ctx.as_string, ch);
5216 if (ch == '\'')
5217 break;
5218 if (ch == SPECIAL_VAR_SYMBOL) {
5219 /* Convert raw ^C to corresponding special variable reference */
5220 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5221 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5222 }
5223 o_addqchr(&ctx.word, ch);
5224 ch = i_getch(input);
5225 }
5226 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005227 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005228
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005229 next = '\0';
5230 if (ch != '\n')
5231 next = i_peek_and_eat_bkslash_nl(input);
5232
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005233 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005234 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005235 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005236 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005237 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005238 || ctx.word.length /* word{... - non-special */
5239 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005240 || (next != ';' /* }; - special */
5241 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005242 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005243 && next != '&' /* }& and }&& ... - special */
5244 && next != '|' /* }|| ... - special */
5245 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005246 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005247 ) {
5248 /* They are not special, skip "{}" */
5249 is_special += 2;
5250 }
5251 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005252 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005253
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005254 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005255 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005256 o_addQchr(&ctx.word, ch);
5257 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5258 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005259 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005260 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005261 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005262 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5263 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005264 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005265 continue;
5266 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005267
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005268 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005269#if ENABLE_HUSH_LINENO_VAR
5270/* Case:
5271 * "while ...; do<whitespace><newline>
5272 * cmd ..."
5273 * would think that "cmd" starts in <whitespace> -
5274 * i.e., at the previous line.
5275 * We need to skip all whitespace before newlines.
5276 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005277 while (ch != '\n') {
5278 next = i_peek(input);
5279 if (next != ' ' && next != '\t' && next != '\n')
5280 break; /* next char is not ws */
5281 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005282 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005283 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005284#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005285 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005286 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005287 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005288 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005289 /* Is this a case when newline is simply ignored?
5290 * Some examples:
5291 * "cmd | <newline> cmd ..."
5292 * "case ... in <newline> word) ..."
5293 */
5294 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005295 && ctx.word.length == 0
5296 && !ctx.word.has_quoted_part
5297 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005298 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005299 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005300 * Without check #1, interactive shell
5301 * ignores even bare <newline>,
5302 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005303 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005304 * ps2> _ <=== wrong, should be ps1
5305 * Without check #2, "cmd & <newline>"
5306 * is similarly mistreated.
5307 * (BTW, this makes "cmd & cmd"
5308 * and "cmd && cmd" non-orthogonal.
5309 * Really, ask yourself, why
5310 * "cmd && <newline>" doesn't start
5311 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005312 * The only reason is that it might be
5313 * a "cmd1 && <nl> cmd2 &" construct,
5314 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005315 */
5316 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005317 if (pi->num_cmds != 0 /* check #1 */
5318 && pi->followup != PIPE_BG /* check #2 */
5319 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005320 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005321 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005322 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005323 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005324 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005325 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005326 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005327 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5328 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005329 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005330 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005331 ctx.is_assignment = MAYBE_ASSIGNMENT;
5332 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005333 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005334 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005335 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005336 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005337 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005338
5339 /* "cmd}" or "cmd }..." without semicolon or &:
5340 * } is an ordinary char in this case, even inside { cmd; }
5341 * Pathological example: { ""}; } should exec "}" cmd
5342 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005343 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005344 if (ctx.word.length != 0 /* word} */
5345 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005346 ) {
5347 goto ordinary_char;
5348 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005349 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5350 /* Generally, there should be semicolon: "cmd; }"
5351 * However, bash allows to omit it if "cmd" is
5352 * a group. Examples:
5353 * { { echo 1; } }
5354 * {(echo 1)}
5355 * { echo 0 >&2 | { echo 1; } }
5356 * { while false; do :; done }
5357 * { case a in b) ;; esac }
5358 */
5359 if (ctx.command->group)
5360 goto term_group;
5361 goto ordinary_char;
5362 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005363 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005364 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005365 goto skip_end_trigger;
5366 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005367 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005368 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005369 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005370 && (ch != ';' || heredoc_cnt == 0)
5371#if ENABLE_HUSH_CASE
5372 && (ch != ')'
5373 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005374 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005375 )
5376#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005377 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005378 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005379 goto parse_error;
5380 }
5381 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005382 ctx.is_assignment = MAYBE_ASSIGNMENT;
5383 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005384 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005385 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005386 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005387 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005388 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005389#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005390 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005391 if (pstring)
5392 *pstring = ctx.as_string.data;
5393 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005394 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005395#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005396 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5397 /* Example: bare "{ }", "()" */
5398 G.last_exitcode = 2; /* bash compat */
5399 syntax_error_unexpected_ch(ch);
5400 goto parse_error2;
5401 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005402 if (heredoc_cnt_ptr)
5403 *heredoc_cnt_ptr = heredoc_cnt;
5404 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005405 debug_printf_parse("parse_stream return %p: "
5406 "end_trigger char found\n",
5407 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005408 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005409 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005410 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005411 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005412
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005413 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005414 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005415
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005416 /* Catch <, > before deciding whether this word is
5417 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5418 switch (ch) {
5419 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005420 redir_fd = redirect_opt_num(&ctx.word);
5421 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005422 goto parse_error;
5423 }
5424 redir_style = REDIRECT_OVERWRITE;
5425 if (next == '>') {
5426 redir_style = REDIRECT_APPEND;
5427 ch = i_getch(input);
5428 nommu_addchr(&ctx.as_string, ch);
5429 }
5430#if 0
5431 else if (next == '(') {
5432 syntax_error(">(process) not supported");
5433 goto parse_error;
5434 }
5435#endif
5436 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5437 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005438 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005439 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005440 redir_fd = redirect_opt_num(&ctx.word);
5441 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005442 goto parse_error;
5443 }
5444 redir_style = REDIRECT_INPUT;
5445 if (next == '<') {
5446 redir_style = REDIRECT_HEREDOC;
5447 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005448 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005449 ch = i_getch(input);
5450 nommu_addchr(&ctx.as_string, ch);
5451 } else if (next == '>') {
5452 redir_style = REDIRECT_IO;
5453 ch = i_getch(input);
5454 nommu_addchr(&ctx.as_string, ch);
5455 }
5456#if 0
5457 else if (next == '(') {
5458 syntax_error("<(process) not supported");
5459 goto parse_error;
5460 }
5461#endif
5462 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5463 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005464 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005465 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005466 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005467 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005468 /* note: we do not add it to &ctx.as_string */
5469/* TODO: in bash:
5470 * comment inside $() goes to the next \n, even inside quoted string (!):
5471 * cmd "$(cmd2 #comment)" - syntax error
5472 * cmd "`cmd2 #comment`" - ok
5473 * We accept both (comment ends where command subst ends, in both cases).
5474 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005475 while (1) {
5476 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005477 if (ch == '\n') {
5478 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005479 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005480 }
5481 ch = i_getch(input);
5482 if (ch == EOF)
5483 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005484 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005485 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005486 }
5487 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005488 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005489 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005490
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005491 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005492 /* check that we are not in word in "a=1 2>word b=1": */
5493 && !ctx.pending_redirect
5494 ) {
5495 /* ch is a special char and thus this word
5496 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005497 ctx.is_assignment = NOT_ASSIGNMENT;
5498 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005499 }
5500
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005501 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5502
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005503 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005504 case SPECIAL_VAR_SYMBOL:
5505 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005506 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5507 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005508 /* fall through */
5509 case '#':
5510 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005511 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005512 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005513 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005514 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005515 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005516 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005517 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005518 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005519 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005520 case '"':
5521 ctx.word.has_quoted_part = 1;
5522 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005523 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005524 insert_empty_quoted_str_marker:
5525 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005526 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5527 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005528 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005529 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005530 if (ctx.is_assignment == NOT_ASSIGNMENT)
5531 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005532 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005533 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005534 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005535 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005536#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005537 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005538 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005539
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005540 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5541 o_addchr(&ctx.word, '`');
5542 USE_FOR_NOMMU(pos = ctx.word.length;)
5543 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005544 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005545# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005546 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005547 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005548# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005549 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5550 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005551 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005552 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005553#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005554 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005555#if ENABLE_HUSH_CASE
5556 case_semi:
5557#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005558 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005559 goto parse_error;
5560 }
5561 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005562#if ENABLE_HUSH_CASE
5563 /* Eat multiple semicolons, detect
5564 * whether it means something special */
5565 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005566 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005567 if (ch != ';')
5568 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005569 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005570 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005571 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005572 ctx.ctx_dsemicolon = 1;
5573 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005574 break;
5575 }
5576 }
5577#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005578 new_cmd:
5579 /* We just finished a cmd. New one may start
5580 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005581 ctx.is_assignment = MAYBE_ASSIGNMENT;
5582 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005583 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005584 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005585 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005586 goto parse_error;
5587 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005588 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005589 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005590 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005591 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005592 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005593 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005594 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005595 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005596 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005597 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005598 goto parse_error;
5599 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005600#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005601 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005602 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005603#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005604 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005606 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005607 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005608 } else {
5609 /* we could pick up a file descriptor choice here
5610 * with redirect_opt_num(), but bash doesn't do it.
5611 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005612 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005613 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005614 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005615 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005616#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005617 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005618 if (ctx.ctx_res_w == RES_MATCH
5619 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005620 && ctx.word.length == 0 /* not word(... */
5621 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005622 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005623 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005624 }
5625#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005626 /* fall through */
5627 case '{': {
5628 int n = parse_group(&ctx, input, ch);
5629 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005630 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005631 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005632 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5633 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005634 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005635 }
Eric Andersen25f27032001-04-26 23:22:31 +00005636 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005637#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005638 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005639 goto case_semi;
5640#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005641
Eric Andersen25f27032001-04-26 23:22:31 +00005642 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005643 /* proper use of this character is caught by end_trigger:
5644 * if we see {, we call parse_group(..., end_trigger='}')
5645 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005646 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005647 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005648 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005649 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005650 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005651 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005652 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005653 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005654
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005655 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005656 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005657 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005658 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005659 struct parse_context *pctx;
5660 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005661
5662 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005663 * Sample for finding leaks on syntax error recovery path.
5664 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005665 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005666 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005667 * while if (true | { true;}); then echo ok; fi; do break; done
5668 * 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 +00005669 */
5670 pctx = &ctx;
5671 do {
5672 /* Update pipe/command counts,
5673 * otherwise freeing may miss some */
5674 done_pipe(pctx, PIPE_SEQ);
5675 debug_printf_clean("freeing list %p from ctx %p\n",
5676 pctx->list_head, pctx);
5677 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005678 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005679 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005680#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005681 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005682#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005683 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005684 if (pctx != &ctx) {
5685 free(pctx);
5686 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005687 IF_HAS_KEYWORDS(pctx = p2;)
5688 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005689
Denys Vlasenko474cb202018-07-24 13:03:03 +02005690 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005691#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005692 if (pstring)
5693 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005694#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005695 debug_leave();
5696 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005697 }
Eric Andersen25f27032001-04-26 23:22:31 +00005698}
5699
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005700
5701/*** Execution routines ***/
5702
5703/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005704#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005705#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005706 expand_string_to_string(str)
5707#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005708static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005709#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005711#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005712static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713
5714/* expand_strvec_to_strvec() takes a list of strings, expands
5715 * all variable references within and returns a pointer to
5716 * a list of expanded strings, possibly with larger number
5717 * of strings. (Think VAR="a b"; echo $VAR).
5718 * This new list is allocated as a single malloc block.
5719 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005720 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005721 * Caller can deallocate entire list by single free(list). */
5722
Denys Vlasenko238081f2010-10-03 14:26:26 +02005723/* A horde of its helpers come first: */
5724
5725static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5726{
5727 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005728 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005729
Denys Vlasenko9e800222010-10-03 14:28:04 +02005730#if ENABLE_HUSH_BRACE_EXPANSION
5731 if (c == '{' || c == '}') {
5732 /* { -> \{, } -> \} */
5733 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005734 /* And now we want to add { or } and continue:
5735 * o_addchr(o, c);
5736 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005737 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005738 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005739 }
5740#endif
5741 o_addchr(o, c);
5742 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005743 /* \z -> \\\z; \<eol> -> \\<eol> */
5744 o_addchr(o, '\\');
5745 if (len) {
5746 len--;
5747 o_addchr(o, '\\');
5748 o_addchr(o, *str++);
5749 }
5750 }
5751 }
5752}
5753
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005754/* Store given string, finalizing the word and starting new one whenever
5755 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005756 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005757 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005758 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5759 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005760static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005761{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005762 int last_is_ifs = 0;
5763
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005765 int word_len;
5766
5767 if (!*str) /* EOL - do not finalize word */
5768 break;
5769 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005770 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005771 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005772 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005773 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005774 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005775 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005776 * Example: "v='\*'; echo b$v" prints "b\*"
5777 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005778 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005779 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005780 /*/ Why can't we do it easier? */
5781 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5782 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5783 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005784 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005785 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005786 if (!*str) /* EOL - do not finalize word */
5787 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005788 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005789
5790 /* We know str here points to at least one IFS char */
5791 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005792 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005793 if (!*str) /* EOL - do not finalize word */
5794 break;
5795
Denys Vlasenko96786362018-04-11 16:02:58 +02005796 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5797 && strchr(G.ifs, *str) /* the second check would fail */
5798 ) {
5799 /* This is a non-whitespace $IFS char */
5800 /* Skip it and IFS whitespace chars, start new word */
5801 str++;
5802 str += strspn(str, G.ifs_whitespace);
5803 goto new_word;
5804 }
5805
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005806 /* Start new word... but not always! */
5807 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005808 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005809 /*
5810 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005811 * here nothing precedes the space in $v expansion,
5812 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005813 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005814 * It's okay if this accesses the byte before first argv[]:
5815 * past call to o_save_ptr() cleared it to zero byte
5816 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005817 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005818 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005819 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005820 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005821 o_addchr(output, '\0');
5822 debug_print_list("expand_on_ifs", output, n);
5823 n = o_save_ptr(output, n);
5824 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005825 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005826
Denys Vlasenko168579a2018-07-19 13:45:54 +02005827 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828 debug_print_list("expand_on_ifs[1]", output, n);
5829 return n;
5830}
5831
5832/* Helper to expand $((...)) and heredoc body. These act as if
5833 * they are in double quotes, with the exception that they are not :).
5834 * Just the rules are similar: "expand only $var and `cmd`"
5835 *
5836 * Returns malloced string.
5837 * As an optimization, we return NULL if expansion is not needed.
5838 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005839static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005840{
5841 char *exp_str;
5842 struct in_str input;
5843 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005844 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005845
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005846 cp = str;
5847 for (;;) {
5848 if (!*cp) return NULL; /* string has no special chars */
5849 if (*cp == '$') break;
5850 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005851#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005852 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005853#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005854 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005855 }
5856
5857 /* We need to expand. Example:
5858 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5859 */
5860 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005861 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005862//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005863 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005864 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005865 EXP_FLAG_ESC_GLOB_CHARS,
5866 /*unbackslash:*/ 1
5867 );
5868 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005869 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005870 return exp_str;
5871}
5872
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005873/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5874 * These can contain single- and double-quoted strings,
5875 * and treated as if the ARG string is initially unquoted. IOW:
5876 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5877 * a dquoted string: "${var#"zz"}"), the difference only comes later
5878 * (word splitting and globbing of the ${var...} result).
5879 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005880#if !BASH_PATTERN_SUBST
5881#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5882 encode_then_expand_vararg(str, handle_squotes)
5883#endif
5884static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5885{
5886#if !BASH_PATTERN_SUBST
5887 const int do_unbackslash = 0;
5888#endif
5889 char *exp_str;
5890 struct in_str input;
5891 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005892 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005893
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005894 cp = str;
5895 for (;;) {
5896 if (!*cp) return NULL; /* string has no special chars */
5897 if (*cp == '$') break;
5898 if (*cp == '\\') break;
5899 if (*cp == '\'') break;
5900 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005901#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005902 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005903#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005904 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005905 }
5906
Denys Vlasenkob762c782018-07-17 14:21:38 +02005907 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005908 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005909 exp_str = NULL;
5910
5911 for (;;) {
5912 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005913
5914 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005915 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5916 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005917
5918 if (!dest.o_expflags) {
5919 if (ch == EOF)
5920 break;
5921 if (handle_squotes && ch == '\'') {
5922 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02005923 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005924 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005925 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005926 }
5927 if (ch == EOF) {
5928 syntax_error_unterm_ch('"');
5929 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005930 }
5931 if (ch == '"') {
5932 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5933 continue;
5934 }
5935 if (ch == '\\') {
5936 ch = i_getch(&input);
5937 if (ch == EOF) {
5938//example? error message? syntax_error_unterm_ch('"');
5939 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5940 goto ret;
5941 }
5942 o_addqchr(&dest, ch);
5943 continue;
5944 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005945 if (ch == '$') {
5946 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5947 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5948 goto ret;
5949 }
5950 continue;
5951 }
5952#if ENABLE_HUSH_TICK
5953 if (ch == '`') {
5954 //unsigned pos = dest->length;
5955 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5956 o_addchr(&dest, 0x80 | '`');
5957 if (!add_till_backquote(&dest, &input,
5958 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5959 )
5960 ) {
5961 goto ret; /* error */
5962 }
5963 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5964 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5965 continue;
5966 }
5967#endif
5968 o_addQchr(&dest, ch);
5969 } /* for (;;) */
5970
5971 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5972 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005973 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5974 do_unbackslash
5975 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005976 ret:
5977 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005978 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005979 return exp_str;
5980}
5981
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005982/* Expanding ARG in ${var+ARG}, ${var-ARG}
5983 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02005984static int encode_then_append_var_plusminus(o_string *output, int n,
5985 const char *str, int dquoted)
5986{
5987 struct in_str input;
5988 o_string dest = NULL_O_STRING;
5989
5990#if 0 //todo?
5991 const char *cp;
5992 cp = str;
5993 for (;;) {
5994 if (!*cp) return NULL; /* string has no special chars */
5995 if (*cp == '$') break;
5996 if (*cp == '\\') break;
5997 if (*cp == '\'') break;
5998 if (*cp == '"') break;
5999#if ENABLE_HUSH_TICK
6000 if (*cp == '`') break;
6001#endif
6002 cp++;
6003 }
6004#endif
6005
Denys Vlasenko294eb462018-07-20 16:18:59 +02006006 setup_string_in_str(&input, str);
6007
6008 for (;;) {
6009 int ch;
6010
6011 ch = i_getch(&input);
6012 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6013 __func__, ch, ch, dest.o_expflags);
6014
6015 if (!dest.o_expflags) {
6016 if (ch == EOF)
6017 break;
6018 if (!dquoted && strchr(G.ifs, ch)) {
6019 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6020 * do not assume we are at the start of the word (PREFIX above).
6021 */
6022 if (dest.data) {
6023 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006024 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006025 o_addchr(output, '\0');
6026 n = o_save_ptr(output, n); /* create next word */
6027 } else
6028 if (output->length != o_get_last_ptr(output, n)
6029 || output->has_quoted_part
6030 ) {
6031 /* For these cases:
6032 * f() { for i; do echo "|$i|"; done; }; x=x
6033 * f a${x:+ }b # 1st condition
6034 * |a|
6035 * |b|
6036 * f ""${x:+ }b # 2nd condition
6037 * ||
6038 * |b|
6039 */
6040 o_addchr(output, '\0');
6041 n = o_save_ptr(output, n); /* create next word */
6042 }
6043 continue;
6044 }
6045 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006046 if (!add_till_single_quote_dquoted(&dest, &input))
6047 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006048 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6049 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006050 continue;
6051 }
6052 }
6053 if (ch == EOF) {
6054 syntax_error_unterm_ch('"');
6055 goto ret; /* error */
6056 }
6057 if (ch == '"') {
6058 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006059 if (dest.o_expflags) {
6060 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6061 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6062 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006063 continue;
6064 }
6065 if (ch == '\\') {
6066 ch = i_getch(&input);
6067 if (ch == EOF) {
6068//example? error message? syntax_error_unterm_ch('"');
6069 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6070 goto ret;
6071 }
6072 o_addqchr(&dest, ch);
6073 continue;
6074 }
6075 if (ch == '$') {
6076 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6077 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6078 goto ret;
6079 }
6080 continue;
6081 }
6082#if ENABLE_HUSH_TICK
6083 if (ch == '`') {
6084 //unsigned pos = dest->length;
6085 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6086 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6087 if (!add_till_backquote(&dest, &input,
6088 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6089 )
6090 ) {
6091 goto ret; /* error */
6092 }
6093 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6094 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6095 continue;
6096 }
6097#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006098 if (dquoted) {
6099 /* Always glob-protect if in dquotes:
6100 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6101 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6102 */
6103 o_addqchr(&dest, ch);
6104 } else {
6105 /* Glob-protect only if char is quoted:
6106 * x=x; echo ${x:+/bin/c*} - prints many filenames
6107 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6108 */
6109 o_addQchr(&dest, ch);
6110 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006111 } /* for (;;) */
6112
6113 if (dest.data) {
6114 n = expand_vars_to_list(output, n, dest.data);
6115 }
6116 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006117 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006118 return n;
6119}
6120
Denys Vlasenko0b883582016-12-23 16:49:07 +01006121#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006122static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006124 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006125 arith_t res;
6126 char *exp_str;
6127
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006128 math_state.lookupvar = get_local_var_value;
6129 math_state.setvar = set_local_var_from_halves;
6130 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006131 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006132 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006133 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006134 if (errmsg_p)
6135 *errmsg_p = math_state.errmsg;
6136 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006137 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 return res;
6139}
6140#endif
6141
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006142#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006143/* ${var/[/]pattern[/repl]} helpers */
6144static char *strstr_pattern(char *val, const char *pattern, int *size)
6145{
6146 while (1) {
6147 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6148 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6149 if (end) {
6150 *size = end - val;
6151 return val;
6152 }
6153 if (*val == '\0')
6154 return NULL;
6155 /* Optimization: if "*pat" did not match the start of "string",
6156 * we know that "tring", "ring" etc will not match too:
6157 */
6158 if (pattern[0] == '*')
6159 return NULL;
6160 val++;
6161 }
6162}
6163static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6164{
6165 char *result = NULL;
6166 unsigned res_len = 0;
6167 unsigned repl_len = strlen(repl);
6168
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006169 /* Null pattern never matches, including if "var" is empty */
6170 if (!pattern[0])
6171 return result; /* NULL, no replaces happened */
6172
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006173 while (1) {
6174 int size;
6175 char *s = strstr_pattern(val, pattern, &size);
6176 if (!s)
6177 break;
6178
6179 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006180 strcpy(mempcpy(result + res_len, val, s - val), repl);
6181 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6183
6184 val = s + size;
6185 if (exp_op == '/')
6186 break;
6187 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006188 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006189 result = xrealloc(result, res_len + strlen(val) + 1);
6190 strcpy(result + res_len, val);
6191 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6192 }
6193 debug_printf_varexp("result:'%s'\n", result);
6194 return result;
6195}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006196#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197
Denys Vlasenko168579a2018-07-19 13:45:54 +02006198static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006199 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006200{
6201 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6202 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6203 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6204 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006205 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006206 } else { /* quoted "$VAR" */
6207 output->has_quoted_part = 1;
6208 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6209 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6210 if (val && val[0])
6211 o_addQstr(output, val);
6212 }
6213 return n;
6214}
6215
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006216/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006217 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006218static NOINLINE int expand_one_var(o_string *output, int n,
6219 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006220{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006221 const char *val;
6222 char *to_be_freed;
6223 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006224 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006225 char exp_op;
6226 char exp_save = exp_save; /* for compiler */
6227 char *exp_saveptr; /* points to expansion operator */
6228 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006229 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006230
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006231 val = NULL;
6232 to_be_freed = NULL;
6233 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006234 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006235 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006236 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006237 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006238 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006239 exp_op = 0;
6240
Denys Vlasenkob762c782018-07-17 14:21:38 +02006241 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006242 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6243 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6244 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006245 ) {
6246 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006247 var++;
6248 exp_op = 'L';
6249 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006250 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006251 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006252 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006253 ) {
6254 /* ${?:0}, ${#[:]%0} etc */
6255 exp_saveptr = var + 1;
6256 } else {
6257 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6258 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6259 }
6260 exp_op = exp_save = *exp_saveptr;
6261 if (exp_op) {
6262 exp_word = exp_saveptr + 1;
6263 if (exp_op == ':') {
6264 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006265//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006266 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006267 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268 ) {
6269 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6270 exp_op = ':';
6271 exp_word--;
6272 }
6273 }
6274 *exp_saveptr = '\0';
6275 } /* else: it's not an expansion op, but bare ${var} */
6276 }
6277
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006278 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006280 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006281 int nn = xatoi_positive(var);
6282 if (nn < G.global_argc)
6283 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284 /* else val remains NULL: $N with too big N */
6285 } else {
6286 switch (var[0]) {
6287 case '$': /* pid */
6288 val = utoa(G.root_pid);
6289 break;
6290 case '!': /* bg pid */
6291 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6292 break;
6293 case '?': /* exitcode */
6294 val = utoa(G.last_exitcode);
6295 break;
6296 case '#': /* argc */
6297 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6298 break;
6299 default:
6300 val = get_local_var_value(var);
6301 }
6302 }
6303
6304 /* Handle any expansions */
6305 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006306 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006307 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006308 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006309 debug_printf_expand("%s\n", val);
6310 } else if (exp_op) {
6311 if (exp_op == '%' || exp_op == '#') {
6312 /* Standard-mandated substring removal ops:
6313 * ${parameter%word} - remove smallest suffix pattern
6314 * ${parameter%%word} - remove largest suffix pattern
6315 * ${parameter#word} - remove smallest prefix pattern
6316 * ${parameter##word} - remove largest prefix pattern
6317 *
6318 * Word is expanded to produce a glob pattern.
6319 * Then var's value is matched to it and matching part removed.
6320 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006321//FIXME: ${x#...${...}...}
6322//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6323//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006325 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 char *exp_exp_word;
6327 char *loc;
6328 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006329 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006330 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006331 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006332 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006333 if (exp_exp_word)
6334 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006335 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6336 /*
6337 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006338 * G.global_argv and results of utoa and get_local_var_value
6339 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006340 * scan_and_match momentarily stores NULs there.
6341 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006342 t = (char*)val;
6343 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006344 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 +02006345 free(exp_exp_word);
6346 if (loc) { /* match was found */
6347 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006348 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006350 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006351 }
6352 }
6353 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006354#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006356 /* It's ${var/[/]pattern[/repl]} thing.
6357 * Note that in encoded form it has TWO parts:
6358 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006359 * and if // is used, it is encoded as \:
6360 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006361 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006362 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006363 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006364 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006365 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006366 * >az >bz
6367 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6368 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6369 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6370 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006371 * (note that a*z _pattern_ is never globbed!)
6372 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006373 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006374 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375 if (!pattern)
6376 pattern = xstrdup(exp_word);
6377 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6378 *p++ = SPECIAL_VAR_SYMBOL;
6379 exp_word = p;
6380 p = strchr(p, SPECIAL_VAR_SYMBOL);
6381 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006382 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006383 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6384 /* HACK ALERT. We depend here on the fact that
6385 * G.global_argv and results of utoa and get_local_var_value
6386 * are actually in writable memory:
6387 * replace_pattern momentarily stores NULs there. */
6388 t = (char*)val;
6389 to_be_freed = replace_pattern(t,
6390 pattern,
6391 (repl ? repl : exp_word),
6392 exp_op);
6393 if (to_be_freed) /* at least one replace happened */
6394 val = to_be_freed;
6395 free(pattern);
6396 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006397 } else {
6398 /* Empty variable always gives nothing */
6399 // "v=''; echo ${v/*/w}" prints "", not "w"
6400 /* Just skip "replace" part */
6401 *p++ = SPECIAL_VAR_SYMBOL;
6402 p = strchr(p, SPECIAL_VAR_SYMBOL);
6403 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006404 }
6405 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006406#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006407 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006408#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006409 /* It's ${var:N[:M]} bashism.
6410 * Note that in encoded form it has TWO parts:
6411 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6412 */
6413 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006414 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006415
Denys Vlasenko063847d2010-09-15 13:33:02 +02006416 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6417 if (errmsg)
6418 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006419 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6420 *p++ = SPECIAL_VAR_SYMBOL;
6421 exp_word = p;
6422 p = strchr(p, SPECIAL_VAR_SYMBOL);
6423 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006424 len = expand_and_evaluate_arith(exp_word, &errmsg);
6425 if (errmsg)
6426 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006427 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006428 if (beg < 0) {
6429 /* negative beg counts from the end */
6430 beg = (arith_t)strlen(val) + beg;
6431 if (beg < 0) /* ${v: -999999} is "" */
6432 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006433 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006434 debug_printf_varexp("from val:'%s'\n", val);
6435 if (len < 0) {
6436 /* in bash, len=-n means strlen()-n */
6437 len = (arith_t)strlen(val) - beg + len;
6438 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006439 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006440 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006441 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006442 arith_err:
6443 val = NULL;
6444 } else {
6445 /* Paranoia. What if user entered 9999999999999
6446 * which fits in arith_t but not int? */
6447 if (len >= INT_MAX)
6448 len = INT_MAX;
6449 val = to_be_freed = xstrndup(val + beg, len);
6450 }
6451 debug_printf_varexp("val:'%s'\n", val);
6452#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006453 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006454 val = NULL;
6455#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006456 } else { /* one of "-=+?" */
6457 /* Standard-mandated substitution ops:
6458 * ${var?word} - indicate error if unset
6459 * If var is unset, word (or a message indicating it is unset
6460 * if word is null) is written to standard error
6461 * and the shell exits with a non-zero exit status.
6462 * Otherwise, the value of var is substituted.
6463 * ${var-word} - use default value
6464 * If var is unset, word is substituted.
6465 * ${var=word} - assign and use default value
6466 * If var is unset, word is assigned to var.
6467 * In all cases, final value of var is substituted.
6468 * ${var+word} - use alternative value
6469 * If var is unset, null is substituted.
6470 * Otherwise, word is substituted.
6471 *
6472 * Word is subjected to tilde expansion, parameter expansion,
6473 * command substitution, and arithmetic expansion.
6474 * If word is not needed, it is not expanded.
6475 *
6476 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6477 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006478 *
6479 * Word-splitting and single quote behavior:
6480 *
6481 * $ f() { for i; do echo "|$i|"; done; };
6482 *
6483 * $ x=; f ${x:?'x y' z}
6484 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6485 * $ x=; f "${x:?'x y' z}"
6486 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6487 *
6488 * $ x=; f ${x:='x y' z}
6489 * |x|
6490 * |y|
6491 * |z|
6492 * $ x=; f "${x:='x y' z}"
6493 * |'x y' z|
6494 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006495 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006496 * |x y|
6497 * |z|
6498 * $ x=x; f "${x:+'x y' z}"
6499 * |'x y' z|
6500 *
6501 * $ x=; f ${x:-'x y' z}
6502 * |x y|
6503 * |z|
6504 * $ x=; f "${x:-'x y' z}"
6505 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006506 */
6507 int use_word = (!val || ((exp_save == ':') && !val[0]));
6508 if (exp_op == '+')
6509 use_word = !use_word;
6510 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6511 (exp_save == ':') ? "true" : "false", use_word);
6512 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006513 if (exp_op == '+' || exp_op == '-') {
6514 /* ${var+word} - use alternative value */
6515 /* ${var-word} - use default value */
6516 n = encode_then_append_var_plusminus(output, n, exp_word,
6517 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006518 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006519 val = NULL;
6520 } else {
6521 /* ${var?word} - indicate error if unset */
6522 /* ${var=word} - assign and use default value */
6523 to_be_freed = encode_then_expand_vararg(exp_word,
6524 /*handle_squotes:*/ !(arg0 & 0x80),
6525 /*unbackslash:*/ 0
6526 );
6527 if (to_be_freed)
6528 exp_word = to_be_freed;
6529 if (exp_op == '?') {
6530 /* mimic bash message */
6531 msg_and_die_if_script("%s: %s",
6532 var,
6533 exp_word[0]
6534 ? exp_word
6535 : "parameter null or not set"
6536 /* ash has more specific messages, a-la: */
6537 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6538 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006539//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006540//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006541// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6542// bash: x: x y z
6543// $
6544// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006545 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006546 val = exp_word;
6547 }
6548 if (exp_op == '=') {
6549 /* ${var=[word]} or ${var:=[word]} */
6550 if (isdigit(var[0]) || var[0] == '#') {
6551 /* mimic bash message */
6552 msg_and_die_if_script("$%s: cannot assign in this way", var);
6553 val = NULL;
6554 } else {
6555 char *new_var = xasprintf("%s=%s", var, val);
6556 set_local_var(new_var, /*flag:*/ 0);
6557 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 }
6559 }
6560 }
6561 } /* one of "-=+?" */
6562
6563 *exp_saveptr = exp_save;
6564 } /* if (exp_op) */
6565
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006566 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006568
Denys Vlasenko168579a2018-07-19 13:45:54 +02006569 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006570
6571 free(to_be_freed);
6572 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006573}
6574
6575/* Expand all variable references in given string, adding words to list[]
6576 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6577 * to be filled). This routine is extremely tricky: has to deal with
6578 * variables/parameters with whitespace, $* and $@, and constructs like
6579 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006580static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006581{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006582 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006583 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006585 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 char *p;
6587
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006588 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6589 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006590 debug_print_list("expand_vars_to_list[0]", output, n);
6591
6592 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6593 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006594#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006595 char arith_buf[sizeof(arith_t)*3 + 2];
6596#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006597
Denys Vlasenko168579a2018-07-19 13:45:54 +02006598 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006599 o_addchr(output, '\0');
6600 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006601 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006602 }
6603
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006604 o_addblock(output, arg, p - arg);
6605 debug_print_list("expand_vars_to_list[1]", output, n);
6606 arg = ++p;
6607 p = strchr(p, SPECIAL_VAR_SYMBOL);
6608
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006609 /* Fetch special var name (if it is indeed one of them)
6610 * and quote bit, force the bit on if singleword expansion -
6611 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006612 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006613
6614 /* Is this variable quoted and thus expansion can't be null?
6615 * "$@" is special. Even if quoted, it can still
6616 * expand to nothing (not even an empty string),
6617 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006619 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620
6621 switch (first_ch & 0x7f) {
6622 /* Highest bit in first_ch indicates that var is double-quoted */
6623 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006624 case '@': {
6625 int i;
6626 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006627 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006628 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006629 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006630 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006631 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006632 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006633 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6634 if (G.global_argv[i++][0] && G.global_argv[i]) {
6635 /* this argv[] is not empty and not last:
6636 * put terminating NUL, start new word */
6637 o_addchr(output, '\0');
6638 debug_print_list("expand_vars_to_list[2]", output, n);
6639 n = o_save_ptr(output, n);
6640 debug_print_list("expand_vars_to_list[3]", output, n);
6641 }
6642 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006643 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006644 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006645 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006646 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006647 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006648 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649 while (1) {
6650 o_addQstr(output, G.global_argv[i]);
6651 if (++i >= G.global_argc)
6652 break;
6653 o_addchr(output, '\0');
6654 debug_print_list("expand_vars_to_list[4]", output, n);
6655 n = o_save_ptr(output, n);
6656 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006657 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006658 while (1) {
6659 o_addQstr(output, G.global_argv[i]);
6660 if (!G.global_argv[++i])
6661 break;
6662 if (G.ifs[0])
6663 o_addchr(output, G.ifs[0]);
6664 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006665 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006666 }
6667 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006668 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006669 case SPECIAL_VAR_SYMBOL: {
6670 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006671 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006672 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006673 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006674 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006675 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006676 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006677 case SPECIAL_VAR_QUOTED_SVS:
6678 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006679 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006680 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006681 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006682 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006683#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006684 case '`': {
6685 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006686 o_string subst_result = NULL_O_STRING;
6687
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006688 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 arg++;
6690 /* Can't just stuff it into output o_string,
6691 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006692 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6694 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006695 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006696 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006697 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006698 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006699 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006700 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006701#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006702#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006703 case '+': {
6704 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006705 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006706
6707 arg++; /* skip '+' */
6708 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6709 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006710 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006711 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6712 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006713 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 break;
6715 }
6716#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006717 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006718 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006719 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006720 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006721 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6722
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006723 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6724 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006725 if (*p != SPECIAL_VAR_SYMBOL)
6726 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006727 arg = ++p;
6728 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6729
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006730 if (*arg) {
6731 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006732 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006733 o_addchr(output, '\0');
6734 n = o_save_ptr(output, n);
6735 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006736 debug_print_list("expand_vars_to_list[a]", output, n);
6737 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006738 * if needed (much earlier), do not use o_addQstr here!
6739 */
6740 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006741 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006742 } else
6743 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006744 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6745 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006746 ) {
6747 n--;
6748 /* allow to reuse list[n] later without re-growth */
6749 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006750 }
6751
6752 return n;
6753}
6754
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006755static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006756{
6757 int n;
6758 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006759 o_string output = NULL_O_STRING;
6760
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006761 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762
6763 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006764 for (;;) {
6765 /* go to next list[n] */
6766 output.ended_in_ifs = 0;
6767 n = o_save_ptr(&output, n);
6768
6769 if (!*argv)
6770 break;
6771
6772 /* expand argv[i] */
6773 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006774 /* if (!output->has_empty_slot) -- need this?? */
6775 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006776 }
6777 debug_print_list("expand_variables", &output, n);
6778
6779 /* output.data (malloced in one block) gets returned in "list" */
6780 list = o_finalize_list(&output, n);
6781 debug_print_strings("expand_variables[1]", list);
6782 return list;
6783}
6784
6785static char **expand_strvec_to_strvec(char **argv)
6786{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006787 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788}
6789
Denys Vlasenko11752d42018-04-03 08:20:58 +02006790#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006791static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6792{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006793 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006794}
6795#endif
6796
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006797/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006798 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006799 *
6800 * NB: should NOT do globbing!
6801 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6802 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006803static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006804{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006805#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006806 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006807 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006808#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809 char *argv[2], **list;
6810
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006811 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006812 /* This is generally an optimization, but it also
6813 * handles "", which otherwise trips over !list[0] check below.
6814 * (is this ever happens that we actually get str="" here?)
6815 */
6816 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6817 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006818 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006819 return xstrdup(str);
6820 }
6821
6822 argv[0] = (char*)str;
6823 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006824 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006825 if (!list[0]) {
6826 /* Example where it happens:
6827 * x=; echo ${x:-"$@"}
6828 */
6829 ((char*)list)[0] = '\0';
6830 } else {
6831 if (HUSH_DEBUG)
6832 if (list[1])
6833 bb_error_msg_and_die("BUG in varexp2");
6834 /* actually, just move string 2*sizeof(char*) bytes back */
6835 overlapping_strcpy((char*)list, list[0]);
6836 if (do_unbackslash)
6837 unbackslash((char*)list);
6838 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006839 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006840 return (char*)list;
6841}
6842
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006843#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844static char* expand_strvec_to_string(char **argv)
6845{
6846 char **list;
6847
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006848 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006849 /* Convert all NULs to spaces */
6850 if (list[0]) {
6851 int n = 1;
6852 while (list[n]) {
6853 if (HUSH_DEBUG)
6854 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6855 bb_error_msg_and_die("BUG in varexp3");
6856 /* bash uses ' ' regardless of $IFS contents */
6857 list[n][-1] = ' ';
6858 n++;
6859 }
6860 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006861 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006862 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6863 return (char*)list;
6864}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006865#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006866
6867static char **expand_assignments(char **argv, int count)
6868{
6869 int i;
6870 char **p;
6871
6872 G.expanded_assignments = p = NULL;
6873 /* Expand assignments into one string each */
6874 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006875 p = add_string_to_strings(p,
6876 expand_string_to_string(argv[i],
6877 EXP_FLAG_ESC_GLOB_CHARS,
6878 /*unbackslash:*/ 1
6879 )
6880 );
6881 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006882 }
6883 G.expanded_assignments = NULL;
6884 return p;
6885}
6886
6887
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006888static void switch_off_special_sigs(unsigned mask)
6889{
6890 unsigned sig = 0;
6891 while ((mask >>= 1) != 0) {
6892 sig++;
6893 if (!(mask & 1))
6894 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006895#if ENABLE_HUSH_TRAP
6896 if (G_traps) {
6897 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006898 /* trap is '', has to remain SIG_IGN */
6899 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006900 free(G_traps[sig]);
6901 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006902 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006903#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006904 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006905 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006906 }
6907}
6908
Denys Vlasenkob347df92011-08-09 22:49:15 +02006909#if BB_MMU
6910/* never called */
6911void re_execute_shell(char ***to_free, const char *s,
6912 char *g_argv0, char **g_argv,
6913 char **builtin_argv) NORETURN;
6914
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915static void reset_traps_to_defaults(void)
6916{
6917 /* This function is always called in a child shell
6918 * after fork (not vfork, NOMMU doesn't use this function).
6919 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006920 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006921 unsigned mask;
6922
6923 /* Child shells are not interactive.
6924 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6925 * Testcase: (while :; do :; done) + ^Z should background.
6926 * Same goes for SIGTERM, SIGHUP, SIGINT.
6927 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006928 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006929 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006930 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006931
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006932 /* Switch off special sigs */
6933 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006934# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006935 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006936# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006937 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006938 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6939 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006940
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006941# if ENABLE_HUSH_TRAP
6942 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006943 return;
6944
6945 /* Reset all sigs to default except ones with empty traps */
6946 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006947 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006948 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006949 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006950 continue; /* empty trap: has to remain SIG_IGN */
6951 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006952 free(G_traps[sig]);
6953 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006954 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006955 if (sig == 0)
6956 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006957 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006959# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960}
6961
6962#else /* !BB_MMU */
6963
6964static void re_execute_shell(char ***to_free, const char *s,
6965 char *g_argv0, char **g_argv,
6966 char **builtin_argv) NORETURN;
6967static void re_execute_shell(char ***to_free, const char *s,
6968 char *g_argv0, char **g_argv,
6969 char **builtin_argv)
6970{
6971# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6972 /* delims + 2 * (number of bytes in printed hex numbers) */
6973 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6974 char *heredoc_argv[4];
6975 struct variable *cur;
6976# if ENABLE_HUSH_FUNCTIONS
6977 struct function *funcp;
6978# endif
6979 char **argv, **pp;
6980 unsigned cnt;
6981 unsigned long long empty_trap_mask;
6982
6983 if (!g_argv0) { /* heredoc */
6984 argv = heredoc_argv;
6985 argv[0] = (char *) G.argv0_for_re_execing;
6986 argv[1] = (char *) "-<";
6987 argv[2] = (char *) s;
6988 argv[3] = NULL;
6989 pp = &argv[3]; /* used as pointer to empty environment */
6990 goto do_exec;
6991 }
6992
6993 cnt = 0;
6994 pp = builtin_argv;
6995 if (pp) while (*pp++)
6996 cnt++;
6997
6998 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006999 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007000 int sig;
7001 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007002 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007003 empty_trap_mask |= 1LL << sig;
7004 }
7005 }
7006
7007 sprintf(param_buf, NOMMU_HACK_FMT
7008 , (unsigned) G.root_pid
7009 , (unsigned) G.root_ppid
7010 , (unsigned) G.last_bg_pid
7011 , (unsigned) G.last_exitcode
7012 , cnt
7013 , empty_trap_mask
7014 IF_HUSH_LOOPS(, G.depth_of_loop)
7015 );
7016# undef NOMMU_HACK_FMT
7017 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7018 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7019 */
7020 cnt += 6;
7021 for (cur = G.top_var; cur; cur = cur->next) {
7022 if (!cur->flg_export || cur->flg_read_only)
7023 cnt += 2;
7024 }
7025# if ENABLE_HUSH_FUNCTIONS
7026 for (funcp = G.top_func; funcp; funcp = funcp->next)
7027 cnt += 3;
7028# endif
7029 pp = g_argv;
7030 while (*pp++)
7031 cnt++;
7032 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7033 *pp++ = (char *) G.argv0_for_re_execing;
7034 *pp++ = param_buf;
7035 for (cur = G.top_var; cur; cur = cur->next) {
7036 if (strcmp(cur->varstr, hush_version_str) == 0)
7037 continue;
7038 if (cur->flg_read_only) {
7039 *pp++ = (char *) "-R";
7040 *pp++ = cur->varstr;
7041 } else if (!cur->flg_export) {
7042 *pp++ = (char *) "-V";
7043 *pp++ = cur->varstr;
7044 }
7045 }
7046# if ENABLE_HUSH_FUNCTIONS
7047 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7048 *pp++ = (char *) "-F";
7049 *pp++ = funcp->name;
7050 *pp++ = funcp->body_as_string;
7051 }
7052# endif
7053 /* We can pass activated traps here. Say, -Tnn:trap_string
7054 *
7055 * However, POSIX says that subshells reset signals with traps
7056 * to SIG_DFL.
7057 * I tested bash-3.2 and it not only does that with true subshells
7058 * of the form ( list ), but with any forked children shells.
7059 * I set trap "echo W" WINCH; and then tried:
7060 *
7061 * { echo 1; sleep 20; echo 2; } &
7062 * while true; do echo 1; sleep 20; echo 2; break; done &
7063 * true | { echo 1; sleep 20; echo 2; } | cat
7064 *
7065 * In all these cases sending SIGWINCH to the child shell
7066 * did not run the trap. If I add trap "echo V" WINCH;
7067 * _inside_ group (just before echo 1), it works.
7068 *
7069 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007070 */
7071 *pp++ = (char *) "-c";
7072 *pp++ = (char *) s;
7073 if (builtin_argv) {
7074 while (*++builtin_argv)
7075 *pp++ = *builtin_argv;
7076 *pp++ = (char *) "";
7077 }
7078 *pp++ = g_argv0;
7079 while (*g_argv)
7080 *pp++ = *g_argv++;
7081 /* *pp = NULL; - is already there */
7082 pp = environ;
7083
7084 do_exec:
7085 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007086 /* Don't propagate SIG_IGN to the child */
7087 if (SPECIAL_JOBSTOP_SIGS != 0)
7088 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007089 execve(bb_busybox_exec_path, argv, pp);
7090 /* Fallback. Useful for init=/bin/hush usage etc */
7091 if (argv[0][0] == '/')
7092 execve(argv[0], argv, pp);
7093 xfunc_error_retval = 127;
7094 bb_error_msg_and_die("can't re-execute the shell");
7095}
7096#endif /* !BB_MMU */
7097
7098
7099static int run_and_free_list(struct pipe *pi);
7100
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007101/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007102 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7103 * end_trigger controls how often we stop parsing
7104 * NUL: parse all, execute, return
7105 * ';': parse till ';' or newline, execute, repeat till EOF
7106 */
7107static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007108{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007109 /* Why we need empty flag?
7110 * An obscure corner case "false; ``; echo $?":
7111 * empty command in `` should still set $? to 0.
7112 * But we can't just set $? to 0 at the start,
7113 * this breaks "false; echo `echo $?`" case.
7114 */
7115 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007116 while (1) {
7117 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007118
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007119#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007120 if (end_trigger == ';') {
7121 G.promptmode = 0; /* PS1 */
7122 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7123 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007124#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007125 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007126 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7127 /* If we are in "big" script
7128 * (not in `cmd` or something similar)...
7129 */
7130 if (pipe_list == ERR_PTR && end_trigger == ';') {
7131 /* Discard cached input (rest of line) */
7132 int ch = inp->last_char;
7133 while (ch != EOF && ch != '\n') {
7134 //bb_error_msg("Discarded:'%c'", ch);
7135 ch = i_getch(inp);
7136 }
7137 /* Force prompt */
7138 inp->p = NULL;
7139 /* This stream isn't empty */
7140 empty = 0;
7141 continue;
7142 }
7143 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007144 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007145 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007146 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007147 debug_print_tree(pipe_list, 0);
7148 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7149 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007150 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007151 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007152 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007153 }
Eric Andersen25f27032001-04-26 23:22:31 +00007154}
7155
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007156static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007157{
7158 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007159 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7160
Eric Andersen25f27032001-04-26 23:22:31 +00007161 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007162 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007163 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007164}
7165
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007166static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007167{
Eric Andersen25f27032001-04-26 23:22:31 +00007168 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007169 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007170
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007171 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007172 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007173 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007174 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007175}
7176
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007177#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007178static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007179{
7180 pid_t pid;
7181 int channel[2];
7182# if !BB_MMU
7183 char **to_free = NULL;
7184# endif
7185
7186 xpipe(channel);
7187 pid = BB_MMU ? xfork() : xvfork();
7188 if (pid == 0) { /* child */
7189 disable_restore_tty_pgrp_on_exit();
7190 /* Process substitution is not considered to be usual
7191 * 'command execution'.
7192 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7193 */
7194 bb_signals(0
7195 + (1 << SIGTSTP)
7196 + (1 << SIGTTIN)
7197 + (1 << SIGTTOU)
7198 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007199 close(channel[0]); /* NB: close _first_, then move fd! */
7200 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007201# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007202 /* Awful hack for `trap` or $(trap).
7203 *
7204 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7205 * contains an example where "trap" is executed in a subshell:
7206 *
7207 * save_traps=$(trap)
7208 * ...
7209 * eval "$save_traps"
7210 *
7211 * Standard does not say that "trap" in subshell shall print
7212 * parent shell's traps. It only says that its output
7213 * must have suitable form, but then, in the above example
7214 * (which is not supposed to be normative), it implies that.
7215 *
7216 * bash (and probably other shell) does implement it
7217 * (traps are reset to defaults, but "trap" still shows them),
7218 * but as a result, "trap" logic is hopelessly messed up:
7219 *
7220 * # trap
7221 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7222 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7223 * # true | trap <--- trap is in subshell - no output (ditto)
7224 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7225 * trap -- 'echo Ho' SIGWINCH
7226 * # echo `(trap)` <--- in subshell in subshell - output
7227 * trap -- 'echo Ho' SIGWINCH
7228 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7229 * trap -- 'echo Ho' SIGWINCH
7230 *
7231 * The rules when to forget and when to not forget traps
7232 * get really complex and nonsensical.
7233 *
7234 * Our solution: ONLY bare $(trap) or `trap` is special.
7235 */
7236 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007237 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007238 && skip_whitespace(s + 4)[0] == '\0'
7239 ) {
7240 static const char *const argv[] = { NULL, NULL };
7241 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007242 fflush_all(); /* important */
7243 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007244 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007245# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007246# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007247 /* Prevent it from trying to handle ctrl-z etc */
7248 IF_HUSH_JOB(G.run_list_level = 1;)
7249 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007250 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007251 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007252 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007253 parse_and_run_string(s);
7254 _exit(G.last_exitcode);
7255# else
7256 /* We re-execute after vfork on NOMMU. This makes this script safe:
7257 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7258 * huge=`cat BIG` # was blocking here forever
7259 * echo OK
7260 */
7261 re_execute_shell(&to_free,
7262 s,
7263 G.global_argv[0],
7264 G.global_argv + 1,
7265 NULL);
7266# endif
7267 }
7268
7269 /* parent */
7270 *pid_p = pid;
7271# if ENABLE_HUSH_FAST
7272 G.count_SIGCHLD++;
7273//bb_error_msg("[%d] fork in generate_stream_from_string:"
7274// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7275// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7276# endif
7277 enable_restore_tty_pgrp_on_exit();
7278# if !BB_MMU
7279 free(to_free);
7280# endif
7281 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007282 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007283}
7284
7285/* Return code is exit status of the process that is run. */
7286static int process_command_subs(o_string *dest, const char *s)
7287{
7288 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007289 pid_t pid;
7290 int status, ch, eol_cnt;
7291
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007292 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007293
7294 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007295 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007296 while ((ch = getc(fp)) != EOF) {
7297 if (ch == '\0')
7298 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007299 if (ch == '\n') {
7300 eol_cnt++;
7301 continue;
7302 }
7303 while (eol_cnt) {
7304 o_addchr(dest, '\n');
7305 eol_cnt--;
7306 }
7307 o_addQchr(dest, ch);
7308 }
7309
7310 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007311 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007312 /* We need to extract exitcode. Test case
7313 * "true; echo `sleep 1; false` $?"
7314 * should print 1 */
7315 safe_waitpid(pid, &status, 0);
7316 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7317 return WEXITSTATUS(status);
7318}
7319#endif /* ENABLE_HUSH_TICK */
7320
7321
7322static void setup_heredoc(struct redir_struct *redir)
7323{
7324 struct fd_pair pair;
7325 pid_t pid;
7326 int len, written;
7327 /* the _body_ of heredoc (misleading field name) */
7328 const char *heredoc = redir->rd_filename;
7329 char *expanded;
7330#if !BB_MMU
7331 char **to_free;
7332#endif
7333
7334 expanded = NULL;
7335 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007336 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007337 if (expanded)
7338 heredoc = expanded;
7339 }
7340 len = strlen(heredoc);
7341
7342 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7343 xpiped_pair(pair);
7344 xmove_fd(pair.rd, redir->rd_fd);
7345
7346 /* Try writing without forking. Newer kernels have
7347 * dynamically growing pipes. Must use non-blocking write! */
7348 ndelay_on(pair.wr);
7349 while (1) {
7350 written = write(pair.wr, heredoc, len);
7351 if (written <= 0)
7352 break;
7353 len -= written;
7354 if (len == 0) {
7355 close(pair.wr);
7356 free(expanded);
7357 return;
7358 }
7359 heredoc += written;
7360 }
7361 ndelay_off(pair.wr);
7362
7363 /* Okay, pipe buffer was not big enough */
7364 /* Note: we must not create a stray child (bastard? :)
7365 * for the unsuspecting parent process. Child creates a grandchild
7366 * and exits before parent execs the process which consumes heredoc
7367 * (that exec happens after we return from this function) */
7368#if !BB_MMU
7369 to_free = NULL;
7370#endif
7371 pid = xvfork();
7372 if (pid == 0) {
7373 /* child */
7374 disable_restore_tty_pgrp_on_exit();
7375 pid = BB_MMU ? xfork() : xvfork();
7376 if (pid != 0)
7377 _exit(0);
7378 /* grandchild */
7379 close(redir->rd_fd); /* read side of the pipe */
7380#if BB_MMU
7381 full_write(pair.wr, heredoc, len); /* may loop or block */
7382 _exit(0);
7383#else
7384 /* Delegate blocking writes to another process */
7385 xmove_fd(pair.wr, STDOUT_FILENO);
7386 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7387#endif
7388 }
7389 /* parent */
7390#if ENABLE_HUSH_FAST
7391 G.count_SIGCHLD++;
7392//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7393#endif
7394 enable_restore_tty_pgrp_on_exit();
7395#if !BB_MMU
7396 free(to_free);
7397#endif
7398 close(pair.wr);
7399 free(expanded);
7400 wait(NULL); /* wait till child has died */
7401}
7402
Denys Vlasenko2db74612017-07-07 22:07:28 +02007403struct squirrel {
7404 int orig_fd;
7405 int moved_to;
7406 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7407 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7408};
7409
Denys Vlasenko621fc502017-07-24 12:42:17 +02007410static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7411{
7412 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7413 sq[i].orig_fd = orig;
7414 sq[i].moved_to = moved;
7415 sq[i+1].orig_fd = -1; /* end marker */
7416 return sq;
7417}
7418
Denys Vlasenko2db74612017-07-07 22:07:28 +02007419static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7420{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007421 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007422 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007423
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007424 i = 0;
7425 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007426 /* If we collide with an already moved fd... */
7427 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007428 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007429 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7430 if (sq[i].moved_to < 0) /* what? */
7431 xfunc_die();
7432 return sq;
7433 }
7434 if (fd == sq[i].orig_fd) {
7435 /* Example: echo Hello >/dev/null 1>&2 */
7436 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7437 return sq;
7438 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007439 }
7440
Denys Vlasenko2db74612017-07-07 22:07:28 +02007441 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007442 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007443 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7444 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007445 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007446 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007447}
7448
Denys Vlasenko657e9002017-07-30 23:34:04 +02007449static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7450{
7451 int i;
7452
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007453 i = 0;
7454 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007455 /* If we collide with an already moved fd... */
7456 if (fd == sq[i].orig_fd) {
7457 /* Examples:
7458 * "echo 3>FILE 3>&- 3>FILE"
7459 * "echo 3>&- 3>FILE"
7460 * No need for last redirect to insert
7461 * another "need to close 3" indicator.
7462 */
7463 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7464 return sq;
7465 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007466 }
7467
7468 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7469 return append_squirrel(sq, i, fd, -1);
7470}
7471
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007472/* fd: redirect wants this fd to be used (e.g. 3>file).
7473 * Move all conflicting internally used fds,
7474 * and remember them so that we can restore them later.
7475 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007476static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007477{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007478 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7479 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007480
7481#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007482 if (fd == G.interactive_fd) {
7483 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007484 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007485 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7486 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007487 }
7488#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007489 /* Are we called from setup_redirects(squirrel==NULL)
7490 * in redirect in a [v]forked child?
7491 */
7492 if (sqp == NULL) {
7493 /* No need to move script fds.
7494 * For NOMMU case, it's actively wrong: we'd change ->fd
7495 * fields in memory for the parent, but parent's fds
7496 * aren't be moved, it would use wrong fd!
7497 * Reproducer: "cmd 3>FILE" in script.
7498 * If we would call move_HFILEs_on_redirect(), child would:
7499 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7500 * close(3) = 0
7501 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7502 */
7503 //bb_error_msg("sqp == NULL: [v]forked child");
7504 return 0;
7505 }
7506
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007507 /* If this one of script's fds? */
7508 if (move_HFILEs_on_redirect(fd, avoid_fd))
7509 return 1; /* yes. "we closed fd" (actually moved it) */
7510
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007511 /* Are we called for "exec 3>FILE"? Came through
7512 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7513 * This case used to fail for this script:
7514 * exec 3>FILE
7515 * echo Ok
7516 * ...100000 more lines...
7517 * echo Ok
7518 * as follows:
7519 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7520 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7521 * dup2(4, 3) = 3
7522 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7523 * close(4) = 0
7524 * write(1, "Ok\n", 3) = 3
7525 * ... = 3
7526 * write(1, "Ok\n", 3) = 3
7527 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7528 * ^^^^^^^^ oops, wrong fd!!!
7529 * With this case separate from sqp == NULL and *after* move_HFILEs,
7530 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007531 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007532 if (sqp == ERR_PTR) {
7533 /* Don't preserve redirected fds: exec is _meant_ to change these */
7534 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007535 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007536 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007537
Denys Vlasenko2db74612017-07-07 22:07:28 +02007538 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7539 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7540 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007541}
7542
Denys Vlasenko2db74612017-07-07 22:07:28 +02007543static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007544{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007545 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007546 int i;
7547 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007548 if (sq[i].moved_to >= 0) {
7549 /* We simply die on error */
7550 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7551 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7552 } else {
7553 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7554 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7555 close(sq[i].orig_fd);
7556 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007557 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007558 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007559 }
7560
Denys Vlasenko2db74612017-07-07 22:07:28 +02007561 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007562}
7563
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007564#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007565static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007566{
7567 if (G_interactive_fd)
7568 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007569 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007570}
7571#endif
7572
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007573static int internally_opened_fd(int fd, struct squirrel *sq)
7574{
7575 int i;
7576
7577#if ENABLE_HUSH_INTERACTIVE
7578 if (fd == G.interactive_fd)
7579 return 1;
7580#endif
7581 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007582 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007583 return 1;
7584
7585 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7586 if (fd == sq[i].moved_to)
7587 return 1;
7588 }
7589 return 0;
7590}
7591
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007592/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7593 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007594static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007595{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007596 struct redir_struct *redir;
7597
7598 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007599 int newfd;
7600 int closed;
7601
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007602 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007603 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007604 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007605 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7606 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007607 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007608 redir->rd_filename);
7609 setup_heredoc(redir);
7610 continue;
7611 }
7612
7613 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007614 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007615 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007616 int mode;
7617
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007618 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007619 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007620 * "cmd >" (no filename)
7621 * "cmd > <file" (2nd redirect starts too early)
7622 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007623 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007624 continue;
7625 }
7626 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007627 p = expand_string_to_string(redir->rd_filename,
7628 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007629 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007630 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007631 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007632 /* Error message from open_or_warn can be lost
7633 * if stderr has been redirected, but bash
7634 * and ash both lose it as well
7635 * (though zsh doesn't!)
7636 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007637 return 1;
7638 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007639 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007640 /* open() gave us precisely the fd we wanted.
7641 * This means that this fd was not busy
7642 * (not opened to anywhere).
7643 * Remember to close it on restore:
7644 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007645 *sqp = add_squirrel_closed(*sqp, newfd);
7646 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007647 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007648 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007649 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7650 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007651 }
7652
Denys Vlasenko657e9002017-07-30 23:34:04 +02007653 if (newfd == redir->rd_fd)
7654 continue;
7655
7656 /* if "N>FILE": move newfd to redir->rd_fd */
7657 /* if "N>&M": dup newfd to redir->rd_fd */
7658 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7659
7660 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7661 if (newfd == REDIRFD_CLOSE) {
7662 /* "N>&-" means "close me" */
7663 if (!closed) {
7664 /* ^^^ optimization: saving may already
7665 * have closed it. If not... */
7666 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007667 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007668 /* Sometimes we do another close on restore, getting EBADF.
7669 * Consider "echo 3>FILE 3>&-"
7670 * first redirect remembers "need to close 3",
7671 * and second redirect closes 3! Restore code then closes 3 again.
7672 */
7673 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007674 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007675 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007676 //errno = EBADF;
7677 //bb_perror_msg_and_die("can't duplicate file descriptor");
7678 newfd = -1; /* same effect as code above */
7679 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007680 xdup2(newfd, redir->rd_fd);
7681 if (redir->rd_dup == REDIRFD_TO_FILE)
7682 /* "rd_fd > FILE" */
7683 close(newfd);
7684 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007685 }
7686 }
7687 return 0;
7688}
7689
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007690static char *find_in_path(const char *arg)
7691{
7692 char *ret = NULL;
7693 const char *PATH = get_local_var_value("PATH");
7694
7695 if (!PATH)
7696 return NULL;
7697
7698 while (1) {
7699 const char *end = strchrnul(PATH, ':');
7700 int sz = end - PATH; /* must be int! */
7701
7702 free(ret);
7703 if (sz != 0) {
7704 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7705 } else {
7706 /* We have xxx::yyyy in $PATH,
7707 * it means "use current dir" */
7708 ret = xstrdup(arg);
7709 }
7710 if (access(ret, F_OK) == 0)
7711 break;
7712
7713 if (*end == '\0') {
7714 free(ret);
7715 return NULL;
7716 }
7717 PATH = end + 1;
7718 }
7719
7720 return ret;
7721}
7722
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007723static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007724 const struct built_in_command *x,
7725 const struct built_in_command *end)
7726{
7727 while (x != end) {
7728 if (strcmp(name, x->b_cmd) != 0) {
7729 x++;
7730 continue;
7731 }
7732 debug_printf_exec("found builtin '%s'\n", name);
7733 return x;
7734 }
7735 return NULL;
7736}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007737static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738{
7739 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7740}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007741static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742{
7743 const struct built_in_command *x = find_builtin1(name);
7744 if (x)
7745 return x;
7746 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7747}
7748
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007749static void remove_nested_vars(void)
7750{
7751 struct variable *cur;
7752 struct variable **cur_pp;
7753
7754 cur_pp = &G.top_var;
7755 while ((cur = *cur_pp) != NULL) {
7756 if (cur->var_nest_level <= G.var_nest_level) {
7757 cur_pp = &cur->next;
7758 continue;
7759 }
7760 /* Unexport */
7761 if (cur->flg_export) {
7762 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7763 bb_unsetenv(cur->varstr);
7764 }
7765 /* Remove from global list */
7766 *cur_pp = cur->next;
7767 /* Free */
7768 if (!cur->max_len) {
7769 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7770 free(cur->varstr);
7771 }
7772 free(cur);
7773 }
7774}
7775
7776static void enter_var_nest_level(void)
7777{
7778 G.var_nest_level++;
7779 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7780
7781 /* Try: f() { echo -n .; f; }; f
7782 * struct variable::var_nest_level is uint16_t,
7783 * thus limiting recursion to < 2^16.
7784 * In any case, with 8 Mbyte stack SEGV happens
7785 * not too long after 2^16 recursions anyway.
7786 */
7787 if (G.var_nest_level > 0xff00)
7788 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7789}
7790
7791static void leave_var_nest_level(void)
7792{
7793 G.var_nest_level--;
7794 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7795 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7796 bb_error_msg_and_die("BUG: nesting underflow");
7797
7798 remove_nested_vars();
7799}
7800
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007801#if ENABLE_HUSH_FUNCTIONS
7802static struct function **find_function_slot(const char *name)
7803{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007804 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007805 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007806
7807 while ((funcp = *funcpp) != NULL) {
7808 if (strcmp(name, funcp->name) == 0) {
7809 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007810 break;
7811 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007812 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007813 }
7814 return funcpp;
7815}
7816
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007817static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007818{
7819 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007820 return funcp;
7821}
7822
7823/* Note: takes ownership on name ptr */
7824static struct function *new_function(char *name)
7825{
7826 struct function **funcpp = find_function_slot(name);
7827 struct function *funcp = *funcpp;
7828
7829 if (funcp != NULL) {
7830 struct command *cmd = funcp->parent_cmd;
7831 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7832 if (!cmd) {
7833 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7834 free(funcp->name);
7835 /* Note: if !funcp->body, do not free body_as_string!
7836 * This is a special case of "-F name body" function:
7837 * body_as_string was not malloced! */
7838 if (funcp->body) {
7839 free_pipe_list(funcp->body);
7840# if !BB_MMU
7841 free(funcp->body_as_string);
7842# endif
7843 }
7844 } else {
7845 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7846 cmd->argv[0] = funcp->name;
7847 cmd->group = funcp->body;
7848# if !BB_MMU
7849 cmd->group_as_string = funcp->body_as_string;
7850# endif
7851 }
7852 } else {
7853 debug_printf_exec("remembering new function '%s'\n", name);
7854 funcp = *funcpp = xzalloc(sizeof(*funcp));
7855 /*funcp->next = NULL;*/
7856 }
7857
7858 funcp->name = name;
7859 return funcp;
7860}
7861
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007862# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007863static void unset_func(const char *name)
7864{
7865 struct function **funcpp = find_function_slot(name);
7866 struct function *funcp = *funcpp;
7867
7868 if (funcp != NULL) {
7869 debug_printf_exec("freeing function '%s'\n", funcp->name);
7870 *funcpp = funcp->next;
7871 /* funcp is unlinked now, deleting it.
7872 * Note: if !funcp->body, the function was created by
7873 * "-F name body", do not free ->body_as_string
7874 * and ->name as they were not malloced. */
7875 if (funcp->body) {
7876 free_pipe_list(funcp->body);
7877 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007878# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007880# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007881 }
7882 free(funcp);
7883 }
7884}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007885# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007886
7887# if BB_MMU
7888#define exec_function(to_free, funcp, argv) \
7889 exec_function(funcp, argv)
7890# endif
7891static void exec_function(char ***to_free,
7892 const struct function *funcp,
7893 char **argv) NORETURN;
7894static void exec_function(char ***to_free,
7895 const struct function *funcp,
7896 char **argv)
7897{
7898# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007899 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007900
7901 argv[0] = G.global_argv[0];
7902 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007903 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007904
7905// Example when we are here: "cmd | func"
7906// func will run with saved-redirect fds open.
7907// $ f() { echo /proc/self/fd/*; }
7908// $ true | f
7909// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7910// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7911// Same in script:
7912// $ . ./SCRIPT
7913// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7914// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7915// They are CLOEXEC so external programs won't see them, but
7916// for "more correctness" we might want to close those extra fds here:
7917//? close_saved_fds_and_FILE_fds();
7918
Denys Vlasenko332e4112018-04-04 22:32:59 +02007919 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007920 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007921 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007922 IF_HUSH_LOCAL(G.func_nest_level++;)
7923
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007924 /* On MMU, funcp->body is always non-NULL */
7925 n = run_list(funcp->body);
7926 fflush_all();
7927 _exit(n);
7928# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007929//? close_saved_fds_and_FILE_fds();
7930
7931//TODO: check whether "true | func_with_return" works
7932
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007933 re_execute_shell(to_free,
7934 funcp->body_as_string,
7935 G.global_argv[0],
7936 argv + 1,
7937 NULL);
7938# endif
7939}
7940
7941static int run_function(const struct function *funcp, char **argv)
7942{
7943 int rc;
7944 save_arg_t sv;
7945 smallint sv_flg;
7946
7947 save_and_replace_G_args(&sv, argv);
7948
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007949 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007950 sv_flg = G_flag_return_in_progress;
7951 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007952
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007953 /* Make "local" variables properly shadow previous ones */
7954 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007955 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007956
7957 /* On MMU, funcp->body is always non-NULL */
7958# if !BB_MMU
7959 if (!funcp->body) {
7960 /* Function defined by -F */
7961 parse_and_run_string(funcp->body_as_string);
7962 rc = G.last_exitcode;
7963 } else
7964# endif
7965 {
7966 rc = run_list(funcp->body);
7967 }
7968
Denys Vlasenko332e4112018-04-04 22:32:59 +02007969 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007970 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007971
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007972 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007973
7974 restore_G_args(&sv, argv);
7975
7976 return rc;
7977}
7978#endif /* ENABLE_HUSH_FUNCTIONS */
7979
7980
7981#if BB_MMU
7982#define exec_builtin(to_free, x, argv) \
7983 exec_builtin(x, argv)
7984#else
7985#define exec_builtin(to_free, x, argv) \
7986 exec_builtin(to_free, argv)
7987#endif
7988static void exec_builtin(char ***to_free,
7989 const struct built_in_command *x,
7990 char **argv) NORETURN;
7991static void exec_builtin(char ***to_free,
7992 const struct built_in_command *x,
7993 char **argv)
7994{
7995#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007996 int rcode;
7997 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007998//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007999 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008000 fflush_all();
8001 _exit(rcode);
8002#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008003 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008004 /* On NOMMU, we must never block!
8005 * Example: { sleep 99 | read line; } & echo Ok
8006 */
8007 re_execute_shell(to_free,
8008 argv[0],
8009 G.global_argv[0],
8010 G.global_argv + 1,
8011 argv);
8012#endif
8013}
8014
8015
8016static void execvp_or_die(char **argv) NORETURN;
8017static void execvp_or_die(char **argv)
8018{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008019 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008020 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008021 /* Don't propagate SIG_IGN to the child */
8022 if (SPECIAL_JOBSTOP_SIGS != 0)
8023 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008024 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008025 e = 2;
8026 if (errno == EACCES) e = 126;
8027 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008028 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008029 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030}
8031
8032#if ENABLE_HUSH_MODE_X
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008033static void print_optionally_squoted(FILE *fp, const char *str)
8034{
8035 unsigned len;
8036 const char *cp;
8037
8038 cp = str;
8039 if (str[0] != '{' && str[0] != '(') for (;;) {
8040 if (!*cp) {
8041 /* string has no special chars */
8042 fputs(str, fp);
8043 return;
8044 }
8045 if (*cp == '\\') break;
8046 if (*cp == '\'') break;
8047 if (*cp == '"') break;
8048 if (*cp == '$') break;
8049 if (*cp == '!') break;
8050 if (*cp == '*') break;
8051 if (*cp == '[') break;
8052 if (*cp == ']') break;
8053#if ENABLE_HUSH_TICK
8054 if (*cp == '`') break;
8055#endif
8056 if (isspace(*cp)) break;
8057 cp++;
8058 }
8059
8060 cp = str;
8061 for (;;) {
8062 /* print '....' up to EOL or first squote */
8063 len = (int)(strchrnul(cp, '\'') - cp);
8064 if (len != 0) {
8065 fprintf(fp, "'%.*s'", len, cp);
8066 cp += len;
8067 }
8068 if (*cp == '\0')
8069 break;
8070 /* string contains squote(s), print them as \' */
8071 fprintf(fp, "\\'");
8072 cp++;
8073 }
8074}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008075static void dump_cmd_in_x_mode(char **argv)
8076{
8077 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008078 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008079
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008080 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02008081 n = G.x_mode_depth;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008082 do bb_putchar_stderr('+'); while ((int)(--n) >= 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008083 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008084 while (argv[n]) {
8085 if (argv[n][0] == '\0')
8086 fputs(" ''", stderr);
8087 else {
8088 bb_putchar_stderr(' ');
8089 print_optionally_squoted(stderr, argv[n]);
8090 }
8091 n++;
8092 }
8093 bb_putchar_stderr('\n');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008094 }
8095}
8096#else
8097# define dump_cmd_in_x_mode(argv) ((void)0)
8098#endif
8099
Denys Vlasenko57000292018-01-12 14:41:45 +01008100#if ENABLE_HUSH_COMMAND
8101static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8102{
8103 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008104
Denys Vlasenko57000292018-01-12 14:41:45 +01008105 if (!opt_vV)
8106 return;
8107
8108 to_free = NULL;
8109 if (!explanation) {
8110 char *path = getenv("PATH");
8111 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008112 if (!explanation)
8113 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008114 if (opt_vV != 'V')
8115 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8116 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008117 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008118 free(to_free);
8119 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008120 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008121}
8122#else
8123# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8124#endif
8125
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008126#if BB_MMU
8127#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8128 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8129#define pseudo_exec(nommu_save, command, argv_expanded) \
8130 pseudo_exec(command, argv_expanded)
8131#endif
8132
8133/* Called after [v]fork() in run_pipe, or from builtin_exec.
8134 * Never returns.
8135 * Don't exit() here. If you don't exec, use _exit instead.
8136 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008137 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008138 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008139static void pseudo_exec_argv(nommu_save_t *nommu_save,
8140 char **argv, int assignment_cnt,
8141 char **argv_expanded) NORETURN;
8142static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8143 char **argv, int assignment_cnt,
8144 char **argv_expanded)
8145{
Denys Vlasenko57000292018-01-12 14:41:45 +01008146 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008147 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008148 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008149 IF_HUSH_COMMAND(char opt_vV = 0;)
8150 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008151
8152 new_env = expand_assignments(argv, assignment_cnt);
8153 dump_cmd_in_x_mode(new_env);
8154
8155 if (!argv[assignment_cnt]) {
8156 /* Case when we are here: ... | var=val | ...
8157 * (note that we do not exit early, i.e., do not optimize out
8158 * expand_assignments(): think about ... | var=`sleep 1` | ...
8159 */
8160 free_strings(new_env);
8161 _exit(EXIT_SUCCESS);
8162 }
8163
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008164 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008165#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008166 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008167#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008168 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008169 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008170#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008171 set_vars_and_save_old(new_env);
8172 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008173
8174 if (argv_expanded) {
8175 argv = argv_expanded;
8176 } else {
8177 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8178#if !BB_MMU
8179 nommu_save->argv = argv;
8180#endif
8181 }
8182 dump_cmd_in_x_mode(argv);
8183
8184#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8185 if (strchr(argv[0], '/') != NULL)
8186 goto skip;
8187#endif
8188
Denys Vlasenko75481d32017-07-31 05:27:09 +02008189#if ENABLE_HUSH_FUNCTIONS
8190 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008191 funcp = find_function(argv[0]);
8192 if (funcp)
8193 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008194#endif
8195
Denys Vlasenko57000292018-01-12 14:41:45 +01008196#if ENABLE_HUSH_COMMAND
8197 /* "command BAR": run BAR without looking it up among functions
8198 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8199 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8200 */
8201 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8202 char *p;
8203
8204 argv++;
8205 p = *argv;
8206 if (p[0] != '-' || !p[1])
8207 continue; /* bash allows "command command command [-OPT] BAR" */
8208
8209 for (;;) {
8210 p++;
8211 switch (*p) {
8212 case '\0':
8213 argv++;
8214 p = *argv;
8215 if (p[0] != '-' || !p[1])
8216 goto after_opts;
8217 continue; /* next arg is also -opts, process it too */
8218 case 'v':
8219 case 'V':
8220 opt_vV = *p;
8221 continue;
8222 default:
8223 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8224 }
8225 }
8226 }
8227 after_opts:
8228# if ENABLE_HUSH_FUNCTIONS
8229 if (opt_vV && find_function(argv[0]))
8230 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8231# endif
8232#endif
8233
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008234 /* Check if the command matches any of the builtins.
8235 * Depending on context, this might be redundant. But it's
8236 * easier to waste a few CPU cycles than it is to figure out
8237 * if this is one of those cases.
8238 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008239 /* Why "BB_MMU ? :" difference in logic? -
8240 * On NOMMU, it is more expensive to re-execute shell
8241 * just in order to run echo or test builtin.
8242 * It's better to skip it here and run corresponding
8243 * non-builtin later. */
8244 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8245 if (x) {
8246 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8247 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008248 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008249
8250#if ENABLE_FEATURE_SH_STANDALONE
8251 /* Check if the command matches any busybox applets */
8252 {
8253 int a = find_applet_by_name(argv[0]);
8254 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008255 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008256# if BB_MMU /* see above why on NOMMU it is not allowed */
8257 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008258 /* Do not leak open fds from opened script files etc.
8259 * Testcase: interactive "ls -l /proc/self/fd"
8260 * should not show tty fd open.
8261 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008262 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008263//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008264//This casuses test failures in
8265//redir_children_should_not_see_saved_fd_2.tests
8266//redir_children_should_not_see_saved_fd_3.tests
8267//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008268 /* Without this, "rm -i FILE" can't be ^C'ed: */
8269 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008270 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008271 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008272 }
8273# endif
8274 /* Re-exec ourselves */
8275 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008276 /* Don't propagate SIG_IGN to the child */
8277 if (SPECIAL_JOBSTOP_SIGS != 0)
8278 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008279 execv(bb_busybox_exec_path, argv);
8280 /* If they called chroot or otherwise made the binary no longer
8281 * executable, fall through */
8282 }
8283 }
8284#endif
8285
8286#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8287 skip:
8288#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008289 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008290 execvp_or_die(argv);
8291}
8292
8293/* Called after [v]fork() in run_pipe
8294 */
8295static void pseudo_exec(nommu_save_t *nommu_save,
8296 struct command *command,
8297 char **argv_expanded) NORETURN;
8298static void pseudo_exec(nommu_save_t *nommu_save,
8299 struct command *command,
8300 char **argv_expanded)
8301{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008302#if ENABLE_HUSH_FUNCTIONS
8303 if (command->cmd_type == CMD_FUNCDEF) {
8304 /* Ignore funcdefs in pipes:
8305 * true | f() { cmd }
8306 */
8307 _exit(0);
8308 }
8309#endif
8310
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008311 if (command->argv) {
8312 pseudo_exec_argv(nommu_save, command->argv,
8313 command->assignment_cnt, argv_expanded);
8314 }
8315
8316 if (command->group) {
8317 /* Cases when we are here:
8318 * ( list )
8319 * { list } &
8320 * ... | ( list ) | ...
8321 * ... | { list } | ...
8322 */
8323#if BB_MMU
8324 int rcode;
8325 debug_printf_exec("pseudo_exec: run_list\n");
8326 reset_traps_to_defaults();
8327 rcode = run_list(command->group);
8328 /* OK to leak memory by not calling free_pipe_list,
8329 * since this process is about to exit */
8330 _exit(rcode);
8331#else
8332 re_execute_shell(&nommu_save->argv_from_re_execing,
8333 command->group_as_string,
8334 G.global_argv[0],
8335 G.global_argv + 1,
8336 NULL);
8337#endif
8338 }
8339
8340 /* Case when we are here: ... | >file */
8341 debug_printf_exec("pseudo_exec'ed null command\n");
8342 _exit(EXIT_SUCCESS);
8343}
8344
8345#if ENABLE_HUSH_JOB
8346static const char *get_cmdtext(struct pipe *pi)
8347{
8348 char **argv;
8349 char *p;
8350 int len;
8351
8352 /* This is subtle. ->cmdtext is created only on first backgrounding.
8353 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8354 * On subsequent bg argv is trashed, but we won't use it */
8355 if (pi->cmdtext)
8356 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008357
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008358 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008359 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008360 pi->cmdtext = xzalloc(1);
8361 return pi->cmdtext;
8362 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008363 len = 0;
8364 do {
8365 len += strlen(*argv) + 1;
8366 } while (*++argv);
8367 p = xmalloc(len);
8368 pi->cmdtext = p;
8369 argv = pi->cmds[0].argv;
8370 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008371 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008372 *p++ = ' ';
8373 } while (*++argv);
8374 p[-1] = '\0';
8375 return pi->cmdtext;
8376}
8377
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008378static void remove_job_from_table(struct pipe *pi)
8379{
8380 struct pipe *prev_pipe;
8381
8382 if (pi == G.job_list) {
8383 G.job_list = pi->next;
8384 } else {
8385 prev_pipe = G.job_list;
8386 while (prev_pipe->next != pi)
8387 prev_pipe = prev_pipe->next;
8388 prev_pipe->next = pi->next;
8389 }
8390 G.last_jobid = 0;
8391 if (G.job_list)
8392 G.last_jobid = G.job_list->jobid;
8393}
8394
8395static void delete_finished_job(struct pipe *pi)
8396{
8397 remove_job_from_table(pi);
8398 free_pipe(pi);
8399}
8400
8401static void clean_up_last_dead_job(void)
8402{
8403 if (G.job_list && !G.job_list->alive_cmds)
8404 delete_finished_job(G.job_list);
8405}
8406
Denys Vlasenko16096292017-07-10 10:00:28 +02008407static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008408{
8409 struct pipe *job, **jobp;
8410 int i;
8411
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008412 clean_up_last_dead_job();
8413
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008414 /* Find the end of the list, and find next job ID to use */
8415 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008416 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008417 while ((job = *jobp) != NULL) {
8418 if (job->jobid > i)
8419 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008420 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008421 }
8422 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008423
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008424 /* Create a new job struct at the end */
8425 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008426 job->next = NULL;
8427 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8428 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8429 for (i = 0; i < pi->num_cmds; i++) {
8430 job->cmds[i].pid = pi->cmds[i].pid;
8431 /* all other fields are not used and stay zero */
8432 }
8433 job->cmdtext = xstrdup(get_cmdtext(pi));
8434
8435 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008436 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008437 G.last_jobid = job->jobid;
8438}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008439#endif /* JOB */
8440
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008441static int job_exited_or_stopped(struct pipe *pi)
8442{
8443 int rcode, i;
8444
8445 if (pi->alive_cmds != pi->stopped_cmds)
8446 return -1;
8447
8448 /* All processes in fg pipe have exited or stopped */
8449 rcode = 0;
8450 i = pi->num_cmds;
8451 while (--i >= 0) {
8452 rcode = pi->cmds[i].cmd_exitcode;
8453 /* usually last process gives overall exitstatus,
8454 * but with "set -o pipefail", last *failed* process does */
8455 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8456 break;
8457 }
8458 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8459 return rcode;
8460}
8461
Denys Vlasenko7e675362016-10-28 21:57:31 +02008462static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008463{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008464#if ENABLE_HUSH_JOB
8465 struct pipe *pi;
8466#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008467 int i, dead;
8468
8469 dead = WIFEXITED(status) || WIFSIGNALED(status);
8470
8471#if DEBUG_JOBS
8472 if (WIFSTOPPED(status))
8473 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8474 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8475 if (WIFSIGNALED(status))
8476 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8477 childpid, WTERMSIG(status), WEXITSTATUS(status));
8478 if (WIFEXITED(status))
8479 debug_printf_jobs("pid %d exited, exitcode %d\n",
8480 childpid, WEXITSTATUS(status));
8481#endif
8482 /* Were we asked to wait for a fg pipe? */
8483 if (fg_pipe) {
8484 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008485
Denys Vlasenko7e675362016-10-28 21:57:31 +02008486 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008487 int rcode;
8488
Denys Vlasenko7e675362016-10-28 21:57:31 +02008489 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8490 if (fg_pipe->cmds[i].pid != childpid)
8491 continue;
8492 if (dead) {
8493 int ex;
8494 fg_pipe->cmds[i].pid = 0;
8495 fg_pipe->alive_cmds--;
8496 ex = WEXITSTATUS(status);
8497 /* bash prints killer signal's name for *last*
8498 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8499 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8500 */
8501 if (WIFSIGNALED(status)) {
8502 int sig = WTERMSIG(status);
8503 if (i == fg_pipe->num_cmds-1)
8504 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8505 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8506 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8507 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8508 * Maybe we need to use sig | 128? */
8509 ex = sig + 128;
8510 }
8511 fg_pipe->cmds[i].cmd_exitcode = ex;
8512 } else {
8513 fg_pipe->stopped_cmds++;
8514 }
8515 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8516 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008517 rcode = job_exited_or_stopped(fg_pipe);
8518 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008519/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8520 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8521 * and "killall -STOP cat" */
8522 if (G_interactive_fd) {
8523#if ENABLE_HUSH_JOB
8524 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008525 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008526#endif
8527 return rcode;
8528 }
8529 if (fg_pipe->alive_cmds == 0)
8530 return rcode;
8531 }
8532 /* There are still running processes in the fg_pipe */
8533 return -1;
8534 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008535 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008536 }
8537
8538#if ENABLE_HUSH_JOB
8539 /* We were asked to wait for bg or orphaned children */
8540 /* No need to remember exitcode in this case */
8541 for (pi = G.job_list; pi; pi = pi->next) {
8542 for (i = 0; i < pi->num_cmds; i++) {
8543 if (pi->cmds[i].pid == childpid)
8544 goto found_pi_and_prognum;
8545 }
8546 }
8547 /* Happens when shell is used as init process (init=/bin/sh) */
8548 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8549 return -1; /* this wasn't a process from fg_pipe */
8550
8551 found_pi_and_prognum:
8552 if (dead) {
8553 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008554 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008555 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008556 rcode = 128 + WTERMSIG(status);
8557 pi->cmds[i].cmd_exitcode = rcode;
8558 if (G.last_bg_pid == pi->cmds[i].pid)
8559 G.last_bg_pid_exitcode = rcode;
8560 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008561 pi->alive_cmds--;
8562 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008563 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008564 printf(JOB_STATUS_FORMAT, pi->jobid,
8565 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008566 delete_finished_job(pi);
8567 } else {
8568/*
8569 * bash deletes finished jobs from job table only in interactive mode,
8570 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8571 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8572 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8573 * We only retain one "dead" job, if it's the single job on the list.
8574 * This covers most of real-world scenarios where this is useful.
8575 */
8576 if (pi != G.job_list)
8577 delete_finished_job(pi);
8578 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008579 }
8580 } else {
8581 /* child stopped */
8582 pi->stopped_cmds++;
8583 }
8584#endif
8585 return -1; /* this wasn't a process from fg_pipe */
8586}
8587
8588/* Check to see if any processes have exited -- if they have,
8589 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008590 *
8591 * If non-NULL fg_pipe: wait for its completion or stop.
8592 * Return its exitcode or zero if stopped.
8593 *
8594 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8595 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8596 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8597 * or 0 if no children changed status.
8598 *
8599 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8600 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8601 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008602 */
8603static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8604{
8605 int attributes;
8606 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008607 int rcode = 0;
8608
8609 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8610
8611 attributes = WUNTRACED;
8612 if (fg_pipe == NULL)
8613 attributes |= WNOHANG;
8614
8615 errno = 0;
8616#if ENABLE_HUSH_FAST
8617 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8618//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8619//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8620 /* There was neither fork nor SIGCHLD since last waitpid */
8621 /* Avoid doing waitpid syscall if possible */
8622 if (!G.we_have_children) {
8623 errno = ECHILD;
8624 return -1;
8625 }
8626 if (fg_pipe == NULL) { /* is WNOHANG set? */
8627 /* We have children, but they did not exit
8628 * or stop yet (we saw no SIGCHLD) */
8629 return 0;
8630 }
8631 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8632 }
8633#endif
8634
8635/* Do we do this right?
8636 * bash-3.00# sleep 20 | false
8637 * <ctrl-Z pressed>
8638 * [3]+ Stopped sleep 20 | false
8639 * bash-3.00# echo $?
8640 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8641 * [hush 1.14.0: yes we do it right]
8642 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008643 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008644 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008645#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008646 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008647 i = G.count_SIGCHLD;
8648#endif
8649 childpid = waitpid(-1, &status, attributes);
8650 if (childpid <= 0) {
8651 if (childpid && errno != ECHILD)
8652 bb_perror_msg("waitpid");
8653#if ENABLE_HUSH_FAST
8654 else { /* Until next SIGCHLD, waitpid's are useless */
8655 G.we_have_children = (childpid == 0);
8656 G.handled_SIGCHLD = i;
8657//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8658 }
8659#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008660 /* ECHILD (no children), or 0 (no change in children status) */
8661 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008662 break;
8663 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008664 rcode = process_wait_result(fg_pipe, childpid, status);
8665 if (rcode >= 0) {
8666 /* fg_pipe exited or stopped */
8667 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008668 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008669 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008670 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008671 rcode = WEXITSTATUS(status);
8672 if (WIFSIGNALED(status))
8673 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008674 if (WIFSTOPPED(status))
8675 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8676 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008677 rcode++;
8678 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008679 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008680 /* This wasn't one of our processes, or */
8681 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008682 } /* while (waitpid succeeds)... */
8683
8684 return rcode;
8685}
8686
8687#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008688static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008689{
8690 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008691 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008692 if (G_saved_tty_pgrp) {
8693 /* Job finished, move the shell to the foreground */
8694 p = getpgrp(); /* our process group id */
8695 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8696 tcsetpgrp(G_interactive_fd, p);
8697 }
8698 return rcode;
8699}
8700#endif
8701
8702/* Start all the jobs, but don't wait for anything to finish.
8703 * See checkjobs().
8704 *
8705 * Return code is normally -1, when the caller has to wait for children
8706 * to finish to determine the exit status of the pipe. If the pipe
8707 * is a simple builtin command, however, the action is done by the
8708 * time run_pipe returns, and the exit code is provided as the
8709 * return value.
8710 *
8711 * Returns -1 only if started some children. IOW: we have to
8712 * mask out retvals of builtins etc with 0xff!
8713 *
8714 * The only case when we do not need to [v]fork is when the pipe
8715 * is single, non-backgrounded, non-subshell command. Examples:
8716 * cmd ; ... { list } ; ...
8717 * cmd && ... { list } && ...
8718 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008719 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008720 * or (if SH_STANDALONE) an applet, and we can run the { list }
8721 * with run_list. If it isn't one of these, we fork and exec cmd.
8722 *
8723 * Cases when we must fork:
8724 * non-single: cmd | cmd
8725 * backgrounded: cmd & { list } &
8726 * subshell: ( list ) [&]
8727 */
8728#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008729#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8730 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008731#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008732static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008733 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008734 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008735 char **argv_expanded)
8736{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008737 /* Assignments occur before redirects. Try:
8738 * a=`sleep 1` sleep 2 3>/qwe/rty
8739 */
8740
8741 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8742 dump_cmd_in_x_mode(new_env);
8743 dump_cmd_in_x_mode(argv_expanded);
8744 /* this takes ownership of new_env[i] elements, and frees new_env: */
8745 set_vars_and_save_old(new_env);
8746
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008747 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008748}
8749static NOINLINE int run_pipe(struct pipe *pi)
8750{
8751 static const char *const null_ptr = NULL;
8752
8753 int cmd_no;
8754 int next_infd;
8755 struct command *command;
8756 char **argv_expanded;
8757 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008758 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008759 int rcode;
8760
8761 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8762 debug_enter();
8763
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008764 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8765 * Result should be 3 lines: q w e, qwe, q w e
8766 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008767 if (G.ifs_whitespace != G.ifs)
8768 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008769 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008770 if (G.ifs) {
8771 char *p;
8772 G.ifs_whitespace = (char*)G.ifs;
8773 p = skip_whitespace(G.ifs);
8774 if (*p) {
8775 /* Not all $IFS is whitespace */
8776 char *d;
8777 int len = p - G.ifs;
8778 p = skip_non_whitespace(p);
8779 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8780 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8781 while (*p) {
8782 if (isspace(*p))
8783 *d++ = *p;
8784 p++;
8785 }
8786 *d = '\0';
8787 }
8788 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008789 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008790 G.ifs_whitespace = (char*)G.ifs;
8791 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008792
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008793 IF_HUSH_JOB(pi->pgrp = -1;)
8794 pi->stopped_cmds = 0;
8795 command = &pi->cmds[0];
8796 argv_expanded = NULL;
8797
8798 if (pi->num_cmds != 1
8799 || pi->followup == PIPE_BG
8800 || command->cmd_type == CMD_SUBSHELL
8801 ) {
8802 goto must_fork;
8803 }
8804
8805 pi->alive_cmds = 1;
8806
8807 debug_printf_exec(": group:%p argv:'%s'\n",
8808 command->group, command->argv ? command->argv[0] : "NONE");
8809
8810 if (command->group) {
8811#if ENABLE_HUSH_FUNCTIONS
8812 if (command->cmd_type == CMD_FUNCDEF) {
8813 /* "executing" func () { list } */
8814 struct function *funcp;
8815
8816 funcp = new_function(command->argv[0]);
8817 /* funcp->name is already set to argv[0] */
8818 funcp->body = command->group;
8819# if !BB_MMU
8820 funcp->body_as_string = command->group_as_string;
8821 command->group_as_string = NULL;
8822# endif
8823 command->group = NULL;
8824 command->argv[0] = NULL;
8825 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8826 funcp->parent_cmd = command;
8827 command->child_func = funcp;
8828
8829 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8830 debug_leave();
8831 return EXIT_SUCCESS;
8832 }
8833#endif
8834 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008835 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008836 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008837 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008838 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008839//FIXME: we need to pass squirrel down into run_list()
8840//for SH_STANDALONE case, or else this construct:
8841// { find /proc/self/fd; true; } >FILE; cmd2
8842//has no way of closing saved fd#1 for "find",
8843//and in SH_STANDALONE mode, "find" is not execed,
8844//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008845 rcode = run_list(command->group) & 0xff;
8846 }
8847 restore_redirects(squirrel);
8848 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8849 debug_leave();
8850 debug_printf_exec("run_pipe: return %d\n", rcode);
8851 return rcode;
8852 }
8853
8854 argv = command->argv ? command->argv : (char **) &null_ptr;
8855 {
8856 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008857 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8858 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008859 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008860 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008861
Denys Vlasenko5807e182018-02-08 19:19:04 +01008862#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008863 if (G.lineno_var)
8864 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8865#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008866
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008867 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008868 /* Assignments, but no command.
8869 * Ensure redirects take effect (that is, create files).
8870 * Try "a=t >file"
8871 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008872 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008873 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008874 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008875 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008876 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008877
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008878 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008879 i = 0;
8880 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008881 char *p = expand_string_to_string(argv[i],
8882 EXP_FLAG_ESC_GLOB_CHARS,
8883 /*unbackslash:*/ 1
8884 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008885#if ENABLE_HUSH_MODE_X
8886 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008887 char *eq;
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008888 if (i == 0) {
8889 unsigned n = G.x_mode_depth;
8890 do
8891 bb_putchar_stderr('+');
8892 while ((int)(--n) >= 0);
8893 }
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008894 eq = strchrnul(p, '=');
8895 fprintf(stderr, " %.*s=", (int)(eq - p), p);
8896 if (*eq)
8897 print_optionally_squoted(stderr, eq + 1);
8898 bb_putchar_stderr('\n');
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008899 }
8900#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008901 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008902 if (set_local_var(p, /*flag:*/ 0)) {
8903 /* assignment to readonly var / putenv error? */
8904 rcode = 1;
8905 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008906 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008907 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008908 /* Redirect error sets $? to 1. Otherwise,
8909 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008910 * Else, clear $?:
8911 * false; q=`exit 2`; echo $? - should print 2
8912 * false; x=1; echo $? - should print 0
8913 * Because of the 2nd case, we can't just use G.last_exitcode.
8914 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008915 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008916 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008917 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8918 debug_leave();
8919 debug_printf_exec("run_pipe: return %d\n", rcode);
8920 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008921 }
8922
8923 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008924#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008925 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008926 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008927 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008928#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008929 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008930
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008931 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008932 if (!argv_expanded[0]) {
8933 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008934 /* `false` still has to set exitcode 1 */
8935 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008936 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008937 }
8938
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008939 old_vars = NULL;
8940 sv_shadowed = G.shadowed_vars_pp;
8941
Denys Vlasenko75481d32017-07-31 05:27:09 +02008942 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008943 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8944 IF_HUSH_FUNCTIONS(x = NULL;)
8945 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008946 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008947 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008948 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8949 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008950 /*
8951 * Variable assignments are executed, but then "forgotten":
8952 * a=`sleep 1;echo A` exec 3>&-; echo $a
8953 * sleeps, but prints nothing.
8954 */
8955 enter_var_nest_level();
8956 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008957 rcode = redirect_and_varexp_helper(command,
8958 /*squirrel:*/ ERR_PTR,
8959 argv_expanded
8960 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008961 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008962 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008963
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008964 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008965 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008966
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008967 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008968 * a=b true; env | grep ^a=
8969 */
8970 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008971 /* Collect all variables "shadowed" by helper
8972 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8973 * into old_vars list:
8974 */
8975 G.shadowed_vars_pp = &old_vars;
8976 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008977 if (rcode == 0) {
8978 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008979 /* Do not collect *to old_vars list* vars shadowed
8980 * by e.g. "local VAR" builtin (collect them
8981 * in the previously nested list instead):
8982 * don't want them to be restored immediately
8983 * after "local" completes.
8984 */
8985 G.shadowed_vars_pp = sv_shadowed;
8986
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008987 debug_printf_exec(": builtin '%s' '%s'...\n",
8988 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008989 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008990 rcode = x->b_function(argv_expanded) & 0xff;
8991 fflush_all();
8992 }
8993#if ENABLE_HUSH_FUNCTIONS
8994 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008995 debug_printf_exec(": function '%s' '%s'...\n",
8996 funcp->name, argv_expanded[1]);
8997 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008998 /*
8999 * But do collect *to old_vars list* vars shadowed
9000 * within function execution. To that end, restore
9001 * this pointer _after_ function run:
9002 */
9003 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009004 }
9005#endif
9006 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009007 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009008 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009009 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009010 if (n < 0 || !APPLET_IS_NOFORK(n))
9011 goto must_fork;
9012
9013 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009014 /* Collect all variables "shadowed" by helper into old_vars list */
9015 G.shadowed_vars_pp = &old_vars;
9016 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9017 G.shadowed_vars_pp = sv_shadowed;
9018
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009019 if (rcode == 0) {
9020 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9021 argv_expanded[0], argv_expanded[1]);
9022 /*
9023 * Note: signals (^C) can't interrupt here.
9024 * We remember them and they will be acted upon
9025 * after applet returns.
9026 * This makes applets which can run for a long time
9027 * and/or wait for user input ineligible for NOFORK:
9028 * for example, "yes" or "rm" (rm -i waits for input).
9029 */
9030 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009031 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009032 } else
9033 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009034
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009035 restore_redirects(squirrel);
9036 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009037 leave_var_nest_level();
9038 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009039
9040 /*
9041 * Try "usleep 99999999" + ^C + "echo $?"
9042 * with FEATURE_SH_NOFORK=y.
9043 */
9044 if (!funcp) {
9045 /* It was builtin or nofork.
9046 * if this would be a real fork/execed program,
9047 * it should have died if a fatal sig was received.
9048 * But OTOH, there was no separate process,
9049 * the sig was sent to _shell_, not to non-existing
9050 * child.
9051 * Let's just handle ^C only, this one is obvious:
9052 * we aren't ok with exitcode 0 when ^C was pressed
9053 * during builtin/nofork.
9054 */
9055 if (sigismember(&G.pending_set, SIGINT))
9056 rcode = 128 + SIGINT;
9057 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009058 free(argv_expanded);
9059 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9060 debug_leave();
9061 debug_printf_exec("run_pipe return %d\n", rcode);
9062 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009063 }
9064
9065 must_fork:
9066 /* NB: argv_expanded may already be created, and that
9067 * might include `cmd` runs! Do not rerun it! We *must*
9068 * use argv_expanded if it's non-NULL */
9069
9070 /* Going to fork a child per each pipe member */
9071 pi->alive_cmds = 0;
9072 next_infd = 0;
9073
9074 cmd_no = 0;
9075 while (cmd_no < pi->num_cmds) {
9076 struct fd_pair pipefds;
9077#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009078 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009079 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009080 nommu_save.old_vars = NULL;
9081 nommu_save.argv = NULL;
9082 nommu_save.argv_from_re_execing = NULL;
9083#endif
9084 command = &pi->cmds[cmd_no];
9085 cmd_no++;
9086 if (command->argv) {
9087 debug_printf_exec(": pipe member '%s' '%s'...\n",
9088 command->argv[0], command->argv[1]);
9089 } else {
9090 debug_printf_exec(": pipe member with no argv\n");
9091 }
9092
9093 /* pipes are inserted between pairs of commands */
9094 pipefds.rd = 0;
9095 pipefds.wr = 1;
9096 if (cmd_no < pi->num_cmds)
9097 xpiped_pair(pipefds);
9098
Denys Vlasenko5807e182018-02-08 19:19:04 +01009099#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009100 if (G.lineno_var)
9101 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9102#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009103
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009104 command->pid = BB_MMU ? fork() : vfork();
9105 if (!command->pid) { /* child */
9106#if ENABLE_HUSH_JOB
9107 disable_restore_tty_pgrp_on_exit();
9108 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9109
9110 /* Every child adds itself to new process group
9111 * with pgid == pid_of_first_child_in_pipe */
9112 if (G.run_list_level == 1 && G_interactive_fd) {
9113 pid_t pgrp;
9114 pgrp = pi->pgrp;
9115 if (pgrp < 0) /* true for 1st process only */
9116 pgrp = getpid();
9117 if (setpgid(0, pgrp) == 0
9118 && pi->followup != PIPE_BG
9119 && G_saved_tty_pgrp /* we have ctty */
9120 ) {
9121 /* We do it in *every* child, not just first,
9122 * to avoid races */
9123 tcsetpgrp(G_interactive_fd, pgrp);
9124 }
9125 }
9126#endif
9127 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9128 /* 1st cmd in backgrounded pipe
9129 * should have its stdin /dev/null'ed */
9130 close(0);
9131 if (open(bb_dev_null, O_RDONLY))
9132 xopen("/", O_RDONLY);
9133 } else {
9134 xmove_fd(next_infd, 0);
9135 }
9136 xmove_fd(pipefds.wr, 1);
9137 if (pipefds.rd > 1)
9138 close(pipefds.rd);
9139 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009140 * and the pipe fd (fd#1) is available for dup'ing:
9141 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9142 * of cmd1 goes into pipe.
9143 */
9144 if (setup_redirects(command, NULL)) {
9145 /* Happens when redir file can't be opened:
9146 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9147 * FOO
9148 * hush: can't open '/qwe/rty': No such file or directory
9149 * BAZ
9150 * (echo BAR is not executed, it hits _exit(1) below)
9151 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009152 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009153 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009154
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009155 /* Stores to nommu_save list of env vars putenv'ed
9156 * (NOMMU, on MMU we don't need that) */
9157 /* cast away volatility... */
9158 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9159 /* pseudo_exec() does not return */
9160 }
9161
9162 /* parent or error */
9163#if ENABLE_HUSH_FAST
9164 G.count_SIGCHLD++;
9165//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9166#endif
9167 enable_restore_tty_pgrp_on_exit();
9168#if !BB_MMU
9169 /* Clean up after vforked child */
9170 free(nommu_save.argv);
9171 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009172 G.var_nest_level = sv_var_nest_level;
9173 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009174 add_vars(nommu_save.old_vars);
9175#endif
9176 free(argv_expanded);
9177 argv_expanded = NULL;
9178 if (command->pid < 0) { /* [v]fork failed */
9179 /* Clearly indicate, was it fork or vfork */
9180 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9181 } else {
9182 pi->alive_cmds++;
9183#if ENABLE_HUSH_JOB
9184 /* Second and next children need to know pid of first one */
9185 if (pi->pgrp < 0)
9186 pi->pgrp = command->pid;
9187#endif
9188 }
9189
9190 if (cmd_no > 1)
9191 close(next_infd);
9192 if (cmd_no < pi->num_cmds)
9193 close(pipefds.wr);
9194 /* Pass read (output) pipe end to next iteration */
9195 next_infd = pipefds.rd;
9196 }
9197
9198 if (!pi->alive_cmds) {
9199 debug_leave();
9200 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9201 return 1;
9202 }
9203
9204 debug_leave();
9205 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9206 return -1;
9207}
9208
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009209/* NB: called by pseudo_exec, and therefore must not modify any
9210 * global data until exec/_exit (we can be a child after vfork!) */
9211static int run_list(struct pipe *pi)
9212{
9213#if ENABLE_HUSH_CASE
9214 char *case_word = NULL;
9215#endif
9216#if ENABLE_HUSH_LOOPS
9217 struct pipe *loop_top = NULL;
9218 char **for_lcur = NULL;
9219 char **for_list = NULL;
9220#endif
9221 smallint last_followup;
9222 smalluint rcode;
9223#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9224 smalluint cond_code = 0;
9225#else
9226 enum { cond_code = 0 };
9227#endif
9228#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009229 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009230 smallint last_rword; /* ditto */
9231#endif
9232
9233 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9234 debug_enter();
9235
9236#if ENABLE_HUSH_LOOPS
9237 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009238 {
9239 struct pipe *cpipe;
9240 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9241 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9242 continue;
9243 /* current word is FOR or IN (BOLD in comments below) */
9244 if (cpipe->next == NULL) {
9245 syntax_error("malformed for");
9246 debug_leave();
9247 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9248 return 1;
9249 }
9250 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9251 if (cpipe->next->res_word == RES_DO)
9252 continue;
9253 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9254 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9255 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9256 ) {
9257 syntax_error("malformed for");
9258 debug_leave();
9259 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9260 return 1;
9261 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009262 }
9263 }
9264#endif
9265
9266 /* Past this point, all code paths should jump to ret: label
9267 * in order to return, no direct "return" statements please.
9268 * This helps to ensure that no memory is leaked. */
9269
9270#if ENABLE_HUSH_JOB
9271 G.run_list_level++;
9272#endif
9273
9274#if HAS_KEYWORDS
9275 rword = RES_NONE;
9276 last_rword = RES_XXXX;
9277#endif
9278 last_followup = PIPE_SEQ;
9279 rcode = G.last_exitcode;
9280
9281 /* Go through list of pipes, (maybe) executing them. */
9282 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009283 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009284 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009285
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009286 if (G.flag_SIGINT)
9287 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009288 if (G_flag_return_in_progress == 1)
9289 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009290
9291 IF_HAS_KEYWORDS(rword = pi->res_word;)
9292 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9293 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009294
9295 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009296 if (
9297#if ENABLE_HUSH_IF
9298 rword == RES_IF || rword == RES_ELIF ||
9299#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009300 pi->followup != PIPE_SEQ
9301 ) {
9302 G.errexit_depth++;
9303 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009304#if ENABLE_HUSH_LOOPS
9305 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9306 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9307 ) {
9308 /* start of a loop: remember where loop starts */
9309 loop_top = pi;
9310 G.depth_of_loop++;
9311 }
9312#endif
9313 /* Still in the same "if...", "then..." or "do..." branch? */
9314 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9315 if ((rcode == 0 && last_followup == PIPE_OR)
9316 || (rcode != 0 && last_followup == PIPE_AND)
9317 ) {
9318 /* It is "<true> || CMD" or "<false> && CMD"
9319 * and we should not execute CMD */
9320 debug_printf_exec("skipped cmd because of || or &&\n");
9321 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009322 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009323 }
9324 }
9325 last_followup = pi->followup;
9326 IF_HAS_KEYWORDS(last_rword = rword;)
9327#if ENABLE_HUSH_IF
9328 if (cond_code) {
9329 if (rword == RES_THEN) {
9330 /* if false; then ... fi has exitcode 0! */
9331 G.last_exitcode = rcode = EXIT_SUCCESS;
9332 /* "if <false> THEN cmd": skip cmd */
9333 continue;
9334 }
9335 } else {
9336 if (rword == RES_ELSE || rword == RES_ELIF) {
9337 /* "if <true> then ... ELSE/ELIF cmd":
9338 * skip cmd and all following ones */
9339 break;
9340 }
9341 }
9342#endif
9343#if ENABLE_HUSH_LOOPS
9344 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9345 if (!for_lcur) {
9346 /* first loop through for */
9347
9348 static const char encoded_dollar_at[] ALIGN1 = {
9349 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9350 }; /* encoded representation of "$@" */
9351 static const char *const encoded_dollar_at_argv[] = {
9352 encoded_dollar_at, NULL
9353 }; /* argv list with one element: "$@" */
9354 char **vals;
9355
9356 vals = (char**)encoded_dollar_at_argv;
9357 if (pi->next->res_word == RES_IN) {
9358 /* if no variable values after "in" we skip "for" */
9359 if (!pi->next->cmds[0].argv) {
9360 G.last_exitcode = rcode = EXIT_SUCCESS;
9361 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9362 break;
9363 }
9364 vals = pi->next->cmds[0].argv;
9365 } /* else: "for var; do..." -> assume "$@" list */
9366 /* create list of variable values */
9367 debug_print_strings("for_list made from", vals);
9368 for_list = expand_strvec_to_strvec(vals);
9369 for_lcur = for_list;
9370 debug_print_strings("for_list", for_list);
9371 }
9372 if (!*for_lcur) {
9373 /* "for" loop is over, clean up */
9374 free(for_list);
9375 for_list = NULL;
9376 for_lcur = NULL;
9377 break;
9378 }
9379 /* Insert next value from for_lcur */
9380 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009381 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009382 continue;
9383 }
9384 if (rword == RES_IN) {
9385 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9386 }
9387 if (rword == RES_DONE) {
9388 continue; /* "done" has no cmds too */
9389 }
9390#endif
9391#if ENABLE_HUSH_CASE
9392 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009393 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009394 case_word = expand_string_to_string(pi->cmds->argv[0],
9395 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009396 debug_printf_exec("CASE word1:'%s'\n", case_word);
9397 //unbackslash(case_word);
9398 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009399 continue;
9400 }
9401 if (rword == RES_MATCH) {
9402 char **argv;
9403
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009404 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009405 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9406 break;
9407 /* all prev words didn't match, does this one match? */
9408 argv = pi->cmds->argv;
9409 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009410 char *pattern;
9411 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9412 pattern = expand_string_to_string(*argv,
9413 EXP_FLAG_ESC_GLOB_CHARS,
9414 /*unbackslash:*/ 0
9415 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009416 /* TODO: which FNM_xxx flags to use? */
9417 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009418 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9419 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009420 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009421 if (cond_code == 0) {
9422 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009423 free(case_word);
9424 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009425 break;
9426 }
9427 argv++;
9428 }
9429 continue;
9430 }
9431 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009432 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009433 if (cond_code != 0)
9434 continue; /* not matched yet, skip this pipe */
9435 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009436 if (rword == RES_ESAC) {
9437 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9438 if (case_word) {
9439 /* "case" did not match anything: still set $? (to 0) */
9440 G.last_exitcode = rcode = EXIT_SUCCESS;
9441 }
9442 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009443#endif
9444 /* Just pressing <enter> in shell should check for jobs.
9445 * OTOH, in non-interactive shell this is useless
9446 * and only leads to extra job checks */
9447 if (pi->num_cmds == 0) {
9448 if (G_interactive_fd)
9449 goto check_jobs_and_continue;
9450 continue;
9451 }
9452
9453 /* After analyzing all keywords and conditions, we decided
9454 * to execute this pipe. NB: have to do checkjobs(NULL)
9455 * after run_pipe to collect any background children,
9456 * even if list execution is to be stopped. */
9457 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009458#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009459 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009460#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009461 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9462 if (r != -1) {
9463 /* We ran a builtin, function, or group.
9464 * rcode is already known
9465 * and we don't need to wait for anything. */
9466 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9467 G.last_exitcode = rcode;
9468 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009469#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009470 /* Was it "break" or "continue"? */
9471 if (G.flag_break_continue) {
9472 smallint fbc = G.flag_break_continue;
9473 /* We might fall into outer *loop*,
9474 * don't want to break it too */
9475 if (loop_top) {
9476 G.depth_break_continue--;
9477 if (G.depth_break_continue == 0)
9478 G.flag_break_continue = 0;
9479 /* else: e.g. "continue 2" should *break* once, *then* continue */
9480 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9481 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009482 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009483 break;
9484 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009485 /* "continue": simulate end of loop */
9486 rword = RES_DONE;
9487 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009488 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009489#endif
9490 if (G_flag_return_in_progress == 1) {
9491 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9492 break;
9493 }
9494 } else if (pi->followup == PIPE_BG) {
9495 /* What does bash do with attempts to background builtins? */
9496 /* even bash 3.2 doesn't do that well with nested bg:
9497 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9498 * I'm NOT treating inner &'s as jobs */
9499#if ENABLE_HUSH_JOB
9500 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009501 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009502#endif
9503 /* Last command's pid goes to $! */
9504 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009505 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009506 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009507/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009508 rcode = EXIT_SUCCESS;
9509 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009510 } else {
9511#if ENABLE_HUSH_JOB
9512 if (G.run_list_level == 1 && G_interactive_fd) {
9513 /* Waits for completion, then fg's main shell */
9514 rcode = checkjobs_and_fg_shell(pi);
9515 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009516 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009517 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009518#endif
9519 /* This one just waits for completion */
9520 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9521 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9522 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009523 G.last_exitcode = rcode;
9524 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009525 }
9526
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009527 /* Handle "set -e" */
9528 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9529 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9530 if (G.errexit_depth == 0)
9531 hush_exit(rcode);
9532 }
9533 G.errexit_depth = sv_errexit_depth;
9534
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009535 /* Analyze how result affects subsequent commands */
9536#if ENABLE_HUSH_IF
9537 if (rword == RES_IF || rword == RES_ELIF)
9538 cond_code = rcode;
9539#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009540 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009541 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009542 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009543#if ENABLE_HUSH_LOOPS
9544 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009545 if (pi->next
9546 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009547 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009548 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009549 if (rword == RES_WHILE) {
9550 if (rcode) {
9551 /* "while false; do...done" - exitcode 0 */
9552 G.last_exitcode = rcode = EXIT_SUCCESS;
9553 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009554 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009555 }
9556 }
9557 if (rword == RES_UNTIL) {
9558 if (!rcode) {
9559 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009560 break;
9561 }
9562 }
9563 }
9564#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009565 } /* for (pi) */
9566
9567#if ENABLE_HUSH_JOB
9568 G.run_list_level--;
9569#endif
9570#if ENABLE_HUSH_LOOPS
9571 if (loop_top)
9572 G.depth_of_loop--;
9573 free(for_list);
9574#endif
9575#if ENABLE_HUSH_CASE
9576 free(case_word);
9577#endif
9578 debug_leave();
9579 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9580 return rcode;
9581}
9582
9583/* Select which version we will use */
9584static int run_and_free_list(struct pipe *pi)
9585{
9586 int rcode = 0;
9587 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009588 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009589 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9590 rcode = run_list(pi);
9591 }
9592 /* free_pipe_list has the side effect of clearing memory.
9593 * In the long run that function can be merged with run_list,
9594 * but doing that now would hobble the debugging effort. */
9595 free_pipe_list(pi);
9596 debug_printf_exec("run_and_free_list return %d\n", rcode);
9597 return rcode;
9598}
9599
9600
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009601static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009602{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009603 sighandler_t old_handler;
9604 unsigned sig = 0;
9605 while ((mask >>= 1) != 0) {
9606 sig++;
9607 if (!(mask & 1))
9608 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009609 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009610 /* POSIX allows shell to re-enable SIGCHLD
9611 * even if it was SIG_IGN on entry.
9612 * Therefore we skip IGN check for it:
9613 */
9614 if (sig == SIGCHLD)
9615 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009616 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9617 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9618 */
9619 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009620 if (old_handler == SIG_IGN) {
9621 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009622 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009623#if ENABLE_HUSH_TRAP
9624 if (!G_traps)
9625 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9626 free(G_traps[sig]);
9627 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9628#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009629 }
9630 }
9631}
9632
9633/* Called a few times only (or even once if "sh -c") */
9634static void install_special_sighandlers(void)
9635{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009636 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009637
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009638 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009639 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009640 if (G_interactive_fd) {
9641 mask |= SPECIAL_INTERACTIVE_SIGS;
9642 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009643 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009644 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009645 /* Careful, do not re-install handlers we already installed */
9646 if (G.special_sig_mask != mask) {
9647 unsigned diff = mask & ~G.special_sig_mask;
9648 G.special_sig_mask = mask;
9649 install_sighandlers(diff);
9650 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009651}
9652
9653#if ENABLE_HUSH_JOB
9654/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009655/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009656static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009657{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009658 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009659
9660 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009661 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009662 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9663 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009664 + (1 << SIGBUS ) * HUSH_DEBUG
9665 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009666 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009667 + (1 << SIGABRT)
9668 /* bash 3.2 seems to handle these just like 'fatal' ones */
9669 + (1 << SIGPIPE)
9670 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009671 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009672 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009673 * we never want to restore pgrp on exit, and this fn is not called
9674 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009675 /*+ (1 << SIGHUP )*/
9676 /*+ (1 << SIGTERM)*/
9677 /*+ (1 << SIGINT )*/
9678 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009679 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009680
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009681 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009682}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009683#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009684
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009685static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009686{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009687 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009688 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009689 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009690 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009691 break;
9692 case 'x':
9693 IF_HUSH_MODE_X(G_x_mode = state;)
9694 break;
9695 case 'o':
9696 if (!o_opt) {
9697 /* "set -+o" without parameter.
9698 * in bash, set -o produces this output:
9699 * pipefail off
9700 * and set +o:
9701 * set +o pipefail
9702 * We always use the second form.
9703 */
9704 const char *p = o_opt_strings;
9705 idx = 0;
9706 while (*p) {
9707 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9708 idx++;
9709 p += strlen(p) + 1;
9710 }
9711 break;
9712 }
9713 idx = index_in_strings(o_opt_strings, o_opt);
9714 if (idx >= 0) {
9715 G.o_opt[idx] = state;
9716 break;
9717 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009718 case 'e':
9719 G.o_opt[OPT_O_ERREXIT] = state;
9720 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009721 default:
9722 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009723 }
9724 return EXIT_SUCCESS;
9725}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009726
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009727int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009728int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009729{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009730 enum {
9731 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009732 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009733 };
9734 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009735 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009736 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009737 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009738 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009739
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009740 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009741 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009742 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009743
Denys Vlasenko10c01312011-05-11 11:49:21 +02009744#if ENABLE_HUSH_FAST
9745 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9746#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009747#if !BB_MMU
9748 G.argv0_for_re_execing = argv[0];
9749#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009750
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009751 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009752 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9753 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009754 shell_ver = xzalloc(sizeof(*shell_ver));
9755 shell_ver->flg_export = 1;
9756 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009757 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009758 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009759 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009760
Denys Vlasenko605067b2010-09-06 12:10:51 +02009761 /* Create shell local variables from the values
9762 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009763 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009764 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009765 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009766 if (e) while (*e) {
9767 char *value = strchr(*e, '=');
9768 if (value) { /* paranoia */
9769 cur_var->next = xzalloc(sizeof(*cur_var));
9770 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009771 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009772 cur_var->max_len = strlen(*e);
9773 cur_var->flg_export = 1;
9774 }
9775 e++;
9776 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009777 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009778 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9779 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009780
9781 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009782 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009783
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009784#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9785 /* Set (but not export) PS1/2 unless already set */
9786 if (!get_local_var_value("PS1"))
9787 set_local_var_from_halves("PS1", "\\w \\$ ");
9788 if (!get_local_var_value("PS2"))
9789 set_local_var_from_halves("PS2", "> ");
9790#endif
9791
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009792#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009793 /* Set (but not export) HOSTNAME unless already set */
9794 if (!get_local_var_value("HOSTNAME")) {
9795 struct utsname uts;
9796 uname(&uts);
9797 set_local_var_from_halves("HOSTNAME", uts.nodename);
9798 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009799 /* bash also exports SHLVL and _,
9800 * and sets (but doesn't export) the following variables:
9801 * BASH=/bin/bash
9802 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9803 * BASH_VERSION='3.2.0(1)-release'
9804 * HOSTTYPE=i386
9805 * MACHTYPE=i386-pc-linux-gnu
9806 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009807 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009808 * EUID=<NNNNN>
9809 * UID=<NNNNN>
9810 * GROUPS=()
9811 * LINES=<NNN>
9812 * COLUMNS=<NNN>
9813 * BASH_ARGC=()
9814 * BASH_ARGV=()
9815 * BASH_LINENO=()
9816 * BASH_SOURCE=()
9817 * DIRSTACK=()
9818 * PIPESTATUS=([0]="0")
9819 * HISTFILE=/<xxx>/.bash_history
9820 * HISTFILESIZE=500
9821 * HISTSIZE=500
9822 * MAILCHECK=60
9823 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9824 * SHELL=/bin/bash
9825 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9826 * TERM=dumb
9827 * OPTERR=1
9828 * OPTIND=1
9829 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009830 * PS4='+ '
9831 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009832#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009833
Denys Vlasenko5807e182018-02-08 19:19:04 +01009834#if ENABLE_HUSH_LINENO_VAR
9835 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009836 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9837 set_local_var(p, /*flags*/ 0);
9838 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9839 }
9840#endif
9841
Denis Vlasenko38f63192007-01-22 09:03:07 +00009842#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009843 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009844#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009845
Eric Andersen94ac2442001-05-22 19:05:18 +00009846 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009847 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009848
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009849 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009850
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009851 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009852 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009853 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009854 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009855 * in order to intercept (more) signals.
9856 */
9857
9858 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009859 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009860 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009861 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009862 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009863 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009864#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009865 "<:$:R:V:"
9866# if ENABLE_HUSH_FUNCTIONS
9867 "F:"
9868# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009869#endif
9870 );
9871 if (opt <= 0)
9872 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009873 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009874 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009875 /* Possibilities:
9876 * sh ... -c 'script'
9877 * sh ... -c 'script' ARG0 [ARG1...]
9878 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009879 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009880 * "" needs to be replaced with NULL
9881 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009882 * Note: the form without ARG0 never happens:
9883 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009884 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009885 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009886 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009887 G.root_ppid = getppid();
9888 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009889 G.global_argv = argv + optind;
9890 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009891 if (builtin_argc) {
9892 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9893 const struct built_in_command *x;
9894
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009895 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009896 x = find_builtin(optarg);
9897 if (x) { /* paranoia */
9898 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9899 G.global_argv += builtin_argc;
9900 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009901 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009902 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009903 }
9904 goto final_return;
9905 }
9906 if (!G.global_argv[0]) {
9907 /* -c 'script' (no params): prevent empty $0 */
9908 G.global_argv--; /* points to argv[i] of 'script' */
9909 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009910 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009911 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009912 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009913 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009914 goto final_return;
9915 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009916 /* Well, we cannot just declare interactiveness,
9917 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009918 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009919 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009920 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009921 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009922 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009923 case 'l':
9924 flags |= OPT_login;
9925 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009926#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009927 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009928 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009929 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009930 case '$': {
9931 unsigned long long empty_trap_mask;
9932
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009933 G.root_pid = bb_strtou(optarg, &optarg, 16);
9934 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009935 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9936 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009937 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9938 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009939 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009940 optarg++;
9941 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009942 optarg++;
9943 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9944 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009945 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009946 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009947# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009948 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009949 for (sig = 1; sig < NSIG; sig++) {
9950 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009951 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009952 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009953 }
9954 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009955# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009956 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009957# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009958 optarg++;
9959 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009960# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009961# if ENABLE_HUSH_FUNCTIONS
9962 /* nommu uses re-exec trick for "... | func | ...",
9963 * should allow "return".
9964 * This accidentally allows returns in subshells.
9965 */
9966 G_flag_return_in_progress = -1;
9967# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009968 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009969 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009970 case 'R':
9971 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009972 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009973 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009974# if ENABLE_HUSH_FUNCTIONS
9975 case 'F': {
9976 struct function *funcp = new_function(optarg);
9977 /* funcp->name is already set to optarg */
9978 /* funcp->body is set to NULL. It's a special case. */
9979 funcp->body_as_string = argv[optind];
9980 optind++;
9981 break;
9982 }
9983# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009984#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009985 case 'n':
9986 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009987 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009988 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009989 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009990 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009991#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009992 fprintf(stderr, "Usage: sh [FILE]...\n"
9993 " or: sh -c command [args]...\n\n");
9994 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009995#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009996 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009997#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009998 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009999 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010000
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010001 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10002 G.global_argc = argc - (optind - 1);
10003 G.global_argv = argv + (optind - 1);
10004 G.global_argv[0] = argv[0];
10005
Denys Vlasenkodea47882009-10-09 15:40:49 +020010006 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010007 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010008 G.root_ppid = getppid();
10009 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010010
10011 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010012 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010013 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010014 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010015 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010016 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010017 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010018 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010019 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010020 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010021 /* bash: after sourcing /etc/profile,
10022 * tries to source (in the given order):
10023 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010024 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010025 * bash also sources ~/.bash_logout on exit.
10026 * If called as sh, skips .bash_XXX files.
10027 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010028 }
10029
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010030 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10031 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010032 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010033 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010034 * "bash <script>" (which is never interactive (unless -i?))
10035 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010036 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010037 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010038 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010039 G.global_argc--;
10040 G.global_argv++;
10041 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010042 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010043 input = hfopen(G.global_argv[0]);
10044 if (!input) {
10045 bb_simple_perror_msg_and_die(G.global_argv[0]);
10046 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010047 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010048 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010049 parse_and_run_file(input);
10050#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010051 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010052#endif
10053 goto final_return;
10054 }
10055
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010056 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010057 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010058 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010059
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010060 /* A shell is interactive if the '-i' flag was given,
10061 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010062 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010063 * no arguments remaining or the -s flag given
10064 * standard input is a terminal
10065 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010066 * Refer to Posix.2, the description of the 'sh' utility.
10067 */
10068#if ENABLE_HUSH_JOB
10069 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010070 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10071 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10072 if (G_saved_tty_pgrp < 0)
10073 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010074
10075 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010076 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010077 if (G_interactive_fd < 0) {
10078 /* try to dup to any fd */
10079 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010080 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010081 /* give up */
10082 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010083 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010084 }
10085 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010086// TODO: track & disallow any attempts of user
10087// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010088 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010089 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010090 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010091 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010092
Mike Frysinger38478a62009-05-20 04:48:06 -040010093 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010094 /* If we were run as 'hush &', sleep until we are
10095 * in the foreground (tty pgrp == our pgrp).
10096 * If we get started under a job aware app (like bash),
10097 * make sure we are now in charge so we don't fight over
10098 * who gets the foreground */
10099 while (1) {
10100 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010101 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10102 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010103 break;
10104 /* send TTIN to ourself (should stop us) */
10105 kill(- shell_pgrp, SIGTTIN);
10106 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010107 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010108
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010109 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010110 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010111
Mike Frysinger38478a62009-05-20 04:48:06 -040010112 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010113 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010114 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010115 /* Put ourselves in our own process group
10116 * (bash, too, does this only if ctty is available) */
10117 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10118 /* Grab control of the terminal */
10119 tcsetpgrp(G_interactive_fd, getpid());
10120 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010121 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010122
10123# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10124 {
10125 const char *hp = get_local_var_value("HISTFILE");
10126 if (!hp) {
10127 hp = get_local_var_value("HOME");
10128 if (hp)
10129 hp = concat_path_file(hp, ".hush_history");
10130 } else {
10131 hp = xstrdup(hp);
10132 }
10133 if (hp) {
10134 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010135 //set_local_var(xasprintf("HISTFILE=%s", ...));
10136 }
10137# if ENABLE_FEATURE_SH_HISTFILESIZE
10138 hp = get_local_var_value("HISTFILESIZE");
10139 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10140# endif
10141 }
10142# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010143 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010144 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010145 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010146#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010147 /* No job control compiled in, only prompt/line editing */
10148 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010149 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010150 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010151 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010152 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010153 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010154 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010155 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010156 }
10157 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010158 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010159 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010160 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010161 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010162#else
10163 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010164 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010165#endif
10166 /* bash:
10167 * if interactive but not a login shell, sources ~/.bashrc
10168 * (--norc turns this off, --rcfile <file> overrides)
10169 */
10170
10171 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010172 /* note: ash and hush share this string */
10173 printf("\n\n%s %s\n"
10174 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10175 "\n",
10176 bb_banner,
10177 "hush - the humble shell"
10178 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010179 }
10180
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010181 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010182
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010183 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010184 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010185}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010186
10187
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010188/*
10189 * Built-ins
10190 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010191static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010192{
10193 return 0;
10194}
10195
Denys Vlasenko265062d2017-01-10 15:13:30 +010010196#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010197static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010198{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010199 int argc = string_array_len(argv);
10200 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010201}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010202#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010203#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010204static int FAST_FUNC builtin_test(char **argv)
10205{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010206 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010207}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010208#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010209#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010210static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010211{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010212 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010213}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010214#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010215#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010216static int FAST_FUNC builtin_printf(char **argv)
10217{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010218 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010219}
10220#endif
10221
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010222#if ENABLE_HUSH_HELP
10223static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10224{
10225 const struct built_in_command *x;
10226
10227 printf(
10228 "Built-in commands:\n"
10229 "------------------\n");
10230 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10231 if (x->b_descr)
10232 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10233 }
10234 return EXIT_SUCCESS;
10235}
10236#endif
10237
10238#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10239static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10240{
10241 show_history(G.line_input_state);
10242 return EXIT_SUCCESS;
10243}
10244#endif
10245
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010246static char **skip_dash_dash(char **argv)
10247{
10248 argv++;
10249 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10250 argv++;
10251 return argv;
10252}
10253
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010254static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010255{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010256 const char *newdir;
10257
10258 argv = skip_dash_dash(argv);
10259 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010260 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010261 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010262 * bash says "bash: cd: HOME not set" and does nothing
10263 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010264 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010265 const char *home = get_local_var_value("HOME");
10266 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010267 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010268 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010269 /* Mimic bash message exactly */
10270 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010271 return EXIT_FAILURE;
10272 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010273 /* Read current dir (get_cwd(1) is inside) and set PWD.
10274 * Note: do not enforce exporting. If PWD was unset or unexported,
10275 * set it again, but do not export. bash does the same.
10276 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010277 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010278 return EXIT_SUCCESS;
10279}
10280
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010281static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10282{
10283 puts(get_cwd(0));
10284 return EXIT_SUCCESS;
10285}
10286
10287static int FAST_FUNC builtin_eval(char **argv)
10288{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010289 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010290
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010291 if (!argv[0])
10292 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010293
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010294 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010295 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010296 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010297 /* bash:
10298 * eval "echo Hi; done" ("done" is syntax error):
10299 * "echo Hi" will not execute too.
10300 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010301 parse_and_run_string(argv[0]);
10302 } else {
10303 /* "The eval utility shall construct a command by
10304 * concatenating arguments together, separating
10305 * each with a <space> character."
10306 */
10307 char *str, *p;
10308 unsigned len = 0;
10309 char **pp = argv;
10310 do
10311 len += strlen(*pp) + 1;
10312 while (*++pp);
10313 str = p = xmalloc(len);
10314 pp = argv;
10315 for (;;) {
10316 p = stpcpy(p, *pp);
10317 pp++;
10318 if (!*pp)
10319 break;
10320 *p++ = ' ';
10321 }
10322 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010323 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010324 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010325 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010326 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010327 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010328}
10329
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010330static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010331{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010332 argv = skip_dash_dash(argv);
10333 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010334 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010335
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010336 /* Careful: we can end up here after [v]fork. Do not restore
10337 * tty pgrp then, only top-level shell process does that */
10338 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10339 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10340
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010341 /* Saved-redirect fds, script fds and G_interactive_fd are still
10342 * open here. However, they are all CLOEXEC, and execv below
10343 * closes them. Try interactive "exec ls -l /proc/self/fd",
10344 * it should show no extra open fds in the "ls" process.
10345 * If we'd try to run builtins/NOEXECs, this would need improving.
10346 */
10347 //close_saved_fds_and_FILE_fds();
10348
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010349 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010350 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010351 * and tcsetpgrp, and this is inherently racy.
10352 */
10353 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010354}
10355
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010356static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010357{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010358 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010359
10360 /* interactive bash:
10361 * # trap "echo EEE" EXIT
10362 * # exit
10363 * exit
10364 * There are stopped jobs.
10365 * (if there are _stopped_ jobs, running ones don't count)
10366 * # exit
10367 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010368 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010369 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010370 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010371 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010372
10373 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010374 argv = skip_dash_dash(argv);
10375 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010376 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010377 /* mimic bash: exit 123abc == exit 255 + error msg */
10378 xfunc_error_retval = 255;
10379 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010380 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010381}
10382
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010383#if ENABLE_HUSH_TYPE
10384/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10385static int FAST_FUNC builtin_type(char **argv)
10386{
10387 int ret = EXIT_SUCCESS;
10388
10389 while (*++argv) {
10390 const char *type;
10391 char *path = NULL;
10392
10393 if (0) {} /* make conditional compile easier below */
10394 /*else if (find_alias(*argv))
10395 type = "an alias";*/
10396#if ENABLE_HUSH_FUNCTIONS
10397 else if (find_function(*argv))
10398 type = "a function";
10399#endif
10400 else if (find_builtin(*argv))
10401 type = "a shell builtin";
10402 else if ((path = find_in_path(*argv)) != NULL)
10403 type = path;
10404 else {
10405 bb_error_msg("type: %s: not found", *argv);
10406 ret = EXIT_FAILURE;
10407 continue;
10408 }
10409
10410 printf("%s is %s\n", *argv, type);
10411 free(path);
10412 }
10413
10414 return ret;
10415}
10416#endif
10417
10418#if ENABLE_HUSH_READ
10419/* Interruptibility of read builtin in bash
10420 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10421 *
10422 * Empty trap makes read ignore corresponding signal, for any signal.
10423 *
10424 * SIGINT:
10425 * - terminates non-interactive shell;
10426 * - interrupts read in interactive shell;
10427 * if it has non-empty trap:
10428 * - executes trap and returns to command prompt in interactive shell;
10429 * - executes trap and returns to read in non-interactive shell;
10430 * SIGTERM:
10431 * - is ignored (does not interrupt) read in interactive shell;
10432 * - terminates non-interactive shell;
10433 * if it has non-empty trap:
10434 * - executes trap and returns to read;
10435 * SIGHUP:
10436 * - terminates shell (regardless of interactivity);
10437 * if it has non-empty trap:
10438 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010439 * SIGCHLD from children:
10440 * - does not interrupt read regardless of interactivity:
10441 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010442 */
10443static int FAST_FUNC builtin_read(char **argv)
10444{
10445 const char *r;
10446 char *opt_n = NULL;
10447 char *opt_p = NULL;
10448 char *opt_t = NULL;
10449 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010450 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010451 const char *ifs;
10452 int read_flags;
10453
10454 /* "!": do not abort on errors.
10455 * Option string must start with "sr" to match BUILTIN_READ_xxx
10456 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010457 read_flags = getopt32(argv,
10458#if BASH_READ_D
10459 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10460#else
10461 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10462#endif
10463 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010464 if (read_flags == (uint32_t)-1)
10465 return EXIT_FAILURE;
10466 argv += optind;
10467 ifs = get_local_var_value("IFS"); /* can be NULL */
10468
10469 again:
10470 r = shell_builtin_read(set_local_var_from_halves,
10471 argv,
10472 ifs,
10473 read_flags,
10474 opt_n,
10475 opt_p,
10476 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010477 opt_u,
10478 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010479 );
10480
10481 if ((uintptr_t)r == 1 && errno == EINTR) {
10482 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010483 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010484 goto again;
10485 }
10486
10487 if ((uintptr_t)r > 1) {
10488 bb_error_msg("%s", r);
10489 r = (char*)(uintptr_t)1;
10490 }
10491
10492 return (uintptr_t)r;
10493}
10494#endif
10495
10496#if ENABLE_HUSH_UMASK
10497static int FAST_FUNC builtin_umask(char **argv)
10498{
10499 int rc;
10500 mode_t mask;
10501
10502 rc = 1;
10503 mask = umask(0);
10504 argv = skip_dash_dash(argv);
10505 if (argv[0]) {
10506 mode_t old_mask = mask;
10507
10508 /* numeric umasks are taken as-is */
10509 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10510 if (!isdigit(argv[0][0]))
10511 mask ^= 0777;
10512 mask = bb_parse_mode(argv[0], mask);
10513 if (!isdigit(argv[0][0]))
10514 mask ^= 0777;
10515 if ((unsigned)mask > 0777) {
10516 mask = old_mask;
10517 /* bash messages:
10518 * bash: umask: 'q': invalid symbolic mode operator
10519 * bash: umask: 999: octal number out of range
10520 */
10521 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10522 rc = 0;
10523 }
10524 } else {
10525 /* Mimic bash */
10526 printf("%04o\n", (unsigned) mask);
10527 /* fall through and restore mask which we set to 0 */
10528 }
10529 umask(mask);
10530
10531 return !rc; /* rc != 0 - success */
10532}
10533#endif
10534
Denys Vlasenko41ade052017-01-08 18:56:24 +010010535#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010536static void print_escaped(const char *s)
10537{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010538 if (*s == '\'')
10539 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010540 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010541 const char *p = strchrnul(s, '\'');
10542 /* print 'xxxx', possibly just '' */
10543 printf("'%.*s'", (int)(p - s), s);
10544 if (*p == '\0')
10545 break;
10546 s = p;
10547 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010548 /* s points to '; print "'''...'''" */
10549 putchar('"');
10550 do putchar('\''); while (*++s == '\'');
10551 putchar('"');
10552 } while (*s);
10553}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010554#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010555
Denys Vlasenko1e660422017-07-17 21:10:50 +020010556#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010557static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010558{
10559 do {
10560 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010561 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010562
10563 /* So far we do not check that name is valid (TODO?) */
10564
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010565 if (*name_end == '\0') {
10566 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010567
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010568 vpp = get_ptr_to_local_var(name, name_end - name);
10569 var = vpp ? *vpp : NULL;
10570
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010571 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010572 /* export -n NAME (without =VALUE) */
10573 if (var) {
10574 var->flg_export = 0;
10575 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10576 unsetenv(name);
10577 } /* else: export -n NOT_EXISTING_VAR: no-op */
10578 continue;
10579 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010580 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010581 /* export NAME (without =VALUE) */
10582 if (var) {
10583 var->flg_export = 1;
10584 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10585 putenv(var->varstr);
10586 continue;
10587 }
10588 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010589 if (flags & SETFLAG_MAKE_RO) {
10590 /* readonly NAME (without =VALUE) */
10591 if (var) {
10592 var->flg_read_only = 1;
10593 continue;
10594 }
10595 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010596# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010597 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010598 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010599 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10600 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010601 /* "local x=abc; ...; local x" - ignore second local decl */
10602 continue;
10603 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010604 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010605# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010606 /* Exporting non-existing variable.
10607 * bash does not put it in environment,
10608 * but remembers that it is exported,
10609 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010610 * We just set it to "" and export.
10611 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010612 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010613 * bash sets the value to "".
10614 */
10615 /* Or, it's "readonly NAME" (without =VALUE).
10616 * bash remembers NAME and disallows its creation
10617 * in the future.
10618 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010619 name = xasprintf("%s=", name);
10620 } else {
10621 /* (Un)exporting/making local NAME=VALUE */
10622 name = xstrdup(name);
10623 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010624 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010625 if (set_local_var(name, flags))
10626 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010627 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010628 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010629}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010630#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010631
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010632#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010633static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010634{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010635 unsigned opt_unexport;
10636
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010637#if ENABLE_HUSH_EXPORT_N
10638 /* "!": do not abort on errors */
10639 opt_unexport = getopt32(argv, "!n");
10640 if (opt_unexport == (uint32_t)-1)
10641 return EXIT_FAILURE;
10642 argv += optind;
10643#else
10644 opt_unexport = 0;
10645 argv++;
10646#endif
10647
10648 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010649 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010650 if (e) {
10651 while (*e) {
10652#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010653 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010654#else
10655 /* ash emits: export VAR='VAL'
10656 * bash: declare -x VAR="VAL"
10657 * we follow ash example */
10658 const char *s = *e++;
10659 const char *p = strchr(s, '=');
10660
10661 if (!p) /* wtf? take next variable */
10662 continue;
10663 /* export var= */
10664 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010665 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010666 putchar('\n');
10667#endif
10668 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010669 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010670 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010671 return EXIT_SUCCESS;
10672 }
10673
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010674 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010675}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010676#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010677
Denys Vlasenko295fef82009-06-03 12:47:26 +020010678#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010679static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010680{
10681 if (G.func_nest_level == 0) {
10682 bb_error_msg("%s: not in a function", argv[0]);
10683 return EXIT_FAILURE; /* bash compat */
10684 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010685 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010686 /* Since all builtins run in a nested variable level,
10687 * need to use level - 1 here. Or else the variable will be removed at once
10688 * after builtin returns.
10689 */
10690 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010691}
10692#endif
10693
Denys Vlasenko1e660422017-07-17 21:10:50 +020010694#if ENABLE_HUSH_READONLY
10695static int FAST_FUNC builtin_readonly(char **argv)
10696{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010697 argv++;
10698 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010699 /* bash: readonly [-p]: list all readonly VARs
10700 * (-p has no effect in bash)
10701 */
10702 struct variable *e;
10703 for (e = G.top_var; e; e = e->next) {
10704 if (e->flg_read_only) {
10705//TODO: quote value: readonly VAR='VAL'
10706 printf("readonly %s\n", e->varstr);
10707 }
10708 }
10709 return EXIT_SUCCESS;
10710 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010711 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010712}
10713#endif
10714
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010715#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010716/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10717static int FAST_FUNC builtin_unset(char **argv)
10718{
10719 int ret;
10720 unsigned opts;
10721
10722 /* "!": do not abort on errors */
10723 /* "+": stop at 1st non-option */
10724 opts = getopt32(argv, "!+vf");
10725 if (opts == (unsigned)-1)
10726 return EXIT_FAILURE;
10727 if (opts == 3) {
10728 bb_error_msg("unset: -v and -f are exclusive");
10729 return EXIT_FAILURE;
10730 }
10731 argv += optind;
10732
10733 ret = EXIT_SUCCESS;
10734 while (*argv) {
10735 if (!(opts & 2)) { /* not -f */
10736 if (unset_local_var(*argv)) {
10737 /* unset <nonexistent_var> doesn't fail.
10738 * Error is when one tries to unset RO var.
10739 * Message was printed by unset_local_var. */
10740 ret = EXIT_FAILURE;
10741 }
10742 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010743# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010744 else {
10745 unset_func(*argv);
10746 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010747# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010748 argv++;
10749 }
10750 return ret;
10751}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010752#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010753
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010754#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010755/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10756 * built-in 'set' handler
10757 * SUSv3 says:
10758 * set [-abCefhmnuvx] [-o option] [argument...]
10759 * set [+abCefhmnuvx] [+o option] [argument...]
10760 * set -- [argument...]
10761 * set -o
10762 * set +o
10763 * Implementations shall support the options in both their hyphen and
10764 * plus-sign forms. These options can also be specified as options to sh.
10765 * Examples:
10766 * Write out all variables and their values: set
10767 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10768 * Turn on the -x and -v options: set -xv
10769 * Unset all positional parameters: set --
10770 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10771 * Set the positional parameters to the expansion of x, even if x expands
10772 * with a leading '-' or '+': set -- $x
10773 *
10774 * So far, we only support "set -- [argument...]" and some of the short names.
10775 */
10776static int FAST_FUNC builtin_set(char **argv)
10777{
10778 int n;
10779 char **pp, **g_argv;
10780 char *arg = *++argv;
10781
10782 if (arg == NULL) {
10783 struct variable *e;
10784 for (e = G.top_var; e; e = e->next)
10785 puts(e->varstr);
10786 return EXIT_SUCCESS;
10787 }
10788
10789 do {
10790 if (strcmp(arg, "--") == 0) {
10791 ++argv;
10792 goto set_argv;
10793 }
10794 if (arg[0] != '+' && arg[0] != '-')
10795 break;
10796 for (n = 1; arg[n]; ++n) {
10797 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10798 goto error;
10799 if (arg[n] == 'o' && argv[1])
10800 argv++;
10801 }
10802 } while ((arg = *++argv) != NULL);
10803 /* Now argv[0] is 1st argument */
10804
10805 if (arg == NULL)
10806 return EXIT_SUCCESS;
10807 set_argv:
10808
10809 /* NB: G.global_argv[0] ($0) is never freed/changed */
10810 g_argv = G.global_argv;
10811 if (G.global_args_malloced) {
10812 pp = g_argv;
10813 while (*++pp)
10814 free(*pp);
10815 g_argv[1] = NULL;
10816 } else {
10817 G.global_args_malloced = 1;
10818 pp = xzalloc(sizeof(pp[0]) * 2);
10819 pp[0] = g_argv[0]; /* retain $0 */
10820 g_argv = pp;
10821 }
10822 /* This realloc's G.global_argv */
10823 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10824
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010825 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010826
10827 return EXIT_SUCCESS;
10828
10829 /* Nothing known, so abort */
10830 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010831 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010832 return EXIT_FAILURE;
10833}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010834#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010835
10836static int FAST_FUNC builtin_shift(char **argv)
10837{
10838 int n = 1;
10839 argv = skip_dash_dash(argv);
10840 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010841 n = bb_strtou(argv[0], NULL, 10);
10842 if (errno || n < 0) {
10843 /* shared string with ash.c */
10844 bb_error_msg("Illegal number: %s", argv[0]);
10845 /*
10846 * ash aborts in this case.
10847 * bash prints error message and set $? to 1.
10848 * Interestingly, for "shift 99999" bash does not
10849 * print error message, but does set $? to 1
10850 * (and does no shifting at all).
10851 */
10852 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010853 }
10854 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010855 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010856 int m = 1;
10857 while (m <= n)
10858 free(G.global_argv[m++]);
10859 }
10860 G.global_argc -= n;
10861 memmove(&G.global_argv[1], &G.global_argv[n+1],
10862 G.global_argc * sizeof(G.global_argv[0]));
10863 return EXIT_SUCCESS;
10864 }
10865 return EXIT_FAILURE;
10866}
10867
Denys Vlasenko74d40582017-08-11 01:32:46 +020010868#if ENABLE_HUSH_GETOPTS
10869static int FAST_FUNC builtin_getopts(char **argv)
10870{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010871/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10872
Denys Vlasenko74d40582017-08-11 01:32:46 +020010873TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010874If a required argument is not found, and getopts is not silent,
10875a question mark (?) is placed in VAR, OPTARG is unset, and a
10876diagnostic message is printed. If getopts is silent, then a
10877colon (:) is placed in VAR and OPTARG is set to the option
10878character found.
10879
10880Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010881
10882"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010883*/
10884 char cbuf[2];
10885 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010886 int c, n, exitcode, my_opterr;
10887 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010888
10889 optstring = *++argv;
10890 if (!optstring || !(var = *++argv)) {
10891 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10892 return EXIT_FAILURE;
10893 }
10894
Denys Vlasenko238ff982017-08-29 13:38:30 +020010895 if (argv[1])
10896 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10897 else
10898 argv = G.global_argv;
10899 cbuf[1] = '\0';
10900
10901 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010902 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010903 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010904 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010905 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010906 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010907
10908 /* getopts stops on first non-option. Add "+" to force that */
10909 /*if (optstring[0] != '+')*/ {
10910 char *s = alloca(strlen(optstring) + 2);
10911 sprintf(s, "+%s", optstring);
10912 optstring = s;
10913 }
10914
Denys Vlasenko238ff982017-08-29 13:38:30 +020010915 /* Naively, now we should just
10916 * cp = get_local_var_value("OPTIND");
10917 * optind = cp ? atoi(cp) : 0;
10918 * optarg = NULL;
10919 * opterr = my_opterr;
10920 * c = getopt(string_array_len(argv), argv, optstring);
10921 * and be done? Not so fast...
10922 * Unlike normal getopt() usage in C programs, here
10923 * each successive call will (usually) have the same argv[] CONTENTS,
10924 * but not the ADDRESSES. Worse yet, it's possible that between
10925 * invocations of "getopts", there will be calls to shell builtins
10926 * which use getopt() internally. Example:
10927 * while getopts "abc" RES -a -bc -abc de; do
10928 * unset -ff func
10929 * done
10930 * This would not work correctly: getopt() call inside "unset"
10931 * modifies internal libc state which is tracking position in
10932 * multi-option strings ("-abc"). At best, it can skip options
10933 * or return the same option infinitely. With glibc implementation
10934 * of getopt(), it would use outright invalid pointers and return
10935 * garbage even _without_ "unset" mangling internal state.
10936 *
10937 * We resort to resetting getopt() state and calling it N times,
10938 * until we get Nth result (or failure).
10939 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10940 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010941 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010942 count = 0;
10943 n = string_array_len(argv);
10944 do {
10945 optarg = NULL;
10946 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10947 c = getopt(n, argv, optstring);
10948 if (c < 0)
10949 break;
10950 count++;
10951 } while (count <= G.getopt_count);
10952
10953 /* Set OPTIND. Prevent resetting of the magic counter! */
10954 set_local_var_from_halves("OPTIND", utoa(optind));
10955 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010956 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010957
10958 /* Set OPTARG */
10959 /* Always set or unset, never left as-is, even on exit/error:
10960 * "If no option was found, or if the option that was found
10961 * does not have an option-argument, OPTARG shall be unset."
10962 */
10963 cp = optarg;
10964 if (c == '?') {
10965 /* If ":optstring" and unknown option is seen,
10966 * it is stored to OPTARG.
10967 */
10968 if (optstring[1] == ':') {
10969 cbuf[0] = optopt;
10970 cp = cbuf;
10971 }
10972 }
10973 if (cp)
10974 set_local_var_from_halves("OPTARG", cp);
10975 else
10976 unset_local_var("OPTARG");
10977
10978 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010979 exitcode = EXIT_SUCCESS;
10980 if (c < 0) { /* -1: end of options */
10981 exitcode = EXIT_FAILURE;
10982 c = '?';
10983 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010984
Denys Vlasenko238ff982017-08-29 13:38:30 +020010985 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010986 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010987 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010988
Denys Vlasenko74d40582017-08-11 01:32:46 +020010989 return exitcode;
10990}
10991#endif
10992
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010993static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010994{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010995 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010996 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010997 save_arg_t sv;
10998 char *args_need_save;
10999#if ENABLE_HUSH_FUNCTIONS
11000 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011001#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011002
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011003 argv = skip_dash_dash(argv);
11004 filename = argv[0];
11005 if (!filename) {
11006 /* bash says: "bash: .: filename argument required" */
11007 return 2; /* bash compat */
11008 }
11009 arg_path = NULL;
11010 if (!strchr(filename, '/')) {
11011 arg_path = find_in_path(filename);
11012 if (arg_path)
11013 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011014 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011015 errno = ENOENT;
11016 bb_simple_perror_msg(filename);
11017 return EXIT_FAILURE;
11018 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011019 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011020 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011021 free(arg_path);
11022 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011023 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011024 /* POSIX: non-interactive shell should abort here,
11025 * not merely fail. So far no one complained :)
11026 */
11027 return EXIT_FAILURE;
11028 }
11029
11030#if ENABLE_HUSH_FUNCTIONS
11031 sv_flg = G_flag_return_in_progress;
11032 /* "we are inside sourced file, ok to use return" */
11033 G_flag_return_in_progress = -1;
11034#endif
11035 args_need_save = argv[1]; /* used as a boolean variable */
11036 if (args_need_save)
11037 save_and_replace_G_args(&sv, argv);
11038
11039 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11040 G.last_exitcode = 0;
11041 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011042 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011043
11044 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11045 restore_G_args(&sv, argv);
11046#if ENABLE_HUSH_FUNCTIONS
11047 G_flag_return_in_progress = sv_flg;
11048#endif
11049
11050 return G.last_exitcode;
11051}
11052
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011053#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011054static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011055{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011056 int sig;
11057 char *new_cmd;
11058
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011059 if (!G_traps)
11060 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011061
11062 argv++;
11063 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011064 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011065 /* No args: print all trapped */
11066 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011067 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011068 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011069 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011070 /* note: bash adds "SIG", but only if invoked
11071 * as "bash". If called as "sh", or if set -o posix,
11072 * then it prints short signal names.
11073 * We are printing short names: */
11074 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011075 }
11076 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011077 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011078 return EXIT_SUCCESS;
11079 }
11080
11081 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011082 /* If first arg is a number: reset all specified signals */
11083 sig = bb_strtou(*argv, NULL, 10);
11084 if (errno == 0) {
11085 int ret;
11086 process_sig_list:
11087 ret = EXIT_SUCCESS;
11088 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011089 sighandler_t handler;
11090
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011091 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011092 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011093 ret = EXIT_FAILURE;
11094 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011095 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011096 continue;
11097 }
11098
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011099 free(G_traps[sig]);
11100 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011101
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011102 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011103 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011104
11105 /* There is no signal for 0 (EXIT) */
11106 if (sig == 0)
11107 continue;
11108
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011109 if (new_cmd)
11110 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11111 else
11112 /* We are removing trap handler */
11113 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011114 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011115 }
11116 return ret;
11117 }
11118
11119 if (!argv[1]) { /* no second arg */
11120 bb_error_msg("trap: invalid arguments");
11121 return EXIT_FAILURE;
11122 }
11123
11124 /* First arg is "-": reset all specified to default */
11125 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11126 /* Everything else: set arg as signal handler
11127 * (includes "" case, which ignores signal) */
11128 if (argv[0][0] == '-') {
11129 if (argv[0][1] == '\0') { /* "-" */
11130 /* new_cmd remains NULL: "reset these sigs" */
11131 goto reset_traps;
11132 }
11133 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11134 argv++;
11135 }
11136 /* else: "-something", no special meaning */
11137 }
11138 new_cmd = *argv;
11139 reset_traps:
11140 argv++;
11141 goto process_sig_list;
11142}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011143#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011144
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011145#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011146static struct pipe *parse_jobspec(const char *str)
11147{
11148 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011149 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011150
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011151 if (sscanf(str, "%%%u", &jobnum) != 1) {
11152 if (str[0] != '%'
11153 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11154 ) {
11155 bb_error_msg("bad argument '%s'", str);
11156 return NULL;
11157 }
11158 /* It is "%%", "%+" or "%" - current job */
11159 jobnum = G.last_jobid;
11160 if (jobnum == 0) {
11161 bb_error_msg("no current job");
11162 return NULL;
11163 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011164 }
11165 for (pi = G.job_list; pi; pi = pi->next) {
11166 if (pi->jobid == jobnum) {
11167 return pi;
11168 }
11169 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011170 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011171 return NULL;
11172}
11173
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011174static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11175{
11176 struct pipe *job;
11177 const char *status_string;
11178
11179 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11180 for (job = G.job_list; job; job = job->next) {
11181 if (job->alive_cmds == job->stopped_cmds)
11182 status_string = "Stopped";
11183 else
11184 status_string = "Running";
11185
11186 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11187 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011188
11189 clean_up_last_dead_job();
11190
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011191 return EXIT_SUCCESS;
11192}
11193
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011194/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011195static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011196{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011197 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011198 struct pipe *pi;
11199
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011200 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011201 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011202
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011203 /* If they gave us no args, assume they want the last backgrounded task */
11204 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011205 for (pi = G.job_list; pi; pi = pi->next) {
11206 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011207 goto found;
11208 }
11209 }
11210 bb_error_msg("%s: no current job", argv[0]);
11211 return EXIT_FAILURE;
11212 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011213
11214 pi = parse_jobspec(argv[1]);
11215 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011216 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011217 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011218 /* TODO: bash prints a string representation
11219 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011220 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011221 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011222 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011223 }
11224
11225 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011226 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11227 for (i = 0; i < pi->num_cmds; i++) {
11228 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011229 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011230 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011231
11232 i = kill(- pi->pgrp, SIGCONT);
11233 if (i < 0) {
11234 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011235 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011236 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011237 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011238 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011239 }
11240
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011241 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011242 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011243 return checkjobs_and_fg_shell(pi);
11244 }
11245 return EXIT_SUCCESS;
11246}
11247#endif
11248
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011249#if ENABLE_HUSH_KILL
11250static int FAST_FUNC builtin_kill(char **argv)
11251{
11252 int ret = 0;
11253
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011254# if ENABLE_HUSH_JOB
11255 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11256 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011257
11258 do {
11259 struct pipe *pi;
11260 char *dst;
11261 int j, n;
11262
11263 if (argv[i][0] != '%')
11264 continue;
11265 /*
11266 * "kill %N" - job kill
11267 * Converting to pgrp / pid kill
11268 */
11269 pi = parse_jobspec(argv[i]);
11270 if (!pi) {
11271 /* Eat bad jobspec */
11272 j = i;
11273 do {
11274 j++;
11275 argv[j - 1] = argv[j];
11276 } while (argv[j]);
11277 ret = 1;
11278 i--;
11279 continue;
11280 }
11281 /*
11282 * In jobs started under job control, we signal
11283 * entire process group by kill -PGRP_ID.
11284 * This happens, f.e., in interactive shell.
11285 *
11286 * Otherwise, we signal each child via
11287 * kill PID1 PID2 PID3.
11288 * Testcases:
11289 * sh -c 'sleep 1|sleep 1 & kill %1'
11290 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11291 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11292 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011293 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011294 dst = alloca(n * sizeof(int)*4);
11295 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011296 if (G_interactive_fd)
11297 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011298 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011299 struct command *cmd = &pi->cmds[j];
11300 /* Skip exited members of the job */
11301 if (cmd->pid == 0)
11302 continue;
11303 /*
11304 * kill_main has matching code to expect
11305 * leading space. Needed to not confuse
11306 * negative pids with "kill -SIGNAL_NO" syntax
11307 */
11308 dst += sprintf(dst, " %u", (int)cmd->pid);
11309 }
11310 *dst = '\0';
11311 } while (argv[++i]);
11312 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011313# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011314
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011315 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011316 ret = run_applet_main(argv, kill_main);
11317 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011318 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011319 return ret;
11320}
11321#endif
11322
11323#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011324/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011325#if !ENABLE_HUSH_JOB
11326# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11327#endif
11328static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011329{
11330 int ret = 0;
11331 for (;;) {
11332 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011333 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011334
Denys Vlasenko830ea352016-11-08 04:59:11 +010011335 if (!sigisemptyset(&G.pending_set))
11336 goto check_sig;
11337
Denys Vlasenko7e675362016-10-28 21:57:31 +020011338 /* waitpid is not interruptible by SA_RESTARTed
11339 * signals which we use. Thus, this ugly dance:
11340 */
11341
11342 /* Make sure possible SIGCHLD is stored in kernel's
11343 * pending signal mask before we call waitpid.
11344 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011345 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011346 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011347 sigfillset(&oldset); /* block all signals, remember old set */
11348 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011349
11350 if (!sigisemptyset(&G.pending_set)) {
11351 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011352 goto restore;
11353 }
11354
11355 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011356/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011357 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011358 debug_printf_exec("checkjobs:%d\n", ret);
11359#if ENABLE_HUSH_JOB
11360 if (waitfor_pipe) {
11361 int rcode = job_exited_or_stopped(waitfor_pipe);
11362 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11363 if (rcode >= 0) {
11364 ret = rcode;
11365 sigprocmask(SIG_SETMASK, &oldset, NULL);
11366 break;
11367 }
11368 }
11369#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011370 /* if ECHILD, there are no children (ret is -1 or 0) */
11371 /* if ret == 0, no children changed state */
11372 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011373 if (errno == ECHILD || ret) {
11374 ret--;
11375 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011376 ret = 0;
11377 sigprocmask(SIG_SETMASK, &oldset, NULL);
11378 break;
11379 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011380 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011381 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11382 /* Note: sigsuspend invokes signal handler */
11383 sigsuspend(&oldset);
11384 restore:
11385 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011386 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011387 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011388 sig = check_and_run_traps();
11389 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011390 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011391 ret = 128 + sig;
11392 break;
11393 }
11394 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11395 }
11396 return ret;
11397}
11398
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011399static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011400{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011401 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011402 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011403
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011404 argv = skip_dash_dash(argv);
11405 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011406 /* Don't care about wait results */
11407 /* Note 1: must wait until there are no more children */
11408 /* Note 2: must be interruptible */
11409 /* Examples:
11410 * $ sleep 3 & sleep 6 & wait
11411 * [1] 30934 sleep 3
11412 * [2] 30935 sleep 6
11413 * [1] Done sleep 3
11414 * [2] Done sleep 6
11415 * $ sleep 3 & sleep 6 & wait
11416 * [1] 30936 sleep 3
11417 * [2] 30937 sleep 6
11418 * [1] Done sleep 3
11419 * ^C <-- after ~4 sec from keyboard
11420 * $
11421 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011422 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011423 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011424
Denys Vlasenko7e675362016-10-28 21:57:31 +020011425 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011426 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011427 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011428#if ENABLE_HUSH_JOB
11429 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011430 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011431 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011432 wait_pipe = parse_jobspec(*argv);
11433 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011434 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011435 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011436 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011437 } else {
11438 /* waiting on "last dead job" removes it */
11439 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011440 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011441 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011442 /* else: parse_jobspec() already emitted error msg */
11443 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011444 }
11445#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011446 /* mimic bash message */
11447 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011448 ret = EXIT_FAILURE;
11449 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011450 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011451
Denys Vlasenko7e675362016-10-28 21:57:31 +020011452 /* Do we have such child? */
11453 ret = waitpid(pid, &status, WNOHANG);
11454 if (ret < 0) {
11455 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011456 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011457 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011458 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011459 /* "wait $!" but last bg task has already exited. Try:
11460 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11461 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011462 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011463 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011464 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011465 } else {
11466 /* Example: "wait 1". mimic bash message */
11467 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011468 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011469 } else {
11470 /* ??? */
11471 bb_perror_msg("wait %s", *argv);
11472 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011473 continue; /* bash checks all argv[] */
11474 }
11475 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011476 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011477 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011478 } else {
11479 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011480 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011481 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011482 if (WIFSIGNALED(status))
11483 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011484 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011485 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011486
11487 return ret;
11488}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011489#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011490
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011491#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11492static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11493{
11494 if (argv[1]) {
11495 def = bb_strtou(argv[1], NULL, 10);
11496 if (errno || def < def_min || argv[2]) {
11497 bb_error_msg("%s: bad arguments", argv[0]);
11498 def = UINT_MAX;
11499 }
11500 }
11501 return def;
11502}
11503#endif
11504
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011505#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011506static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011507{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011508 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011509 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011510 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011511 /* if we came from builtin_continue(), need to undo "= 1" */
11512 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011513 return EXIT_SUCCESS; /* bash compat */
11514 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011515 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011516
11517 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11518 if (depth == UINT_MAX)
11519 G.flag_break_continue = BC_BREAK;
11520 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011521 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011522
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011523 return EXIT_SUCCESS;
11524}
11525
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011526static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011527{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011528 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11529 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011530}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011531#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011532
11533#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011534static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011535{
11536 int rc;
11537
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011538 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011539 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11540 return EXIT_FAILURE; /* bash compat */
11541 }
11542
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011543 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011544
11545 /* bash:
11546 * out of range: wraps around at 256, does not error out
11547 * non-numeric param:
11548 * f() { false; return qwe; }; f; echo $?
11549 * bash: return: qwe: numeric argument required <== we do this
11550 * 255 <== we also do this
11551 */
11552 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11553 return rc;
11554}
11555#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011556
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011557#if ENABLE_HUSH_TIMES
11558static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11559{
11560 static const uint8_t times_tbl[] ALIGN1 = {
11561 ' ', offsetof(struct tms, tms_utime),
11562 '\n', offsetof(struct tms, tms_stime),
11563 ' ', offsetof(struct tms, tms_cutime),
11564 '\n', offsetof(struct tms, tms_cstime),
11565 0
11566 };
11567 const uint8_t *p;
11568 unsigned clk_tck;
11569 struct tms buf;
11570
11571 clk_tck = bb_clk_tck();
11572
11573 times(&buf);
11574 p = times_tbl;
11575 do {
11576 unsigned sec, frac;
11577 unsigned long t;
11578 t = *(clock_t *)(((char *) &buf) + p[1]);
11579 sec = t / clk_tck;
11580 frac = t % clk_tck;
11581 printf("%um%u.%03us%c",
11582 sec / 60, sec % 60,
11583 (frac * 1000) / clk_tck,
11584 p[0]);
11585 p += 2;
11586 } while (*p);
11587
11588 return EXIT_SUCCESS;
11589}
11590#endif
11591
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011592#if ENABLE_HUSH_MEMLEAK
11593static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11594{
11595 void *p;
11596 unsigned long l;
11597
11598# ifdef M_TRIM_THRESHOLD
11599 /* Optional. Reduces probability of false positives */
11600 malloc_trim(0);
11601# endif
11602 /* Crude attempt to find where "free memory" starts,
11603 * sans fragmentation. */
11604 p = malloc(240);
11605 l = (unsigned long)p;
11606 free(p);
11607 p = malloc(3400);
11608 if (l < (unsigned long)p) l = (unsigned long)p;
11609 free(p);
11610
11611
11612# if 0 /* debug */
11613 {
11614 struct mallinfo mi = mallinfo();
11615 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11616 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11617 }
11618# endif
11619
11620 if (!G.memleak_value)
11621 G.memleak_value = l;
11622
11623 l -= G.memleak_value;
11624 if ((long)l < 0)
11625 l = 0;
11626 l /= 1024;
11627 if (l > 127)
11628 l = 127;
11629
11630 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11631 return l;
11632}
11633#endif