blob: 2da288c1554eba4528dc4ff19a6ff7891285495a [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
360#ifndef F_DUPFD_CLOEXEC
361# define F_DUPFD_CLOEXEC F_DUPFD
362#endif
363#ifndef PIPE_BUF
364# define PIPE_BUF 4096 /* amount of buffering in a pipe */
365#endif
366
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000367
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100368/* So far, all bash compat is controlled by one config option */
369/* Separate defines document which part of code implements what */
370#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100372#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200374#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200375#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376
377
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200378/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000379#define LEAK_HUNTING 0
380#define BUILD_AS_NOMMU 0
381/* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
384 */
385#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200386/* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
391 */
392#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200393/* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
395 */
396#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000397
398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000399#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400# undef BB_MMU
401# undef USE_FOR_NOMMU
402# undef USE_FOR_MMU
403# define BB_MMU 0
404# define USE_FOR_NOMMU(...) __VA_ARGS__
405# define USE_FOR_MMU(...)
406#endif
407
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200408#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100409#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000410/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef CONFIG_FEATURE_SH_STANDALONE
412# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000413# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100414# undef IF_NOT_FEATURE_SH_STANDALONE
415# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# define IF_FEATURE_SH_STANDALONE(...)
417# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000418#endif
419
Denis Vlasenko05743d72008-02-10 12:10:08 +0000420#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# undef ENABLE_FEATURE_EDITING
422# define ENABLE_FEATURE_EDITING 0
423# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200425# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427#endif
428
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000429/* Do we support ANY keywords? */
430#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000431# define HAS_KEYWORDS 1
432# define IF_HAS_KEYWORDS(...) __VA_ARGS__
433# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000434#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000435# define HAS_KEYWORDS 0
436# define IF_HAS_KEYWORDS(...)
437# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000439
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000440/* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_parse(...) do {} while (0)
445#define debug_print_tree(a, b) do {} while (0)
446#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000447#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000448#define debug_printf_jobs(...) do {} while (0)
449#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200450#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000451#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200452#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000453#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000454#define debug_printf_subst(...) do {} while (0)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200455#define debug_printf_prompt(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000456#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000457
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000458#define ERR_PTR ((void*)(long)1)
459
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100460#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000461
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200462#define _SPECIAL_VARS_STR "_*@$!?#"
463#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
464#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100465#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200466/* Support / and // replace ops */
467/* Note that // is stored as \ in "encoded" string representation */
468# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
469# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
470# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
471#else
472# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
473# define VAR_SUBST_OPS "%#:-=+?"
474# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
475#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200476
Denys Vlasenko932b9972018-01-11 12:39:48 +0100477#define SPECIAL_VAR_SYMBOL_STR "\3"
478#define SPECIAL_VAR_SYMBOL 3
479/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
480#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000481
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200482struct variable;
483
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000484static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
485
486/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000487 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488 */
489#if !BB_MMU
490typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200491 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000493 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494} nommu_save_t;
495#endif
496
Denys Vlasenko9b782552010-09-08 13:33:26 +0200497enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000498 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000499#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000500 RES_IF ,
501 RES_THEN ,
502 RES_ELIF ,
503 RES_ELSE ,
504 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000505#endif
506#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_FOR ,
508 RES_WHILE ,
509 RES_UNTIL ,
510 RES_DO ,
511 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000512#endif
513#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516#if ENABLE_HUSH_CASE
517 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200518 /* three pseudo-keywords support contrived "case" syntax: */
519 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
520 RES_MATCH , /* "word)" */
521 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000522 RES_ESAC ,
523#endif
524 RES_XXXX ,
525 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200526};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000527
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000528typedef struct o_string {
529 char *data;
530 int length; /* position where data is appended */
531 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200532 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000533 /* At least some part of the string was inside '' or "",
534 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200535 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000536 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200537 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538} o_string;
539enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200540 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
541 EXP_FLAG_GLOB = 0x2,
542 /* Protect newly added chars against globbing
543 * by prepending \ to *, ?, [, \ */
544 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
545};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000546/* Used for initialization: o_string foo = NULL_O_STRING; */
547#define NULL_O_STRING { NULL }
548
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200549#ifndef debug_printf_parse
550static const char *const assignment_flag[] = {
551 "MAYBE_ASSIGNMENT",
552 "DEFINITELY_ASSIGNMENT",
553 "NOT_ASSIGNMENT",
554 "WORD_IS_KEYWORD",
555};
556#endif
557
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000558typedef struct in_str {
559 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200560 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200561 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000564
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200565/* The descrip member of this structure is only used to make
566 * debugging output pretty */
567static const struct {
568 int mode;
569 signed char default_fd;
570 char descrip[3];
571} redir_table[] = {
572 { O_RDONLY, 0, "<" },
573 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
574 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
575 { O_CREAT|O_RDWR, 1, "<>" },
576 { O_RDONLY, 0, "<<" },
577/* Should not be needed. Bogus default_fd helps in debugging */
578/* { O_RDONLY, 77, "<<" }, */
579};
580
Eric Andersen25f27032001-04-26 23:22:31 +0000581struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000582 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000583 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000584 int rd_fd; /* fd to redirect */
585 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
586 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000587 smallint rd_type; /* (enum redir_type) */
588 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000589 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200590 * bit 0: do we need to trim leading tabs?
591 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000592 */
Eric Andersen25f27032001-04-26 23:22:31 +0000593};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000594typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200595 REDIRECT_INPUT = 0,
596 REDIRECT_OVERWRITE = 1,
597 REDIRECT_APPEND = 2,
598 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000599 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200600 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000601
602 REDIRFD_CLOSE = -3,
603 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000604 REDIRFD_TO_FILE = -1,
605 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000606
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000607 HEREDOC_SKIPTABS = 1,
608 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000609} redir_type;
610
Eric Andersen25f27032001-04-26 23:22:31 +0000611
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000612struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000613 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200614 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100615#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100616 unsigned lineno;
617#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200618 smallint cmd_type; /* CMD_xxx */
619#define CMD_NORMAL 0
620#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200621#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
622/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
623 * "export v=t*"
624 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200625# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000626#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200627#if ENABLE_HUSH_FUNCTIONS
628# define CMD_FUNCDEF 3
629#endif
630
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100631 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200632 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
633 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000634#if !BB_MMU
635 char *group_as_string;
636#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000637#if ENABLE_HUSH_FUNCTIONS
638 struct function *child_func;
639/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200640 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000641 * When we execute "f1() {a;}" cmd, we create new function and clear
642 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200643 * When we execute "f1() {b;}", we notice that f1 exists,
644 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000645 * we put those fields back into cmd->xxx
646 * (struct function has ->parent_cmd ptr to facilitate that).
647 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
648 * Without this trick, loop would execute a;b;b;b;...
649 * instead of correct sequence a;b;a;b;...
650 * When command is freed, it severs the link
651 * (sets ->child_func->parent_cmd to NULL).
652 */
653#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000654 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000655/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
656 * and on execution these are substituted with their values.
657 * Substitution can make _several_ words out of one argv[n]!
658 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000659 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000660 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 struct redir_struct *redirects; /* I/O redirections */
662};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000663/* Is there anything in this command at all? */
664#define IS_NULL_CMD(cmd) \
665 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
666
Eric Andersen25f27032001-04-26 23:22:31 +0000667struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000668 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000669 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000670 int alive_cmds; /* number of commands running (not exited) */
671 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000672#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100673 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000674 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000675 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000676#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000677 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000678 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000679 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
680 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000681};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000682typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100683 PIPE_SEQ = 0,
684 PIPE_AND = 1,
685 PIPE_OR = 2,
686 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000687} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000688/* Is there anything in this pipe at all? */
689#define IS_NULL_PIPE(pi) \
690 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000691
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000692/* This holds pointers to the various results of parsing */
693struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000694 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000695 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000696 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000697 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000698 /* last command in pipe (being constructed right now) */
699 struct command *command;
700 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000701 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200702 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000703#if !BB_MMU
704 o_string as_string;
705#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200706 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000707#if HAS_KEYWORDS
708 smallint ctx_res_w;
709 smallint ctx_inverted; /* "! cmd | cmd" */
710#if ENABLE_HUSH_CASE
711 smallint ctx_dsemicolon; /* ";;" seen */
712#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000713 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
714 int old_flag;
715 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000716 * example: "if pipe1; pipe2; then pipe3; fi"
717 * when we see "if" or "then", we malloc and copy current context,
718 * and make ->stack point to it. then we parse pipeN.
719 * when closing "then" / fi" / whatever is found,
720 * we move list_head into ->stack->command->group,
721 * copy ->stack into current context, and delete ->stack.
722 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000723 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000724 struct parse_context *stack;
725#endif
726};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200727enum {
728 MAYBE_ASSIGNMENT = 0,
729 DEFINITELY_ASSIGNMENT = 1,
730 NOT_ASSIGNMENT = 2,
731 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
732 WORD_IS_KEYWORD = 3,
733};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000734
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000735/* On program start, environ points to initial environment.
736 * putenv adds new pointers into it, unsetenv removes them.
737 * Neither of these (de)allocates the strings.
738 * setenv allocates new strings in malloc space and does putenv,
739 * and thus setenv is unusable (leaky) for shell's purposes */
740#define setenv(...) setenv_is_leaky_dont_use()
741struct variable {
742 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000743 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000744 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200745 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000746 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000747 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000748};
749
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000750enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000751 BC_BREAK = 1,
752 BC_CONTINUE = 2,
753};
754
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000755#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000756struct function {
757 struct function *next;
758 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000759 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000760 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200761# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000762 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200763# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000764};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000765#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000766
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000767
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100768/* set -/+o OPT support. (TODO: make it optional)
769 * bash supports the following opts:
770 * allexport off
771 * braceexpand on
772 * emacs on
773 * errexit off
774 * errtrace off
775 * functrace off
776 * hashall on
777 * histexpand off
778 * history on
779 * ignoreeof off
780 * interactive-comments on
781 * keyword off
782 * monitor on
783 * noclobber off
784 * noexec off
785 * noglob off
786 * nolog off
787 * notify off
788 * nounset off
789 * onecmd off
790 * physical off
791 * pipefail off
792 * posix off
793 * privileged off
794 * verbose off
795 * vi off
796 * xtrace off
797 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800798static const char o_opt_strings[] ALIGN1 =
799 "pipefail\0"
800 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200801 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800802#if ENABLE_HUSH_MODE_X
803 "xtrace\0"
804#endif
805 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100806enum {
807 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800808 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200809 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800810#if ENABLE_HUSH_MODE_X
811 OPT_O_XTRACE,
812#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100813 NUM_OPT_O
814};
815
816
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200817struct FILE_list {
818 struct FILE_list *next;
819 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200820 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200821};
822
823
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000824/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825/* Sorted roughly by size (smaller offsets == smaller code) */
826struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000827 /* interactive_fd != 0 means we are an interactive shell.
828 * If we are, then saved_tty_pgrp can also be != 0, meaning
829 * that controlling tty is available. With saved_tty_pgrp == 0,
830 * job control still works, but terminal signals
831 * (^C, ^Z, ^Y, ^\) won't work at all, and background
832 * process groups can only be created with "cmd &".
833 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
834 * to give tty to the foreground process group,
835 * and will take it back when the group is stopped (^Z)
836 * or killed (^C).
837 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838#if ENABLE_HUSH_INTERACTIVE
839 /* 'interactive_fd' is a fd# open to ctty, if we have one
840 * _AND_ if we decided to act interactively */
841 int interactive_fd;
842 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200843 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000844# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000845#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000846# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000847#endif
848#if ENABLE_FEATURE_EDITING
849 line_input_t *line_input_state;
850#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000851 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200852 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000853 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200854#if ENABLE_HUSH_RANDOM_SUPPORT
855 random_t random_gen;
856#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000857#if ENABLE_HUSH_JOB
858 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100859 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000860 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000861 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400862# define G_saved_tty_pgrp (G.saved_tty_pgrp)
863#else
864# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000865#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200866 /* How deeply are we in context where "set -e" is ignored */
867 int errexit_depth;
868 /* "set -e" rules (do we follow them correctly?):
869 * Exit if pipe, list, or compound command exits with a non-zero status.
870 * Shell does not exit if failed command is part of condition in
871 * if/while, part of && or || list except the last command, any command
872 * in a pipe but the last, or if the command's return value is being
873 * inverted with !. If a compound command other than a subshell returns a
874 * non-zero status because a command failed while -e was being ignored, the
875 * shell does not exit. A trap on ERR, if set, is executed before the shell
876 * exits [ERR is a bashism].
877 *
878 * If a compound command or function executes in a context where -e is
879 * ignored, none of the commands executed within are affected by the -e
880 * setting. If a compound command or function sets -e while executing in a
881 * context where -e is ignored, that setting does not have any effect until
882 * the compound command or the command containing the function call completes.
883 */
884
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100885 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100886#if ENABLE_HUSH_MODE_X
887# define G_x_mode (G.o_opt[OPT_O_XTRACE])
888#else
889# define G_x_mode 0
890#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200891#if ENABLE_HUSH_INTERACTIVE
892 smallint promptmode; /* 0: PS1, 1: PS2 */
893#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000894 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000895#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000896 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000897#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000898#if ENABLE_HUSH_FUNCTIONS
899 /* 0: outside of a function (or sourced file)
900 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000901 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000902 */
903 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200904# define G_flag_return_in_progress (G.flag_return_in_progress)
905#else
906# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000907#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000908 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200909 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000910 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200911 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200912 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100913#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000914 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000915 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100916# define G_global_args_malloced (G.global_args_malloced)
917#else
918# define G_global_args_malloced 0
919#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000920 /* how many non-NULL argv's we have. NB: $# + 1 */
921 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000922 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000923#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000924 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000925#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000926#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000927 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000928 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000929#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200930#if ENABLE_HUSH_GETOPTS
931 unsigned getopt_count;
932#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000933 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200934 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000935 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200936 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200937 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200938 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200939 unsigned var_nest_level;
940#if ENABLE_HUSH_FUNCTIONS
941# if ENABLE_HUSH_LOCAL
942 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200943# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200944 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000945#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000946 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200947#if ENABLE_HUSH_FAST
948 unsigned count_SIGCHLD;
949 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200950 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200951#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100952#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100953 unsigned lineno;
954 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100955#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200956 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200957 /* Which signals have non-DFL handler (even with no traps set)?
958 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200959 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200960 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200961 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200962 * Other than these two times, never modified.
963 */
964 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200965#if ENABLE_HUSH_JOB
966 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100967# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200968#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200969# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200970#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100971#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000972 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100973# define G_traps G.traps
974#else
975# define G_traps ((char**)NULL)
976#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200977 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100978#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000979 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100980#endif
981#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000982 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000983#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200984 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200985#if ENABLE_FEATURE_EDITING
986 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
987#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000988};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000989#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000990/* Not #defining name to G.name - this quickly gets unwieldy
991 * (too many defines). Also, I actually prefer to see when a variable
992 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000993#define INIT_G() do { \
994 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200995 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
996 sigfillset(&G.sa.sa_mask); \
997 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000998} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000999
1000
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001001/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001002static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001003#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001004static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001005#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001006static int builtin_eval(char **argv) FAST_FUNC;
1007static int builtin_exec(char **argv) FAST_FUNC;
1008static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001009#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001010static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001011#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001012#if ENABLE_HUSH_READONLY
1013static int builtin_readonly(char **argv) FAST_FUNC;
1014#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001015#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001016static int builtin_fg_bg(char **argv) FAST_FUNC;
1017static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001018#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001019#if ENABLE_HUSH_GETOPTS
1020static int builtin_getopts(char **argv) FAST_FUNC;
1021#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001022#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001023static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001024#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001025#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001026static int builtin_history(char **argv) FAST_FUNC;
1027#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001028#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001029static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001030#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001031#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001032static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001033#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001034#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001035static int builtin_printf(char **argv) FAST_FUNC;
1036#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001038#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001039static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001040#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001041#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001043#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_shift(char **argv) FAST_FUNC;
1045static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001046#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001048#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001049#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001051#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001052#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001054#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001055#if ENABLE_HUSH_TIMES
1056static int builtin_times(char **argv) FAST_FUNC;
1057#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001059#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001061#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001062#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001063static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001064#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001065#if ENABLE_HUSH_KILL
1066static int builtin_kill(char **argv) FAST_FUNC;
1067#endif
1068#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001069static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001070#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001071#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001072static int builtin_break(char **argv) FAST_FUNC;
1073static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001074#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001075#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001076static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001077#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001078
1079/* Table of built-in functions. They can be forked or not, depending on
1080 * context: within pipes, they fork. As simple commands, they do not.
1081 * When used in non-forking context, they can change global variables
1082 * in the parent shell process. If forked, of course they cannot.
1083 * For example, 'unset foo | whatever' will parse and run, but foo will
1084 * still be set at the end. */
1085struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001086 const char *b_cmd;
1087 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001088#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001089 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001090# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001091#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001092# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001093#endif
1094};
1095
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001096static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001097 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001098 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001100 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#endif
1102#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001103 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001105 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001107 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001108#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001109 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1110 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001111 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001112#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001113 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001114#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001115#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001116 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001117#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001118#if ENABLE_HUSH_GETOPTS
1119 BLTIN("getopts" , builtin_getopts , NULL),
1120#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001122 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001124#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001125 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001126#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001127#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001129#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001130#if ENABLE_HUSH_KILL
1131 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1132#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001133#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001134 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001135#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001136#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001138#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001139#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001140 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001141#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001142#if ENABLE_HUSH_READONLY
1143 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1144#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001145#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001146 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001147#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001148#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001149 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001150#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001151 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001152#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001153 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001154#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001155#if ENABLE_HUSH_TIMES
1156 BLTIN("times" , builtin_times , NULL),
1157#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001158#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001159 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001160#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001161 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001162#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001163 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001164#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001165#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001166 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001167#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001168#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001169 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001170#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001171#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001172 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001173#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001174#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001175 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001176#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001177};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001178/* These builtins won't be used if we are on NOMMU and need to re-exec
1179 * (it's cheaper to run an external program in this case):
1180 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001182#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001183 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001184#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001185#if BASH_TEST2
1186 BLTIN("[[" , builtin_test , NULL),
1187#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001188#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001189 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001190#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001191#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001192 BLTIN("printf" , builtin_printf , NULL),
1193#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001194 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001195#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001196 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001197#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001198};
1199
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001200
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001201/* Debug printouts.
1202 */
1203#if HUSH_DEBUG
1204/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001205# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001206# define debug_enter() (G.debug_indent++)
1207# define debug_leave() (G.debug_indent--)
1208#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001209# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001210# define debug_enter() ((void)0)
1211# define debug_leave() ((void)0)
1212#endif
1213
1214#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001215# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001216#endif
1217
1218#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001219# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001220#endif
1221
1222#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001223#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001224#endif
1225
1226#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001227# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001228#endif
1229
1230#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001231# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001232# define DEBUG_JOBS 1
1233#else
1234# define DEBUG_JOBS 0
1235#endif
1236
1237#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001238# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001239# define DEBUG_EXPAND 1
1240#else
1241# define DEBUG_EXPAND 0
1242#endif
1243
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001244#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001245# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001246#endif
1247
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001249# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001250# define DEBUG_GLOB 1
1251#else
1252# define DEBUG_GLOB 0
1253#endif
1254
Denys Vlasenko2db74612017-07-07 22:07:28 +02001255#ifndef debug_printf_redir
1256# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1257#endif
1258
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001260# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001261#endif
1262
1263#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001265#endif
1266
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001267#ifndef debug_printf_prompt
1268# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1269#endif
1270
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001271#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001272# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001273# define DEBUG_CLEAN 1
1274#else
1275# define DEBUG_CLEAN 0
1276#endif
1277
1278#if DEBUG_EXPAND
1279static void debug_print_strings(const char *prefix, char **vv)
1280{
1281 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001282 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001283 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001284 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001285}
1286#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001287# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001288#endif
1289
1290
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001291/* Leak hunting. Use hush_leaktool.sh for post-processing.
1292 */
1293#if LEAK_HUNTING
1294static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001295{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001296 void *ptr = xmalloc((size + 0xff) & ~0xff);
1297 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1298 return ptr;
1299}
1300static void *xxrealloc(int lineno, void *ptr, size_t size)
1301{
1302 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1303 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1304 return ptr;
1305}
1306static char *xxstrdup(int lineno, const char *str)
1307{
1308 char *ptr = xstrdup(str);
1309 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1310 return ptr;
1311}
1312static void xxfree(void *ptr)
1313{
1314 fdprintf(2, "free %p\n", ptr);
1315 free(ptr);
1316}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001317# define xmalloc(s) xxmalloc(__LINE__, s)
1318# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1319# define xstrdup(s) xxstrdup(__LINE__, s)
1320# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001321#endif
1322
1323
1324/* Syntax and runtime errors. They always abort scripts.
1325 * In interactive use they usually discard unparsed and/or unexecuted commands
1326 * and return to the prompt.
1327 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1328 */
1329#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001330# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001331# define syntax_error(lineno, msg) syntax_error(msg)
1332# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1333# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1334# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1335# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001336#endif
1337
Denys Vlasenko39701202017-08-02 19:44:05 +02001338static void die_if_script(void)
1339{
1340 if (!G_interactive_fd) {
1341 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1342 xfunc_error_retval = G.last_exitcode;
1343 xfunc_die();
1344 }
1345}
1346
1347static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001348{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001349 va_list p;
1350
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001351#if HUSH_DEBUG >= 2
1352 bb_error_msg("hush.c:%u", lineno);
1353#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001354 va_start(p, fmt);
1355 bb_verror_msg(fmt, p, NULL);
1356 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001357 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001358}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001359
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001360static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001361{
1362 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001363 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001364 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001365 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001366 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001367}
1368
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001369static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001370{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001371 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001372 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373}
1374
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001375static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001376{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001377 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001378//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1379// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001380}
1381
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001382static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001383{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001384 char msg[2] = { ch, '\0' };
1385 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386}
1387
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001388static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001389{
1390 char msg[2];
1391 msg[0] = ch;
1392 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001393#if HUSH_DEBUG >= 2
1394 bb_error_msg("hush.c:%u", lineno);
1395#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001396 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001397 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001398}
1399
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001401# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402# undef syntax_error
1403# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001404# undef syntax_error_unterm_ch
1405# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001406# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001407#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001408# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001409# define syntax_error(msg) syntax_error(__LINE__, msg)
1410# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1411# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1412# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1413# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001414#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001415
Denis Vlasenko552433b2009-04-04 19:29:21 +00001416
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001417#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001418static void cmdedit_update_prompt(void);
1419#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001420# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001421#endif
1422
1423
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001424/* Utility functions
1425 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001426/* Replace each \x with x in place, return ptr past NUL. */
1427static char *unbackslash(char *src)
1428{
Denys Vlasenko71885402009-09-24 01:44:13 +02001429 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001430 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001431 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001432 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001433 if (*src != '\0') {
1434 /* \x -> x */
1435 *dst++ = *src++;
1436 continue;
1437 }
1438 /* else: "\<nul>". Do not delete this backslash.
1439 * Testcase: eval 'echo ok\'
1440 */
1441 *dst++ = '\\';
1442 /* fallthrough */
1443 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001444 if ((*dst++ = *src++) == '\0')
1445 break;
1446 }
1447 return dst;
1448}
1449
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001450static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001451{
1452 int i;
1453 unsigned count1;
1454 unsigned count2;
1455 char **v;
1456
1457 v = strings;
1458 count1 = 0;
1459 if (v) {
1460 while (*v) {
1461 count1++;
1462 v++;
1463 }
1464 }
1465 count2 = 0;
1466 v = add;
1467 while (*v) {
1468 count2++;
1469 v++;
1470 }
1471 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1472 v[count1 + count2] = NULL;
1473 i = count2;
1474 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001475 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001476 return v;
1477}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001478#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001479static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1480{
1481 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1482 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1483 return ptr;
1484}
1485#define add_strings_to_strings(strings, add, need_to_dup) \
1486 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1487#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001488
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001489/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001490static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001491{
1492 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001493 v[0] = add;
1494 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001495 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001496}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001497#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001498static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1499{
1500 char **ptr = add_string_to_strings(strings, add);
1501 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1502 return ptr;
1503}
1504#define add_string_to_strings(strings, add) \
1505 xx_add_string_to_strings(__LINE__, strings, add)
1506#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001508static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001509{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001510 char **v;
1511
1512 if (!strings)
1513 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001514 v = strings;
1515 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001516 free(*v);
1517 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001518 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001519 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001520}
1521
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001522static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001523{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001524 int newfd;
1525 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001526 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1527 if (newfd >= 0) {
1528 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1529 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1530 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001531 if (errno == EBUSY)
1532 goto repeat;
1533 if (errno == EINTR)
1534 goto repeat;
1535 }
1536 return newfd;
1537}
1538
Denys Vlasenko657e9002017-07-30 23:34:04 +02001539static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001540{
1541 int newfd;
1542 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001543 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001544 if (newfd < 0) {
1545 if (errno == EBUSY)
1546 goto repeat;
1547 if (errno == EINTR)
1548 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001549 /* fd was not open? */
1550 if (errno == EBADF)
1551 return fd;
1552 xfunc_die();
1553 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001554 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1555 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001556 close(fd);
1557 return newfd;
1558}
1559
1560
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001561/* Manipulating the list of open FILEs */
1562static FILE *remember_FILE(FILE *fp)
1563{
1564 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001565 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001566 n->next = G.FILE_list;
1567 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568 n->fp = fp;
1569 n->fd = fileno(fp);
1570 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001571 }
1572 return fp;
1573}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001574static void fclose_and_forget(FILE *fp)
1575{
1576 struct FILE_list **pp = &G.FILE_list;
1577 while (*pp) {
1578 struct FILE_list *cur = *pp;
1579 if (cur->fp == fp) {
1580 *pp = cur->next;
1581 free(cur);
1582 break;
1583 }
1584 pp = &cur->next;
1585 }
1586 fclose(fp);
1587}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001588static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001589{
1590 struct FILE_list *fl = G.FILE_list;
1591 while (fl) {
1592 if (fd == fl->fd) {
1593 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001594 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001595 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001596 return 1;
1597 }
1598 fl = fl->next;
1599 }
1600 return 0;
1601}
1602static void restore_redirected_FILEs(void)
1603{
1604 struct FILE_list *fl = G.FILE_list;
1605 while (fl) {
1606 int should_be = fileno(fl->fp);
1607 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001608 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001609 xmove_fd(fl->fd, should_be);
1610 fl->fd = should_be;
1611 }
1612 fl = fl->next;
1613 }
1614}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001615#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001616static void close_all_FILE_list(void)
1617{
1618 struct FILE_list *fl = G.FILE_list;
1619 while (fl) {
1620 /* fclose would also free FILE object.
1621 * It is disastrous if we share memory with a vforked parent.
1622 * I'm not sure we never come here after vfork.
1623 * Therefore just close fd, nothing more.
1624 */
1625 /*fclose(fl->fp); - unsafe */
1626 close(fl->fd);
1627 fl = fl->next;
1628 }
1629}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001630#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001631static int fd_in_FILEs(int fd)
1632{
1633 struct FILE_list *fl = G.FILE_list;
1634 while (fl) {
1635 if (fl->fd == fd)
1636 return 1;
1637 fl = fl->next;
1638 }
1639 return 0;
1640}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001641
1642
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001643/* Helpers for setting new $n and restoring them back
1644 */
1645typedef struct save_arg_t {
1646 char *sv_argv0;
1647 char **sv_g_argv;
1648 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001649 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001650} save_arg_t;
1651
1652static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1653{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001654 sv->sv_argv0 = argv[0];
1655 sv->sv_g_argv = G.global_argv;
1656 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001657 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001658
1659 argv[0] = G.global_argv[0]; /* retain $0 */
1660 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001661 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001662
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001663 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001664}
1665
1666static void restore_G_args(save_arg_t *sv, char **argv)
1667{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001668#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001669 if (G.global_args_malloced) {
1670 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001671 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001672 while (*++pp) /* note: does not free $0 */
1673 free(*pp);
1674 free(G.global_argv);
1675 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001676#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001677 argv[0] = sv->sv_argv0;
1678 G.global_argv = sv->sv_g_argv;
1679 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001680 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001681}
1682
1683
Denis Vlasenkod5762932009-03-31 11:22:57 +00001684/* Basic theory of signal handling in shell
1685 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001686 * This does not describe what hush does, rather, it is current understanding
1687 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001688 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1689 *
1690 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1691 * is finished or backgrounded. It is the same in interactive and
1692 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001693 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001694 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001695 * backgrounds (i.e. stops) or kills all members of currently running
1696 * pipe.
1697 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001698 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001699 * or by SIGINT in interactive shell.
1700 *
1701 * Trap handlers will execute even within trap handlers. (right?)
1702 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001703 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1704 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001705 *
1706 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001707 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001708 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001709 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001710 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001711 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001712 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001713 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001714 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001715 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001716 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001717 *
1718 * SIGQUIT: ignore
1719 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001720 * SIGHUP (interactive):
1721 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001723 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1724 * that all pipe members are stopped. Try this in bash:
1725 * while :; do :; done - ^Z does not background it
1726 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001727 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001728 * of the command line, show prompt. NB: ^C does not send SIGINT
1729 * to interactive shell while shell is waiting for a pipe,
1730 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001731 * Example 1: this waits 5 sec, but does not execute ls:
1732 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1733 * Example 2: this does not wait and does not execute ls:
1734 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1735 * Example 3: this does not wait 5 sec, but executes ls:
1736 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001737 * Example 4: this does not wait and does not execute ls:
1738 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001739 *
1740 * (What happens to signals which are IGN on shell start?)
1741 * (What happens with signal mask on shell start?)
1742 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001743 * Old implementation
1744 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001745 * We use in-kernel pending signal mask to determine which signals were sent.
1746 * We block all signals which we don't want to take action immediately,
1747 * i.e. we block all signals which need to have special handling as described
1748 * above, and all signals which have traps set.
1749 * After each pipe execution, we extract any pending signals via sigtimedwait()
1750 * and act on them.
1751 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001752 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001753 * sigset_t blocked_set: current blocked signal set
1754 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001755 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001756 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001757 * "trap 'cmd' SIGxxx":
1758 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001759 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001760 * unblock signals with special interactive handling
1761 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001762 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001763 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001764 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001765 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001766 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001767 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001768 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001769 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001770 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001771 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001772 * Standard says "When a subshell is entered, traps that are not being ignored
1773 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001774 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001775 *
1776 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001777 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001778 * masked signals are not visible!
1779 *
1780 * New implementation
1781 * ==================
1782 * We record each signal we are interested in by installing signal handler
1783 * for them - a bit like emulating kernel pending signal mask in userspace.
1784 * We are interested in: signals which need to have special handling
1785 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001786 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001787 * After each pipe execution, we extract any pending signals
1788 * and act on them.
1789 *
1790 * unsigned special_sig_mask: a mask of shell-special signals.
1791 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1792 * char *traps[sig] if trap for sig is set (even if it's '').
1793 * sigset_t pending_set: set of sigs we received.
1794 *
1795 * "trap - SIGxxx":
1796 * if sig is in special_sig_mask, set handler back to:
1797 * record_pending_signo, or to IGN if it's a tty stop signal
1798 * if sig is in fatal_sig_mask, set handler back to sigexit.
1799 * else: set handler back to SIG_DFL
1800 * "trap 'cmd' SIGxxx":
1801 * set handler to record_pending_signo.
1802 * "trap '' SIGxxx":
1803 * set handler to SIG_IGN.
1804 * after [v]fork, if we plan to be a shell:
1805 * set signals with special interactive handling to SIG_DFL
1806 * (because child shell is not interactive),
1807 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1808 * after [v]fork, if we plan to exec:
1809 * POSIX says fork clears pending signal mask in child - no need to clear it.
1810 *
1811 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1812 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1813 *
1814 * Note (compat):
1815 * Standard says "When a subshell is entered, traps that are not being ignored
1816 * are set to the default actions". bash interprets it so that traps which
1817 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001818 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001819enum {
1820 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001821 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001822 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001823 | (1 << SIGHUP)
1824 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001825 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001826#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001827 | (1 << SIGTTIN)
1828 | (1 << SIGTTOU)
1829 | (1 << SIGTSTP)
1830#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001831 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001832};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001833
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001834static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001835{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001836 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001837#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001838 if (sig == SIGCHLD) {
1839 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001840//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 +02001841 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001842#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001843}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001844
Denys Vlasenko0806e402011-05-12 23:06:20 +02001845static sighandler_t install_sighandler(int sig, sighandler_t handler)
1846{
1847 struct sigaction old_sa;
1848
1849 /* We could use signal() to install handlers... almost:
1850 * except that we need to mask ALL signals while handlers run.
1851 * I saw signal nesting in strace, race window isn't small.
1852 * SA_RESTART is also needed, but in Linux, signal()
1853 * sets SA_RESTART too.
1854 */
1855 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1856 /* sigfillset(&G.sa.sa_mask); - already done */
1857 /* G.sa.sa_flags = SA_RESTART; - already done */
1858 G.sa.sa_handler = handler;
1859 sigaction(sig, &G.sa, &old_sa);
1860 return old_sa.sa_handler;
1861}
1862
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001863static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001864
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001865static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001866static void restore_ttypgrp_and__exit(void)
1867{
1868 /* xfunc has failed! die die die */
1869 /* no EXIT traps, this is an escape hatch! */
1870 G.exiting = 1;
1871 hush_exit(xfunc_error_retval);
1872}
1873
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001874#if ENABLE_HUSH_JOB
1875
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001876/* Needed only on some libc:
1877 * It was observed that on exit(), fgetc'ed buffered data
1878 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1879 * With the net effect that even after fork(), not vfork(),
1880 * exit() in NOEXECed applet in "sh SCRIPT":
1881 * noexec_applet_here
1882 * echo END_OF_SCRIPT
1883 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1884 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001885 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001886 * and in `cmd` handling.
1887 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1888 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001889static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001890static void fflush_and__exit(void)
1891{
1892 fflush_all();
1893 _exit(xfunc_error_retval);
1894}
1895
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001896/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001897# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001898/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001899# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001900
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001901/* Restores tty foreground process group, and exits.
1902 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001903 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001904 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001905 * We also call it if xfunc is exiting.
1906 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001907static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001908static void sigexit(int sig)
1909{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001910 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001911 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001912 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1913 /* Disable all signals: job control, SIGPIPE, etc.
1914 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1915 */
1916 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001917 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001918 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001919
1920 /* Not a signal, just exit */
1921 if (sig <= 0)
1922 _exit(- sig);
1923
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001924 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001925}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001926#else
1927
Denys Vlasenko8391c482010-05-22 17:50:43 +02001928# define disable_restore_tty_pgrp_on_exit() ((void)0)
1929# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001930
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001931#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001932
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001933static sighandler_t pick_sighandler(unsigned sig)
1934{
1935 sighandler_t handler = SIG_DFL;
1936 if (sig < sizeof(unsigned)*8) {
1937 unsigned sigmask = (1 << sig);
1938
1939#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001940 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001941 if (G_fatal_sig_mask & sigmask)
1942 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001943 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001944#endif
1945 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001946 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001947 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001948 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001949 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001950 * in an endless loop when we try to do some
1951 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001952 */
1953 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1954 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001955 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001956 }
1957 return handler;
1958}
1959
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001960/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001961static void hush_exit(int exitcode)
1962{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001963#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1964 save_history(G.line_input_state);
1965#endif
1966
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001967 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001968 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001969 char *argv[3];
1970 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001971 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001972 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001973 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001974 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001975 * "trap" will still show it, if executed
1976 * in the handler */
1977 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001978 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001979
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001980#if ENABLE_FEATURE_CLEAN_UP
1981 {
1982 struct variable *cur_var;
1983 if (G.cwd != bb_msg_unknown)
1984 free((char*)G.cwd);
1985 cur_var = G.top_var;
1986 while (cur_var) {
1987 struct variable *tmp = cur_var;
1988 if (!cur_var->max_len)
1989 free(cur_var->varstr);
1990 cur_var = cur_var->next;
1991 free(tmp);
1992 }
1993 }
1994#endif
1995
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001996 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001997#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001998 sigexit(- (exitcode & 0xff));
1999#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002000 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002001#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002002}
2003
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002004
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002005//TODO: return a mask of ALL handled sigs?
2006static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002007{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002008 int last_sig = 0;
2009
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002010 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002011 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002012
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002013 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002014 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002015 sig = 0;
2016 do {
2017 sig++;
2018 if (sigismember(&G.pending_set, sig)) {
2019 sigdelset(&G.pending_set, sig);
2020 goto got_sig;
2021 }
2022 } while (sig < NSIG);
2023 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002024 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002025 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002026 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002027 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002028 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002029 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002030 char *argv[3];
2031 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002032 argv[1] = xstrdup(G_traps[sig]);
2033 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002034 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002035 save_rcode = G.last_exitcode;
2036 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002037 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002038//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002039 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002040 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002041 } /* else: "" trap, ignoring signal */
2042 continue;
2043 }
2044 /* not a trap: special action */
2045 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002046 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002047 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002048 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002049 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002050 break;
2051#if ENABLE_HUSH_JOB
2052 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002053//TODO: why are we doing this? ash and dash don't do this,
2054//they have no handler for SIGHUP at all,
2055//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002056 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002057 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058 /* bash is observed to signal whole process groups,
2059 * not individual processes */
2060 for (job = G.job_list; job; job = job->next) {
2061 if (job->pgrp <= 0)
2062 continue;
2063 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2064 if (kill(- job->pgrp, SIGHUP) == 0)
2065 kill(- job->pgrp, SIGCONT);
2066 }
2067 sigexit(SIGHUP);
2068 }
2069#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002070#if ENABLE_HUSH_FAST
2071 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002072 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002073 G.count_SIGCHLD++;
2074//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2075 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002076 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002077 * This simplifies wait builtin a bit.
2078 */
2079 break;
2080#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002081 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002082 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002083 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002084 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002085 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002086 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002087 * in interactive shell, because TERM is ignored.
2088 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002089 break;
2090 }
2091 }
2092 return last_sig;
2093}
2094
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002095
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002096static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002097{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002098 if (force || G.cwd == NULL) {
2099 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2100 * we must not try to free(bb_msg_unknown) */
2101 if (G.cwd == bb_msg_unknown)
2102 G.cwd = NULL;
2103 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2104 if (!G.cwd)
2105 G.cwd = bb_msg_unknown;
2106 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002107 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002108}
2109
Denis Vlasenko83506862007-11-23 13:11:42 +00002110
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002111/*
2112 * Shell and environment variable support
2113 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002114static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002116 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002117 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002118
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002119 pp = &G.top_var;
2120 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002121 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002122 return pp;
2123 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 }
2125 return NULL;
2126}
2127
Denys Vlasenko03dad222010-01-12 23:29:57 +01002128static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002129{
Denys Vlasenko29082232010-07-16 13:52:32 +02002130 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002131 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002132
2133 if (G.expanded_assignments) {
2134 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002135 while (*cpp) {
2136 char *cp = *cpp;
2137 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2138 return cp + len + 1;
2139 cpp++;
2140 }
2141 }
2142
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002143 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002144 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002145 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002146
Denys Vlasenkodea47882009-10-09 15:40:49 +02002147 if (strcmp(name, "PPID") == 0)
2148 return utoa(G.root_ppid);
2149 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002150#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002151 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002152 return utoa(next_random(&G.random_gen));
2153#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154 return NULL;
2155}
2156
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002157static void handle_changed_special_names(const char *name, unsigned name_len)
2158{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002159 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2160 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2161 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002162 cmdedit_update_prompt();
2163 return;
2164 }
2165
2166 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2167 && name_len == 6
2168 ) {
2169#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002170 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002171 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002172 return;
2173 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002174#endif
2175#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002176 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002177 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002178 return;
2179 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002180#endif
2181 }
2182}
2183
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002184/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002185 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002186 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002187#define SETFLAG_EXPORT (1 << 0)
2188#define SETFLAG_UNEXPORT (1 << 1)
2189#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002190#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002191static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002192{
Denys Vlasenko61407802018-04-04 21:14:28 +02002193 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002194 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002195 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002196 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002198 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199
Denis Vlasenko950bd722009-04-21 11:23:56 +00002200 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002201 if (HUSH_DEBUG && !eq_sign)
2202 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002203
Denis Vlasenko950bd722009-04-21 11:23:56 +00002204 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002205 cur_pp = &G.top_var;
2206 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002208 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002209 continue;
2210 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002211
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002214 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002215 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002216//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2217//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002218 return -1;
2219 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002220 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002221 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2222 *eq_sign = '\0';
2223 unsetenv(str);
2224 *eq_sign = '=';
2225 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002226 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002227 /* bash 3.2.33(1) and exported vars:
2228 * # export z=z
2229 * # f() { local z=a; env | grep ^z; }
2230 * # f
2231 * z=a
2232 * # env | grep ^z
2233 * z=z
2234 */
2235 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002236 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002237 /* New variable is local ("local VAR=VAL" or
2238 * "VAR=VAL cmd")
2239 * and existing one is global, or local
2240 * on a lower level that new one.
2241 * Remove it from global variable list:
2242 */
2243 *cur_pp = cur->next;
2244 if (G.shadowed_vars_pp) {
2245 /* Save in "shadowed" list */
2246 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2247 cur->flg_export ? "exported " : "",
2248 cur->varstr, cur->var_nest_level, str, local_lvl
2249 );
2250 cur->next = *G.shadowed_vars_pp;
2251 *G.shadowed_vars_pp = cur;
2252 } else {
2253 /* Came from pseudo_exec_argv(), no need to save: delete it */
2254 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2255 cur->flg_export ? "exported " : "",
2256 cur->varstr, cur->var_nest_level, str, local_lvl
2257 );
2258 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2259 free_me = cur->varstr; /* then free it later */
2260 free(cur);
2261 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002262 break;
2263 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002264
Denis Vlasenko950bd722009-04-21 11:23:56 +00002265 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002266 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002267 free_and_exp:
2268 free(str);
2269 goto exp;
2270 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002271
2272 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002273 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002274 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002275 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002276 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002277 strcpy(cur->varstr, str);
2278 goto free_and_exp;
2279 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002280 /* Can't reuse */
2281 cur->max_len = 0;
2282 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002283 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002284 /* max_len == 0 signifies "malloced" var, which we can
2285 * (and have to) free. But we can't free(cur->varstr) here:
2286 * if cur->flg_export is 1, it is in the environment.
2287 * We should either unsetenv+free, or wait until putenv,
2288 * then putenv(new)+free(old).
2289 */
2290 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291 goto set_str_and_exp;
2292 }
2293
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002294 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002295 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002296 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002297 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002298 cur->next = *cur_pp;
2299 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002300
2301 set_str_and_exp:
2302 cur->varstr = str;
2303 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002304#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002305 if (flags & SETFLAG_MAKE_RO) {
2306 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002307 }
2308#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002309 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310 cur->flg_export = 1;
2311 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002312 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002313 cur->flg_export = 0;
2314 /* unsetenv was already done */
2315 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002316 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002317 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002318 i = putenv(cur->varstr);
2319 /* only now we can free old exported malloced string */
2320 free(free_me);
2321 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002322 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002323 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002324 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002325
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002326 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002327
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 return 0;
2329}
2330
Denys Vlasenko6db47842009-09-05 20:15:17 +02002331/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002332static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002333{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002334 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002335}
2336
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002337#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002338static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339{
2340 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002341 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002342
Denys Vlasenko61407802018-04-04 21:14:28 +02002343 cur_pp = &G.top_var;
2344 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002345 if (strncmp(cur->varstr, name, name_len) == 0
2346 && cur->varstr[name_len] == '='
2347 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002348 if (cur->flg_read_only) {
2349 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002350 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002351 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002352
Denys Vlasenko61407802018-04-04 21:14:28 +02002353 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002354 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2355 bb_unsetenv(cur->varstr);
2356 if (!cur->max_len)
2357 free(cur->varstr);
2358 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002359
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002360 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002361 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002362 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002363 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002364
2365 /* Handle "unset PS1" et al even if did not find the variable to unset */
2366 handle_changed_special_names(name, name_len);
2367
Mike Frysingerd690f682009-03-30 06:50:54 +00002368 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002369}
2370
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002371static int unset_local_var(const char *name)
2372{
2373 return unset_local_var_len(name, strlen(name));
2374}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002375#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002376
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002377#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2378 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002379static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002380{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002381 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002382 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002383}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002384#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002385
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002386
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002387/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002388 * Helpers for "var1=val1 var2=val2 cmd" feature
2389 */
2390static void add_vars(struct variable *var)
2391{
2392 struct variable *next;
2393
2394 while (var) {
2395 next = var->next;
2396 var->next = G.top_var;
2397 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002398 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002399 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002400 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002401 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002402 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002403 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002404 var = next;
2405 }
2406}
2407
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002408/* We put strings[i] into variable table and possibly putenv them.
2409 * If variable is read only, we can free the strings[i]
2410 * which attempts to overwrite it.
2411 * The strings[] vector itself is freed.
2412 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002413static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002414{
2415 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002416
2417 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002418 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002419
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002420 s = strings;
2421 while (*s) {
2422 struct variable *var_p;
2423 struct variable **var_pp;
2424 char *eq;
2425
2426 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002427 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002428 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002429 var_pp = get_ptr_to_local_var(*s, eq - *s);
2430 if (var_pp) {
2431 var_p = *var_pp;
2432 if (var_p->flg_read_only) {
2433 char **p;
2434 bb_error_msg("%s: readonly variable", *s);
2435 /*
2436 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2437 * If VAR is readonly, leaving it in the list
2438 * after asssignment error (msg above)
2439 * causes doubled error message later, on unset.
2440 */
2441 debug_printf_env("removing/freeing '%s' element\n", *s);
2442 free(*s);
2443 p = s;
2444 do { *p = p[1]; p++; } while (*p);
2445 goto next;
2446 }
2447 /* below, set_local_var() with nest level will
2448 * "shadow" (remove) this variable from
2449 * global linked list.
2450 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002451 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002452 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2453 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002454 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002455 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002456 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002457 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002458}
2459
2460
2461/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002462 * Unicode helper
2463 */
2464static void reinit_unicode_for_hush(void)
2465{
2466 /* Unicode support should be activated even if LANG is set
2467 * _during_ shell execution, not only if it was set when
2468 * shell was started. Therefore, re-check LANG every time:
2469 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002470 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2471 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002472 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002473 const char *s = get_local_var_value("LC_ALL");
2474 if (!s) s = get_local_var_value("LC_CTYPE");
2475 if (!s) s = get_local_var_value("LANG");
2476 reinit_unicode(s);
2477 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002478}
2479
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002480/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002481 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483
2484#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002485/* To test correct lineedit/interactive behavior, type from command line:
2486 * echo $P\
2487 * \
2488 * AT\
2489 * H\
2490 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002491 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002492 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002493# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002494static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002496 G.PS1 = get_local_var_value("PS1");
2497 if (G.PS1 == NULL)
2498 G.PS1 = "";
2499 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002500 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002501 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002502}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002503# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002504static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002505{
2506 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002507
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002508 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002509
2510 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2511 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002512 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002513 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2514 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002515 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002516 /* bash uses $PWD value, even if it is set by user.
2517 * It uses current dir only if PWD is unset.
2518 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002519 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002520 }
2521 prompt_str = G.PS1;
2522 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002523 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002524 return prompt_str;
2525}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002526static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002527{
2528 int r;
2529 const char *prompt_str;
2530
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002531 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002532# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002533 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002534 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002535 if (G.flag_SIGINT) {
2536 /* There was ^C'ed, make it look prettier: */
2537 bb_putchar('\n');
2538 G.flag_SIGINT = 0;
2539 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002540 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002541 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002542 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002543 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002544 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002545 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002546 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002547 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002548 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002549 if (r != 0 && !G.flag_SIGINT)
2550 break;
2551 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002552 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2553 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002554 G.last_exitcode = 128 + SIGINT;
2555 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002556 if (r < 0) {
2557 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002558 i->p = NULL;
2559 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002560 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002562 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002563 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002564# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002565 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002566 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002567 if (i->last_char == '\0' || i->last_char == '\n') {
2568 /* Why check_and_run_traps here? Try this interactively:
2569 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2570 * $ <[enter], repeatedly...>
2571 * Without check_and_run_traps, handler never runs.
2572 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002573 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002574 fputs(prompt_str, stdout);
2575 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002576 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002577//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002578 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002579 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2580 * no ^C masking happens during fgetc, no special code for ^C:
2581 * it generates SIGINT as usual.
2582 */
2583 check_and_run_traps();
2584 if (G.flag_SIGINT)
2585 G.last_exitcode = 128 + SIGINT;
2586 if (r != '\0')
2587 break;
2588 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002589 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002590# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002592/* This is the magic location that prints prompts
2593 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002594static int fgetc_interactive(struct in_str *i)
2595{
2596 int ch;
2597 /* If it's interactive stdin, get new line. */
2598 if (G_interactive_fd && i->file == stdin) {
2599 /* Returns first char (or EOF), the rest is in i->p[] */
2600 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002601 G.promptmode = 1; /* PS2 */
2602 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002603 } else {
2604 /* Not stdin: script file, sourced file, etc */
2605 do ch = fgetc(i->file); while (ch == '\0');
2606 }
2607 return ch;
2608}
2609#else
2610static inline int fgetc_interactive(struct in_str *i)
2611{
2612 int ch;
2613 do ch = fgetc(i->file); while (ch == '\0');
2614 return ch;
2615}
2616#endif /* INTERACTIVE */
2617
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002618static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619{
2620 int ch;
2621
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002622 if (!i->file) {
2623 /* string-based in_str */
2624 ch = (unsigned char)*i->p;
2625 if (ch != '\0') {
2626 i->p++;
2627 i->last_char = ch;
2628 return ch;
2629 }
2630 return EOF;
2631 }
2632
2633 /* FILE-based in_str */
2634
Denys Vlasenko4074d492016-09-30 01:49:53 +02002635#if ENABLE_FEATURE_EDITING
2636 /* This can be stdin, check line editing char[] buffer */
2637 if (i->p && *i->p != '\0') {
2638 ch = (unsigned char)*i->p++;
2639 goto out;
2640 }
2641#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002642 /* peek_buf[] is an int array, not char. Can contain EOF. */
2643 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002644 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002645 int ch2 = i->peek_buf[1];
2646 i->peek_buf[0] = ch2;
2647 if (ch2 == 0) /* very likely, avoid redundant write */
2648 goto out;
2649 i->peek_buf[1] = 0;
2650 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002651 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002652
Denys Vlasenko4074d492016-09-30 01:49:53 +02002653 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002654 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002655 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002656 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002657#if ENABLE_HUSH_LINENO_VAR
2658 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002659 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002660 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2661 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002662#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663 return ch;
2664}
2665
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002666static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667{
2668 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002669
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002670 if (!i->file) {
2671 /* string-based in_str */
2672 /* Doesn't report EOF on NUL. None of the callers care. */
2673 return (unsigned char)*i->p;
2674 }
2675
2676 /* FILE-based in_str */
2677
Denys Vlasenko4074d492016-09-30 01:49:53 +02002678#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002679 /* This can be stdin, check line editing char[] buffer */
2680 if (i->p && *i->p != '\0')
2681 return (unsigned char)*i->p;
2682#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002683 /* peek_buf[] is an int array, not char. Can contain EOF. */
2684 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002685 if (ch != 0)
2686 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002687
Denys Vlasenko4074d492016-09-30 01:49:53 +02002688 /* Need to get a new char */
2689 ch = fgetc_interactive(i);
2690 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2691
2692 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2693#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2694 if (i->p) {
2695 i->p -= 1;
2696 return ch;
2697 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002698#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002699 i->peek_buf[0] = ch;
2700 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002701 return ch;
2702}
2703
Denys Vlasenko4074d492016-09-30 01:49:53 +02002704/* Only ever called if i_peek() was called, and did not return EOF.
2705 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2706 * not end-of-line. Therefore we never need to read a new editing line here.
2707 */
2708static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002709{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002710 int ch;
2711
2712 /* There are two cases when i->p[] buffer exists.
2713 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002714 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002715 * In both cases, we know that i->p[0] exists and not NUL, and
2716 * the peek2 result is in i->p[1].
2717 */
2718 if (i->p)
2719 return (unsigned char)i->p[1];
2720
2721 /* Now we know it is a file-based in_str. */
2722
2723 /* peek_buf[] is an int array, not char. Can contain EOF. */
2724 /* Is there 2nd char? */
2725 ch = i->peek_buf[1];
2726 if (ch == 0) {
2727 /* We did not read it yet, get it now */
2728 do ch = fgetc(i->file); while (ch == '\0');
2729 i->peek_buf[1] = ch;
2730 }
2731
2732 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2733 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002734}
2735
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002736static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2737{
2738 for (;;) {
2739 int ch, ch2;
2740
2741 ch = i_getch(input);
2742 if (ch != '\\')
2743 return ch;
2744 ch2 = i_peek(input);
2745 if (ch2 != '\n')
2746 return ch;
2747 /* backslash+newline, skip it */
2748 i_getch(input);
2749 }
2750}
2751
2752/* Note: this function _eats_ \<newline> pairs, safe to use plain
2753 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2754 */
2755static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2756{
2757 for (;;) {
2758 int ch, ch2;
2759
2760 ch = i_peek(input);
2761 if (ch != '\\')
2762 return ch;
2763 ch2 = i_peek2(input);
2764 if (ch2 != '\n')
2765 return ch;
2766 /* backslash+newline, skip it */
2767 i_getch(input);
2768 i_getch(input);
2769 }
2770}
2771
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772static void setup_file_in_str(struct in_str *i, FILE *f)
2773{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002774 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002776 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777}
2778
2779static void setup_string_in_str(struct in_str *i, const char *s)
2780{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002781 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002782 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002783 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784}
2785
2786
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002787/*
2788 * o_string support
2789 */
2790#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002791
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002792static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002793{
2794 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002795 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002796 if (o->data)
2797 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002798}
2799
Denys Vlasenko18567402018-07-20 17:51:31 +02002800static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002801{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002802 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002803 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002804}
2805
Denys Vlasenko18567402018-07-20 17:51:31 +02002806static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002807{
2808 free(o->data);
2809}
2810
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002811static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002812{
2813 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002814 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002815 o->data = xrealloc(o->data, 1 + o->maxlen);
2816 }
2817}
2818
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002819static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002820{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002821 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002822 if (o->length < o->maxlen) {
2823 /* likely. avoid o_grow_by() call */
2824 add:
2825 o->data[o->length] = ch;
2826 o->length++;
2827 o->data[o->length] = '\0';
2828 return;
2829 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002830 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002831 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002832}
2833
Denys Vlasenko657086a2016-09-29 18:07:42 +02002834#if 0
2835/* Valid only if we know o_string is not empty */
2836static void o_delchr(o_string *o)
2837{
2838 o->length--;
2839 o->data[o->length] = '\0';
2840}
2841#endif
2842
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002843static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002844{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002845 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002846 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002847 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002848}
2849
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002850static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002851{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002852 o_addblock(o, str, strlen(str));
2853}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002854
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002855#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002856static void nommu_addchr(o_string *o, int ch)
2857{
2858 if (o)
2859 o_addchr(o, ch);
2860}
2861#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002862# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002863#endif
2864
2865static void o_addstr_with_NUL(o_string *o, const char *str)
2866{
2867 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002868}
2869
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002870/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002871 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002872 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2873 * Apparently, on unquoted $v bash still does globbing
2874 * ("v='*.txt'; echo $v" prints all .txt files),
2875 * but NOT brace expansion! Thus, there should be TWO independent
2876 * quoting mechanisms on $v expansion side: one protects
2877 * $v from brace expansion, and other additionally protects "$v" against globbing.
2878 * We have only second one.
2879 */
2880
Denys Vlasenko9e800222010-10-03 14:28:04 +02002881#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002882# define MAYBE_BRACES "{}"
2883#else
2884# define MAYBE_BRACES ""
2885#endif
2886
Eric Andersen25f27032001-04-26 23:22:31 +00002887/* My analysis of quoting semantics tells me that state information
2888 * is associated with a destination, not a source.
2889 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002890static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002891{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002892 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002893 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002894 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002895 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002896 o_grow_by(o, sz);
2897 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002898 o->data[o->length] = '\\';
2899 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002900 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002901 o->data[o->length] = ch;
2902 o->length++;
2903 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002904}
2905
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002906static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002907{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002908 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002909 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2910 && strchr("*?[\\" MAYBE_BRACES, ch)
2911 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002912 sz++;
2913 o->data[o->length] = '\\';
2914 o->length++;
2915 }
2916 o_grow_by(o, sz);
2917 o->data[o->length] = ch;
2918 o->length++;
2919 o->data[o->length] = '\0';
2920}
2921
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002922static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002923{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002924 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002925 char ch;
2926 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002927 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002928 if (ordinary_cnt > len) /* paranoia */
2929 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002930 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002931 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002932 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002933 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002934 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002935
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002936 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002937 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002938 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002939 sz++;
2940 o->data[o->length] = '\\';
2941 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002942 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002943 o_grow_by(o, sz);
2944 o->data[o->length] = ch;
2945 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002946 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002947 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002948}
2949
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002950static void o_addQblock(o_string *o, const char *str, int len)
2951{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002952 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002953 o_addblock(o, str, len);
2954 return;
2955 }
2956 o_addqblock(o, str, len);
2957}
2958
Denys Vlasenko38292b62010-09-05 14:49:40 +02002959static void o_addQstr(o_string *o, const char *str)
2960{
2961 o_addQblock(o, str, strlen(str));
2962}
2963
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002964/* A special kind of o_string for $VAR and `cmd` expansion.
2965 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002966 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002967 * list[i] contains an INDEX (int!) into this string data.
2968 * It means that if list[] needs to grow, data needs to be moved higher up
2969 * but list[i]'s need not be modified.
2970 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002971 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2973 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002974#if DEBUG_EXPAND || DEBUG_GLOB
2975static void debug_print_list(const char *prefix, o_string *o, int n)
2976{
2977 char **list = (char**)o->data;
2978 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2979 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002980
2981 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002982 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 +02002983 prefix, list, n, string_start, o->length, o->maxlen,
2984 !!(o->o_expflags & EXP_FLAG_GLOB),
2985 o->has_quoted_part,
2986 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002987 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002988 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002989 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2990 o->data + (int)(uintptr_t)list[i] + string_start,
2991 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002992 i++;
2993 }
2994 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002995 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002996 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002997 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002998 }
2999}
3000#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003001# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003002#endif
3003
3004/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3005 * in list[n] so that it points past last stored byte so far.
3006 * It returns n+1. */
3007static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003008{
3009 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003010 int string_start;
3011 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003012
3013 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003014 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3015 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003016 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003017 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003018 /* list[n] points to string_start, make space for 16 more pointers */
3019 o->maxlen += 0x10 * sizeof(list[0]);
3020 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003021 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003022 memmove(list + n + 0x10, list + n, string_len);
3023 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003024 } else {
3025 debug_printf_list("list[%d]=%d string_start=%d\n",
3026 n, string_len, string_start);
3027 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003028 } else {
3029 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003030 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3031 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003032 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3033 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003034 o->has_empty_slot = 0;
3035 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003036 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003037 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003038 return n + 1;
3039}
3040
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003041/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003042static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003043{
3044 char **list = (char**)o->data;
3045 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3046
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003047 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003048}
3049
Denys Vlasenko9e800222010-10-03 14:28:04 +02003050#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003051/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3052 * first, it processes even {a} (no commas), second,
3053 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003054 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003055 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003056
3057/* Helper */
3058static int glob_needed(const char *s)
3059{
3060 while (*s) {
3061 if (*s == '\\') {
3062 if (!s[1])
3063 return 0;
3064 s += 2;
3065 continue;
3066 }
3067 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3068 return 1;
3069 s++;
3070 }
3071 return 0;
3072}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003073/* Return pointer to next closing brace or to comma */
3074static const char *next_brace_sub(const char *cp)
3075{
3076 unsigned depth = 0;
3077 cp++;
3078 while (*cp != '\0') {
3079 if (*cp == '\\') {
3080 if (*++cp == '\0')
3081 break;
3082 cp++;
3083 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003084 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003085 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003086 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003087 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003088 depth++;
3089 }
3090
3091 return *cp != '\0' ? cp : NULL;
3092}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003093/* Recursive brace globber. Note: may garble pattern[]. */
3094static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003095{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003096 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003097 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003098 const char *next;
3099 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003100 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003101 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102
3103 debug_printf_glob("glob_brace('%s')\n", pattern);
3104
3105 begin = pattern;
3106 while (1) {
3107 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003108 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003109 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003110 /* Find the first sub-pattern and at the same time
3111 * find the rest after the closing brace */
3112 next = next_brace_sub(begin);
3113 if (next == NULL) {
3114 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003115 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003116 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003117 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003118 /* "{abc}" with no commas - illegal
3119 * brace expr, disregard and skip it */
3120 begin = next + 1;
3121 continue;
3122 }
3123 break;
3124 }
3125 if (*begin == '\\' && begin[1] != '\0')
3126 begin++;
3127 begin++;
3128 }
3129 debug_printf_glob("begin:%s\n", begin);
3130 debug_printf_glob("next:%s\n", next);
3131
3132 /* Now find the end of the whole brace expression */
3133 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003134 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003135 rest = next_brace_sub(rest);
3136 if (rest == NULL) {
3137 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003138 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003139 }
3140 debug_printf_glob("rest:%s\n", rest);
3141 }
3142 rest_len = strlen(++rest) + 1;
3143
3144 /* We are sure the brace expression is well-formed */
3145
3146 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003147 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003148
3149 /* We have a brace expression. BEGIN points to the opening {,
3150 * NEXT points past the terminator of the first element, and REST
3151 * points past the final }. We will accumulate result names from
3152 * recursive runs for each brace alternative in the buffer using
3153 * GLOB_APPEND. */
3154
3155 p = begin + 1;
3156 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003157 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003158 memcpy(
3159 mempcpy(
3160 mempcpy(new_pattern_buf,
3161 /* We know the prefix for all sub-patterns */
3162 pattern, begin - pattern),
3163 p, next - p),
3164 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003165
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003166 /* Note: glob_brace() may garble new_pattern_buf[].
3167 * That's why we re-copy prefix every time (1st memcpy above).
3168 */
3169 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003170 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003171 /* We saw the last entry */
3172 break;
3173 }
3174 p = next + 1;
3175 next = next_brace_sub(next);
3176 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003177 free(new_pattern_buf);
3178 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003179
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003180 simple_glob:
3181 {
3182 int gr;
3183 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003184
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003185 memset(&globdata, 0, sizeof(globdata));
3186 gr = glob(pattern, 0, NULL, &globdata);
3187 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3188 if (gr != 0) {
3189 if (gr == GLOB_NOMATCH) {
3190 globfree(&globdata);
3191 /* NB: garbles parameter */
3192 unbackslash(pattern);
3193 o_addstr_with_NUL(o, pattern);
3194 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3195 return o_save_ptr_helper(o, n);
3196 }
3197 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003198 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003199 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3200 * but we didn't specify it. Paranoia again. */
3201 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3202 }
3203 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3204 char **argv = globdata.gl_pathv;
3205 while (1) {
3206 o_addstr_with_NUL(o, *argv);
3207 n = o_save_ptr_helper(o, n);
3208 argv++;
3209 if (!*argv)
3210 break;
3211 }
3212 }
3213 globfree(&globdata);
3214 }
3215 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003216}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003217/* Performs globbing on last list[],
3218 * saving each result as a new list[].
3219 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003220static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003221{
3222 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003223
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003224 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003225 if (!o->data)
3226 return o_save_ptr_helper(o, n);
3227 pattern = o->data + o_get_last_ptr(o, n);
3228 debug_printf_glob("glob pattern '%s'\n", pattern);
3229 if (!glob_needed(pattern)) {
3230 /* unbackslash last string in o in place, fix length */
3231 o->length = unbackslash(pattern) - o->data;
3232 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3233 return o_save_ptr_helper(o, n);
3234 }
3235
3236 copy = xstrdup(pattern);
3237 /* "forget" pattern in o */
3238 o->length = pattern - o->data;
3239 n = glob_brace(copy, o, n);
3240 free(copy);
3241 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003242 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003243 return n;
3244}
3245
Denys Vlasenko238081f2010-10-03 14:26:26 +02003246#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003247
3248/* Helper */
3249static int glob_needed(const char *s)
3250{
3251 while (*s) {
3252 if (*s == '\\') {
3253 if (!s[1])
3254 return 0;
3255 s += 2;
3256 continue;
3257 }
3258 if (*s == '*' || *s == '[' || *s == '?')
3259 return 1;
3260 s++;
3261 }
3262 return 0;
3263}
3264/* Performs globbing on last list[],
3265 * saving each result as a new list[].
3266 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003267static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003268{
3269 glob_t globdata;
3270 int gr;
3271 char *pattern;
3272
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003273 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003274 if (!o->data)
3275 return o_save_ptr_helper(o, n);
3276 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003277 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003278 if (!glob_needed(pattern)) {
3279 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003280 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003281 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003282 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003283 return o_save_ptr_helper(o, n);
3284 }
3285
3286 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003287 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3288 * If we glob "*.\*" and don't find anything, we need
3289 * to fall back to using literal "*.*", but GLOB_NOCHECK
3290 * will return "*.\*"!
3291 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003292 gr = glob(pattern, 0, NULL, &globdata);
3293 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003294 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003295 if (gr == GLOB_NOMATCH) {
3296 globfree(&globdata);
3297 goto literal;
3298 }
3299 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003300 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003301 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3302 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003303 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003304 }
3305 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3306 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003307 /* "forget" pattern in o */
3308 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003309 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003310 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003311 n = o_save_ptr_helper(o, n);
3312 argv++;
3313 if (!*argv)
3314 break;
3315 }
3316 }
3317 globfree(&globdata);
3318 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003319 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003320 return n;
3321}
3322
Denys Vlasenko238081f2010-10-03 14:26:26 +02003323#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003324
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003325/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003326 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003327static int o_save_ptr(o_string *o, int n)
3328{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003329 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003330 /* If o->has_empty_slot, list[n] was already globbed
3331 * (if it was requested back then when it was filled)
3332 * so don't do that again! */
3333 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003334 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003335 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003336 return o_save_ptr_helper(o, n);
3337}
3338
3339/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003340static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003341{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003342 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003343 int string_start;
3344
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003345 if (DEBUG_EXPAND)
3346 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003347 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003348 list = (char**)o->data;
3349 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3350 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003351 while (n) {
3352 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003353 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003354 }
3355 return list;
3356}
3357
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003358static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003359
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003360/* Returns pi->next - next pipe in the list */
3361static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003362{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363 struct pipe *next;
3364 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003365
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003366 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003367 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 struct command *command;
3369 struct redir_struct *r, *rnext;
3370
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003371 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003372 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003373 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003374 if (DEBUG_CLEAN) {
3375 int a;
3376 char **p;
3377 for (a = 0, p = command->argv; *p; a++, p++) {
3378 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3379 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 }
3381 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003382 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003383 }
3384 /* not "else if": on syntax error, we may have both! */
3385 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003386 debug_printf_clean(" begin group (cmd_type:%d)\n",
3387 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003388 free_pipe_list(command->group);
3389 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003390 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003391 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003392 /* else is crucial here.
3393 * If group != NULL, child_func is meaningless */
3394#if ENABLE_HUSH_FUNCTIONS
3395 else if (command->child_func) {
3396 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3397 command->child_func->parent_cmd = NULL;
3398 }
3399#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003400#if !BB_MMU
3401 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003402 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003403#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003404 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003405 debug_printf_clean(" redirect %d%s",
3406 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003407 /* guard against the case >$FOO, where foo is unset or blank */
3408 if (r->rd_filename) {
3409 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3410 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003411 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003412 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003413 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003414 rnext = r->next;
3415 free(r);
3416 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003417 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003418 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003419 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003420 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003421#if ENABLE_HUSH_JOB
3422 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003423 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003424#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003425
3426 next = pi->next;
3427 free(pi);
3428 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003429}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003430
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003431static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003432{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003433 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003434#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003435 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003436#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003437 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003438 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003439 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003440}
3441
3442
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003443/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003444
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003445#ifndef debug_print_tree
3446static void debug_print_tree(struct pipe *pi, int lvl)
3447{
3448 static const char *const PIPE[] = {
3449 [PIPE_SEQ] = "SEQ",
3450 [PIPE_AND] = "AND",
3451 [PIPE_OR ] = "OR" ,
3452 [PIPE_BG ] = "BG" ,
3453 };
3454 static const char *RES[] = {
3455 [RES_NONE ] = "NONE" ,
3456# if ENABLE_HUSH_IF
3457 [RES_IF ] = "IF" ,
3458 [RES_THEN ] = "THEN" ,
3459 [RES_ELIF ] = "ELIF" ,
3460 [RES_ELSE ] = "ELSE" ,
3461 [RES_FI ] = "FI" ,
3462# endif
3463# if ENABLE_HUSH_LOOPS
3464 [RES_FOR ] = "FOR" ,
3465 [RES_WHILE] = "WHILE",
3466 [RES_UNTIL] = "UNTIL",
3467 [RES_DO ] = "DO" ,
3468 [RES_DONE ] = "DONE" ,
3469# endif
3470# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3471 [RES_IN ] = "IN" ,
3472# endif
3473# if ENABLE_HUSH_CASE
3474 [RES_CASE ] = "CASE" ,
3475 [RES_CASE_IN ] = "CASE_IN" ,
3476 [RES_MATCH] = "MATCH",
3477 [RES_CASE_BODY] = "CASE_BODY",
3478 [RES_ESAC ] = "ESAC" ,
3479# endif
3480 [RES_XXXX ] = "XXXX" ,
3481 [RES_SNTX ] = "SNTX" ,
3482 };
3483 static const char *const CMDTYPE[] = {
3484 "{}",
3485 "()",
3486 "[noglob]",
3487# if ENABLE_HUSH_FUNCTIONS
3488 "func()",
3489# endif
3490 };
3491
3492 int pin, prn;
3493
3494 pin = 0;
3495 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003496 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3497 lvl*2, "",
3498 pin,
3499 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3500 RES[pi->res_word],
3501 pi->followup, PIPE[pi->followup]
3502 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003503 prn = 0;
3504 while (prn < pi->num_cmds) {
3505 struct command *command = &pi->cmds[prn];
3506 char **argv = command->argv;
3507
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003508 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003509 lvl*2, "", prn,
3510 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003511#if ENABLE_HUSH_LINENO_VAR
3512 fdprintf(2, " LINENO:%u", command->lineno);
3513#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003514 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003515 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003516 CMDTYPE[command->cmd_type],
3517 argv
3518# if !BB_MMU
3519 , " group_as_string:", command->group_as_string
3520# else
3521 , "", ""
3522# endif
3523 );
3524 debug_print_tree(command->group, lvl+1);
3525 prn++;
3526 continue;
3527 }
3528 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003529 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003530 argv++;
3531 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003532 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003533 prn++;
3534 }
3535 pi = pi->next;
3536 pin++;
3537 }
3538}
3539#endif /* debug_print_tree */
3540
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003541static struct pipe *new_pipe(void)
3542{
Eric Andersen25f27032001-04-26 23:22:31 +00003543 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003544 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003545 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003546 return pi;
3547}
3548
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003549/* Command (member of a pipe) is complete, or we start a new pipe
3550 * if ctx->command is NULL.
3551 * No errors possible here.
3552 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553static int done_command(struct parse_context *ctx)
3554{
3555 /* The command is really already in the pipe structure, so
3556 * advance the pipe counter and make a new, null command. */
3557 struct pipe *pi = ctx->pipe;
3558 struct command *command = ctx->command;
3559
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003560#if 0 /* Instead we emit error message at run time */
3561 if (ctx->pending_redirect) {
3562 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003563 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003564 ctx->pending_redirect = NULL;
3565 }
3566#endif
3567
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003569 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003570 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003571 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003572 }
3573 pi->num_cmds++;
3574 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003575 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576 } else {
3577 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3578 }
3579
3580 /* Only real trickiness here is that the uncommitted
3581 * command structure is not counted in pi->num_cmds. */
3582 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003583 ctx->command = command = &pi->cmds[pi->num_cmds];
3584 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003585 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003586#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003587 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003588 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003589#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003590 return pi->num_cmds; /* used only for 0/nonzero check */
3591}
3592
3593static void done_pipe(struct parse_context *ctx, pipe_style type)
3594{
3595 int not_null;
3596
3597 debug_printf_parse("done_pipe entered, followup %d\n", type);
3598 /* Close previous command */
3599 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003600#if HAS_KEYWORDS
3601 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3602 ctx->ctx_inverted = 0;
3603 ctx->pipe->res_word = ctx->ctx_res_w;
3604#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003605 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3606 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003607 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3608 * in a backgrounded subshell.
3609 */
3610 struct pipe *pi;
3611 struct command *command;
3612
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003613 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003614 pi = ctx->list_head;
3615 while (pi != ctx->pipe) {
3616 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3617 goto no_conv;
3618 pi = pi->next;
3619 }
3620
3621 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3622 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3623 pi = xzalloc(sizeof(*pi));
3624 pi->followup = PIPE_BG;
3625 pi->num_cmds = 1;
3626 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3627 command = &pi->cmds[0];
3628 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3629 command->cmd_type = CMD_NORMAL;
3630 command->group = ctx->list_head;
3631#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003632 command->group_as_string = xstrndup(
3633 ctx->as_string.data,
3634 ctx->as_string.length - 1 /* do not copy last char, "&" */
3635 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003636#endif
3637 /* Replace all pipes in ctx with one newly created */
3638 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003639 } else {
3640 no_conv:
3641 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003642 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003643
3644 /* Without this check, even just <enter> on command line generates
3645 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003646 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003647 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003648#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003649 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003650#endif
3651#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003652 || ctx->ctx_res_w == RES_DONE
3653 || ctx->ctx_res_w == RES_FOR
3654 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003655#endif
3656#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003657 || ctx->ctx_res_w == RES_ESAC
3658#endif
3659 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003660 struct pipe *new_p;
3661 debug_printf_parse("done_pipe: adding new pipe: "
3662 "not_null:%d ctx->ctx_res_w:%d\n",
3663 not_null, ctx->ctx_res_w);
3664 new_p = new_pipe();
3665 ctx->pipe->next = new_p;
3666 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003667 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003668 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003669 * This is used to control execution.
3670 * RES_FOR and RES_IN are NOT sticky (needed to support
3671 * cases where variable or value happens to match a keyword):
3672 */
3673#if ENABLE_HUSH_LOOPS
3674 if (ctx->ctx_res_w == RES_FOR
3675 || ctx->ctx_res_w == RES_IN)
3676 ctx->ctx_res_w = RES_NONE;
3677#endif
3678#if ENABLE_HUSH_CASE
3679 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003680 ctx->ctx_res_w = RES_CASE_BODY;
3681 if (ctx->ctx_res_w == RES_CASE)
3682 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003683#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003684 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003685 /* Create the memory for command, roughly:
3686 * ctx->pipe->cmds = new struct command;
3687 * ctx->command = &ctx->pipe->cmds[0];
3688 */
3689 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003690 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003691 }
3692 debug_printf_parse("done_pipe return\n");
3693}
3694
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003695static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003696{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003697 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003698 if (MAYBE_ASSIGNMENT != 0)
3699 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003700 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003701 /* Create the memory for command, roughly:
3702 * ctx->pipe->cmds = new struct command;
3703 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003704 */
3705 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003706}
3707
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003708/* If a reserved word is found and processed, parse context is modified
3709 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003710 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003711#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003712struct reserved_combo {
3713 char literal[6];
3714 unsigned char res;
3715 unsigned char assignment_flag;
3716 int flag;
3717};
3718enum {
3719 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003720# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003721 FLAG_IF = (1 << RES_IF ),
3722 FLAG_THEN = (1 << RES_THEN ),
3723 FLAG_ELIF = (1 << RES_ELIF ),
3724 FLAG_ELSE = (1 << RES_ELSE ),
3725 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003726# endif
3727# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003728 FLAG_FOR = (1 << RES_FOR ),
3729 FLAG_WHILE = (1 << RES_WHILE),
3730 FLAG_UNTIL = (1 << RES_UNTIL),
3731 FLAG_DO = (1 << RES_DO ),
3732 FLAG_DONE = (1 << RES_DONE ),
3733 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003734# endif
3735# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003736 FLAG_MATCH = (1 << RES_MATCH),
3737 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003738# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003739 FLAG_START = (1 << RES_XXXX ),
3740};
3741
3742static const struct reserved_combo* match_reserved_word(o_string *word)
3743{
Eric Andersen25f27032001-04-26 23:22:31 +00003744 /* Mostly a list of accepted follow-up reserved words.
3745 * FLAG_END means we are done with the sequence, and are ready
3746 * to turn the compound list into a command.
3747 * FLAG_START means the word must start a new compound list.
3748 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003749 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003750# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003751 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3752 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3753 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3754 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3755 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3756 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003757# endif
3758# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003759 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3760 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3761 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3762 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3763 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3764 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003765# endif
3766# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003767 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3768 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003769# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003770 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003771 const struct reserved_combo *r;
3772
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003773 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003774 if (strcmp(word->data, r->literal) == 0)
3775 return r;
3776 }
3777 return NULL;
3778}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003779/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003780 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003781static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003782{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003783# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003784 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003785 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003786 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003787# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003788 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003789
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003790 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003791 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003792 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003793 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003794 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003795
3796 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003797# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003798 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3799 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003801 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003802# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003803 if (r->flag == 0) { /* '!' */
3804 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003805 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003806 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003807 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003808 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003809 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003810 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003811 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003812 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003813
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003814 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003815 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003816 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003817 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003818 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003819 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003820 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003821 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003822 } else {
3823 /* "{...} fi" is ok. "{...} if" is not
3824 * Example:
3825 * if { echo foo; } then { echo bar; } fi */
3826 if (ctx->command->group)
3827 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003828 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003829
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003830 ctx->ctx_res_w = r->res;
3831 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003832 ctx->is_assignment = r->assignment_flag;
3833 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003834
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003835 if (ctx->old_flag & FLAG_END) {
3836 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003837
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003838 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003839 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003840 old = ctx->stack;
3841 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003842 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003843# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003844 /* At this point, the compound command's string is in
3845 * ctx->as_string... except for the leading keyword!
3846 * Consider this example: "echo a | if true; then echo a; fi"
3847 * ctx->as_string will contain "true; then echo a; fi",
3848 * with "if " remaining in old->as_string!
3849 */
3850 {
3851 char *str;
3852 int len = old->as_string.length;
3853 /* Concatenate halves */
3854 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003855 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003856 /* Find where leading keyword starts in first half */
3857 str = old->as_string.data + len;
3858 if (str > old->as_string.data)
3859 str--; /* skip whitespace after keyword */
3860 while (str > old->as_string.data && isalpha(str[-1]))
3861 str--;
3862 /* Ugh, we're done with this horrid hack */
3863 old->command->group_as_string = xstrdup(str);
3864 debug_printf_parse("pop, remembering as:'%s'\n",
3865 old->command->group_as_string);
3866 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003867# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003868 *ctx = *old; /* physical copy */
3869 free(old);
3870 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003871 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003872}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003873#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003874
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003875/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003876 * Normal return is 0. Syntax errors return 1.
3877 * Note: on return, word is reset, but not o_free'd!
3878 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003879static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003880{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003881 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003882
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003883 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3884 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003885 debug_printf_parse("done_word return 0: true null, ignored\n");
3886 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003887 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003888
Eric Andersen25f27032001-04-26 23:22:31 +00003889 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003890 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3891 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003892 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003893 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003894 * If the redirection operator is "<<" or "<<-", the word
3895 * that follows the redirection operator shall be
3896 * subjected to quote removal; it is unspecified whether
3897 * any of the other expansions occur. For the other
3898 * redirection operators, the word that follows the
3899 * redirection operator shall be subjected to tilde
3900 * expansion, parameter expansion, command substitution,
3901 * arithmetic expansion, and quote removal.
3902 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003903 * on the word by a non-interactive shell; an interactive
3904 * shell may perform it, but shall do so only when
3905 * the expansion would result in one word."
3906 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003907//bash does not do parameter/command substitution or arithmetic expansion
3908//for _heredoc_ redirection word: these constructs look for exact eof marker
3909// as written:
3910// <<EOF$t
3911// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003912// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3913
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003914 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003915 /* Cater for >\file case:
3916 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3917 * Same with heredocs:
3918 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3919 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003920 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3921 unbackslash(ctx->pending_redirect->rd_filename);
3922 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003923 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003924 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3925 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003926 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003927 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003928 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003929 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003930#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003931# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003932 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003933 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003934 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003935 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003936 /* ctx->ctx_res_w = RES_MATCH; */
3937 ctx->ctx_dsemicolon = 0;
3938 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003939# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003940 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003941# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003942 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3943 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003944# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003945# if ENABLE_HUSH_CASE
3946 && ctx->ctx_res_w != RES_CASE
3947# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003948 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003949 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003950 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003951 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003952 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003953# if ENABLE_HUSH_LINENO_VAR
3954/* Case:
3955 * "while ...; do
3956 * cmd ..."
3957 * If we don't close the pipe _now_, immediately after "do", lineno logic
3958 * sees "cmd" as starting at "do" - i.e., at the previous line.
3959 */
3960 if (0
3961 IF_HUSH_IF(|| reserved->res == RES_THEN)
3962 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3963 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3964 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3965 ) {
3966 done_pipe(ctx, PIPE_SEQ);
3967 }
3968# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003969 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003970 debug_printf_parse("done_word return %d\n",
3971 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003972 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003973 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003974# if defined(CMD_SINGLEWORD_NOGLOB)
3975 if (0
3976# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003977 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003978# endif
3979 /* In bash, local/export/readonly are special, args
3980 * are assignments and therefore expansion of them
3981 * should be "one-word" expansion:
3982 * $ export i=`echo 'a b'` # one arg: "i=a b"
3983 * compare with:
3984 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3985 * ls: cannot access i=a: No such file or directory
3986 * ls: cannot access b: No such file or directory
3987 * Note: bash 3.2.33(1) does this only if export word
3988 * itself is not quoted:
3989 * $ export i=`echo 'aaa bbb'`; echo "$i"
3990 * aaa bbb
3991 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3992 * aaa
3993 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003994 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3995 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3996 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003997 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003998 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3999 }
4000 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004001# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004002 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004003#endif /* HAS_KEYWORDS */
4004
Denis Vlasenkobb929512009-04-16 10:59:40 +00004005 if (command->group) {
4006 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004007 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004008 debug_printf_parse("done_word return 1: syntax error, "
4009 "groups and arglists don't mix\n");
4010 return 1;
4011 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004012
4013 /* If this word wasn't an assignment, next ones definitely
4014 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004015 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4016 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004017 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004018 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004019 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004020 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004021 command->assignment_cnt++;
4022 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4023 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004024 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4025 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004026 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004027 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4028 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004029 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004030 }
Eric Andersen25f27032001-04-26 23:22:31 +00004031
Denis Vlasenko06810332007-05-21 23:30:54 +00004032#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004033 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004034 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004035 || !is_well_formed_var_name(command->argv[0], '\0')
4036 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004037 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004038 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004039 return 1;
4040 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004041 /* Force FOR to have just one word (variable name) */
4042 /* NB: basically, this makes hush see "for v in ..."
4043 * syntax as if it is "for v; in ...". FOR and IN become
4044 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004045 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004046 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004047#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004048#if ENABLE_HUSH_CASE
4049 /* Force CASE to have just one word */
4050 if (ctx->ctx_res_w == RES_CASE) {
4051 done_pipe(ctx, PIPE_SEQ);
4052 }
4053#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004054
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004055 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004056
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004057 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004058 return 0;
4059}
4060
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004061
4062/* Peek ahead in the input to find out if we have a "&n" construct,
4063 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004064 * Return:
4065 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4066 * REDIRFD_SYNTAX_ERR if syntax error,
4067 * REDIRFD_TO_FILE if no & was seen,
4068 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004069 */
4070#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004071#define parse_redir_right_fd(as_string, input) \
4072 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004073#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004074static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004075{
4076 int ch, d, ok;
4077
4078 ch = i_peek(input);
4079 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004080 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004081
4082 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004083 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004084 ch = i_peek(input);
4085 if (ch == '-') {
4086 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004087 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004088 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004089 }
4090 d = 0;
4091 ok = 0;
4092 while (ch != EOF && isdigit(ch)) {
4093 d = d*10 + (ch-'0');
4094 ok = 1;
4095 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004096 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 ch = i_peek(input);
4098 }
4099 if (ok) return d;
4100
4101//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4102
4103 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004104 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004105}
4106
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004107/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004108 */
4109static int parse_redirect(struct parse_context *ctx,
4110 int fd,
4111 redir_type style,
4112 struct in_str *input)
4113{
4114 struct command *command = ctx->command;
4115 struct redir_struct *redir;
4116 struct redir_struct **redirp;
4117 int dup_num;
4118
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004119 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004120 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004121 /* Check for a '>&1' type redirect */
4122 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4123 if (dup_num == REDIRFD_SYNTAX_ERR)
4124 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004125 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004126 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004127 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004128 if (dup_num) { /* <<-... */
4129 ch = i_getch(input);
4130 nommu_addchr(&ctx->as_string, ch);
4131 ch = i_peek(input);
4132 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004135 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004136 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004137 if (ch == '|') {
4138 /* >|FILE redirect ("clobbering" >).
4139 * Since we do not support "set -o noclobber" yet,
4140 * >| and > are the same for now. Just eat |.
4141 */
4142 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004143 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 }
4145 }
4146
4147 /* Create a new redir_struct and append it to the linked list */
4148 redirp = &command->redirects;
4149 while ((redir = *redirp) != NULL) {
4150 redirp = &(redir->next);
4151 }
4152 *redirp = redir = xzalloc(sizeof(*redir));
4153 /* redir->next = NULL; */
4154 /* redir->rd_filename = NULL; */
4155 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004156 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004158 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4159 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004160
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004161 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004162 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004163 /* Erik had a check here that the file descriptor in question
4164 * is legit; I postpone that to "run time"
4165 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004166 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4167 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004168 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004169#if 0 /* Instead we emit error message at run time */
4170 if (ctx->pending_redirect) {
4171 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004172 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004173 }
4174#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 /* Set ctx->pending_redirect, so we know what to do at the
4176 * end of the next parsed word. */
4177 ctx->pending_redirect = redir;
4178 }
4179 return 0;
4180}
4181
Eric Andersen25f27032001-04-26 23:22:31 +00004182/* If a redirect is immediately preceded by a number, that number is
4183 * supposed to tell which file descriptor to redirect. This routine
4184 * looks for such preceding numbers. In an ideal world this routine
4185 * needs to handle all the following classes of redirects...
4186 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4187 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4188 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4189 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004190 *
4191 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4192 * "2.7 Redirection
4193 * ... If n is quoted, the number shall not be recognized as part of
4194 * the redirection expression. For example:
4195 * echo \2>a
4196 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004197 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004198 *
4199 * A -1 return means no valid number was found,
4200 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004201 */
4202static int redirect_opt_num(o_string *o)
4203{
4204 int num;
4205
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004207 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004208 num = bb_strtou(o->data, NULL, 10);
4209 if (errno || num < 0)
4210 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004211 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004212 return num;
4213}
4214
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004215#if BB_MMU
4216#define fetch_till_str(as_string, input, word, skip_tabs) \
4217 fetch_till_str(input, word, skip_tabs)
4218#endif
4219static char *fetch_till_str(o_string *as_string,
4220 struct in_str *input,
4221 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004222 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004223{
4224 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004225 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004226 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004227 int ch;
4228
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004229 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004230
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004231 while (1) {
4232 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004233 if (ch != EOF)
4234 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004235 if (ch == '\n' || ch == EOF) {
4236 check_heredoc_end:
4237 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4238 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4239 heredoc.data[past_EOL] = '\0';
4240 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4241 return heredoc.data;
4242 }
4243 if (ch == '\n') {
4244 /* This is a new line.
4245 * Remember position and backslash-escaping status.
4246 */
4247 o_addchr(&heredoc, ch);
4248 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004250 past_EOL = heredoc.length;
4251 /* Get 1st char of next line, possibly skipping leading tabs */
4252 do {
4253 ch = i_getch(input);
4254 if (ch != EOF)
4255 nommu_addchr(as_string, ch);
4256 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4257 /* If this immediately ended the line,
4258 * go back to end-of-line checks.
4259 */
4260 if (ch == '\n')
4261 goto check_heredoc_end;
4262 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004263 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004264 }
4265 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004266 o_free(&heredoc);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004267 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004268 }
4269 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004270 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004271 if (prev == '\\' && ch == '\\')
4272 /* Correctly handle foo\\<eol> (not a line cont.) */
4273 prev = 0; /* not \ */
4274 else
4275 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004276 }
4277}
4278
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004279/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4280 * and load them all. There should be exactly heredoc_cnt of them.
4281 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004282static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4283{
4284 struct pipe *pi = ctx->list_head;
4285
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004286 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004287 int i;
4288 struct command *cmd = pi->cmds;
4289
4290 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4291 pi->num_cmds,
4292 cmd->argv ? cmd->argv[0] : "NONE");
4293 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004294 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004295
4296 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4297 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004298 while (redir) {
4299 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004300 char *p;
4301
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004302 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004303 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004304 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004305 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004306 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004307 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004308 return 1;
4309 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004310 free(redir->rd_filename);
4311 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004312 heredoc_cnt--;
4313 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004314 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004315 }
4316 cmd++;
4317 }
4318 pi = pi->next;
4319 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004320#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004321 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004322 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004323 bb_error_msg_and_die("heredoc BUG 2");
4324#endif
4325 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326}
4327
4328
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004329static int run_list(struct pipe *pi);
4330#if BB_MMU
4331#define parse_stream(pstring, input, end_trigger) \
4332 parse_stream(input, end_trigger)
4333#endif
4334static struct pipe *parse_stream(char **pstring,
4335 struct in_str *input,
4336 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004337
Eric Andersen25f27032001-04-26 23:22:31 +00004338
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004339static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004340 struct in_str *input, int ch)
4341{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004342 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004343 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004344 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004345#if BB_MMU
4346# define as_string NULL
4347#else
4348 char *as_string = NULL;
4349#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004350 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004351 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004352 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004353
4354 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004355#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004356 if (ch == '(' && !ctx->word.has_quoted_part) {
4357 if (ctx->word.length)
4358 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004359 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004360 if (!command->argv)
4361 goto skip; /* (... */
4362 if (command->argv[1]) { /* word word ... (... */
4363 syntax_error_unexpected_ch('(');
4364 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004365 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004366 /* it is "word(..." or "word (..." */
4367 do
4368 ch = i_getch(input);
4369 while (ch == ' ' || ch == '\t');
4370 if (ch != ')') {
4371 syntax_error_unexpected_ch(ch);
4372 return 1;
4373 }
4374 nommu_addchr(&ctx->as_string, ch);
4375 do
4376 ch = i_getch(input);
4377 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004378 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004379 syntax_error_unexpected_ch(ch);
4380 return 1;
4381 }
4382 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004383 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004384 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004385 }
4386#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004387
4388#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004389 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004390 || ctx->word.length /* word{... */
4391 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004392 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004393 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004394 debug_printf_parse("parse_group return 1: "
4395 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004396 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004397 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004398#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004399
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004400 IF_HUSH_FUNCTIONS(skip:)
4401
Denis Vlasenko240c2552009-04-03 03:45:05 +00004402 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004403 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004404 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004405 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4406 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004407 } else {
4408 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004409 ch = i_peek(input);
4410 if (ch != ' ' && ch != '\t' && ch != '\n'
4411 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4412 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004413 syntax_error_unexpected_ch(ch);
4414 return 1;
4415 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004416 if (ch != '(') {
4417 ch = i_getch(input);
4418 nommu_addchr(&ctx->as_string, ch);
4419 }
Eric Andersen25f27032001-04-26 23:22:31 +00004420 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004421
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004422 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004423#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004424 if (as_string)
4425 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004426#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004427
4428 /* empty ()/{} or parse error? */
4429 if (!pipe_list || pipe_list == ERR_PTR) {
4430 /* parse_stream already emitted error msg */
4431 if (!BB_MMU)
4432 free(as_string);
4433 debug_printf_parse("parse_group return 1: "
4434 "parse_stream returned %p\n", pipe_list);
4435 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004436 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004437#if !BB_MMU
4438 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4439 command->group_as_string = as_string;
4440 debug_printf_parse("end of group, remembering as:'%s'\n",
4441 command->group_as_string);
4442#endif
4443
4444#if ENABLE_HUSH_FUNCTIONS
4445 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4446 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4447 struct command *cmd2;
4448
4449 cmd2 = xzalloc(sizeof(*cmd2));
4450 cmd2->cmd_type = CMD_SUBSHELL;
4451 cmd2->group = pipe_list;
4452# if !BB_MMU
4453//UNTESTED!
4454 cmd2->group_as_string = command->group_as_string;
4455 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4456# endif
4457
4458 pipe_list = new_pipe();
4459 pipe_list->cmds = cmd2;
4460 pipe_list->num_cmds = 1;
4461 }
4462#endif
4463
4464 command->group = pipe_list;
4465
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004466 debug_printf_parse("parse_group return 0\n");
4467 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004468 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004469#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004470}
4471
Denys Vlasenko0b883582016-12-23 16:49:07 +01004472#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004473/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004474static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004476static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477{
4478 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004479 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004480 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004481 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004482 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004483 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004484 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004485 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004486 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004487 }
4488}
4489/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004490static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004491{
4492 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004493 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004494 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004495 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004496 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004497 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004498 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004499 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004500 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004501 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004502 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004503 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004504 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004505 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004506 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4507 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004508 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004509 continue;
4510 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004511 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004512 }
4513}
4514/* Process `cmd` - copy contents until "`" is seen. Complicated by
4515 * \` quoting.
4516 * "Within the backquoted style of command substitution, backslash
4517 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4518 * The search for the matching backquote shall be satisfied by the first
4519 * backquote found without a preceding backslash; during this search,
4520 * if a non-escaped backquote is encountered within a shell comment,
4521 * a here-document, an embedded command substitution of the $(command)
4522 * form, or a quoted string, undefined results occur. A single-quoted
4523 * or double-quoted string that begins, but does not end, within the
4524 * "`...`" sequence produces undefined results."
4525 * Example Output
4526 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4527 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004528static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004529{
4530 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004531 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004532 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004533 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004534 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004535 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4536 ch = i_getch(input);
4537 if (ch != '`'
4538 && ch != '$'
4539 && ch != '\\'
4540 && (!in_dquote || ch != '"')
4541 ) {
4542 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004543 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004544 }
4545 if (ch == EOF) {
4546 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004547 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004548 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004549 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004550 }
4551}
4552/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4553 * quoting and nested ()s.
4554 * "With the $(command) style of command substitution, all characters
4555 * following the open parenthesis to the matching closing parenthesis
4556 * constitute the command. Any valid shell script can be used for command,
4557 * except a script consisting solely of redirections which produces
4558 * unspecified results."
4559 * Example Output
4560 * echo $(echo '(TEST)' BEST) (TEST) BEST
4561 * echo $(echo 'TEST)' BEST) TEST) BEST
4562 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004563 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004564 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004565 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004566 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4567 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004569#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004570static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004572 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004573 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004574# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004575 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004576# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004577 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4578
Denys Vlasenko817a2022018-06-26 15:35:17 +02004579#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004580 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004581#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004582 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4583
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004584 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004585 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004586 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004587 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004589 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004590 if (ch == end_ch
4591# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004592 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004593# endif
4594 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004595 if (!dbl)
4596 break;
4597 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004598 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004599 i_getch(input); /* eat second ')' */
4600 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004601 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004602 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004603 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004604 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004605 if (ch == '(' || ch == '{') {
4606 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004607 if (!add_till_closing_bracket(dest, input, ch))
4608 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004609 o_addchr(dest, ch);
4610 continue;
4611 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004612 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004613 if (!add_till_single_quote(dest, input))
4614 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004615 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004616 continue;
4617 }
4618 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004619 if (!add_till_double_quote(dest, input))
4620 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004621 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004622 continue;
4623 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004624 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004625 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4626 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004627 o_addchr(dest, ch);
4628 continue;
4629 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004630 if (ch == '\\') {
4631 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004632 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004633 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004634 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004635 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004636 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004637#if 0
4638 if (ch == '\n') {
4639 /* "backslash+newline", ignore both */
4640 o_delchr(dest); /* undo insertion of '\' */
4641 continue;
4642 }
4643#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004644 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004645 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004646 continue;
4647 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004648 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004649 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004650 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004651}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004652#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004653
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004654/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004655#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004656#define parse_dollar(as_string, dest, input, quote_mask) \
4657 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004658#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004659#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004660static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004661 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004662 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004663{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004664 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004665
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004666 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004667 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004668 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004669 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004670 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004671 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004673 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004674 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004675 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004676 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004677 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004678 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004679 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004680 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004681 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004682 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004683 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004684 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004686 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004687 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004688 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004689 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004691 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004692 o_addchr(dest, ch | quote_mask);
4693 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004694 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004695 case '$': /* pid */
4696 case '!': /* last bg pid */
4697 case '?': /* last exit code */
4698 case '#': /* number of args */
4699 case '*': /* args */
4700 case '@': /* args */
4701 goto make_one_char_var;
4702 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004703 char len_single_ch;
4704
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4706
Denys Vlasenko74369502010-05-21 19:52:01 +02004707 ch = i_getch(input); /* eat '{' */
4708 nommu_addchr(as_string, ch);
4709
Denys Vlasenko46e64982016-09-29 19:50:55 +02004710 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004711 /* It should be ${?}, or ${#var},
4712 * or even ${?+subst} - operator acting on a special variable,
4713 * or the beginning of variable name.
4714 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004715 if (ch == EOF
4716 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4717 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004718 bad_dollar_syntax:
4719 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004720 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4721 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004722 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004723 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004724 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004725 ch |= quote_mask;
4726
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004727 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004728 * However, this regresses some of our testsuite cases
4729 * which check invalid constructs like ${%}.
4730 * Oh well... let's check that the var name part is fine... */
4731
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004732 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004733 unsigned pos;
4734
Denys Vlasenko74369502010-05-21 19:52:01 +02004735 o_addchr(dest, ch);
4736 debug_printf_parse(": '%c'\n", ch);
4737
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004738 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004739 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004740 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004741 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004742
Denys Vlasenko74369502010-05-21 19:52:01 +02004743 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004744 unsigned end_ch;
4745 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004746 /* handle parameter expansions
4747 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4748 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004749 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4750 if (len_single_ch != '#'
4751 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4752 || i_peek(input) != '}'
4753 ) {
4754 goto bad_dollar_syntax;
4755 }
4756 /* else: it's "length of C" ${#C} op,
4757 * where C is a single char
4758 * special var name, e.g. ${#!}.
4759 */
4760 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004761 /* Eat everything until closing '}' (or ':') */
4762 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004763 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004764 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004765 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004766 ) {
4767 /* It's ${var:N[:M]} thing */
4768 end_ch = '}' * 0x100 + ':';
4769 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004770 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004771 && ch == '/'
4772 ) {
4773 /* It's ${var/[/]pattern[/repl]} thing */
4774 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4775 i_getch(input);
4776 nommu_addchr(as_string, '/');
4777 ch = '\\';
4778 }
4779 end_ch = '}' * 0x100 + '/';
4780 }
4781 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004782 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004783 if (!BB_MMU)
4784 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004785#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004786 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004787 if (last_ch == 0) /* error? */
4788 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004789#else
4790#error Simple code to only allow ${var} is not implemented
4791#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004792 if (as_string) {
4793 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004794 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004795 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004796
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004797 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4798 && (end_ch & 0xff00)
4799 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004800 /* close the first block: */
4801 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004802 /* while parsing N from ${var:N[:M]}
4803 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004804 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004805 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004806 end_ch = '}';
4807 goto again;
4808 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004809 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004810 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004811 /* it's ${var:N} - emulate :999999999 */
4812 o_addstr(dest, "999999999");
4813 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004814 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004815 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004816 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004817 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004818 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4820 break;
4821 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004822#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004823 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004824 unsigned pos;
4825
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004826 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004827 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004828# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004829 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004830 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004831 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004832 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4833 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004834 if (!BB_MMU)
4835 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004836 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4837 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004838 if (as_string) {
4839 o_addstr(as_string, dest->data + pos);
4840 o_addchr(as_string, ')');
4841 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004842 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004843 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004844 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004845 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004846# endif
4847# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004848 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4849 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004850 if (!BB_MMU)
4851 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004852 if (!add_till_closing_bracket(dest, input, ')'))
4853 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004854 if (as_string) {
4855 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004856 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004857 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004858 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004859# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004860 break;
4861 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004862#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004863 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004864 goto make_var;
4865#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004866 /* TODO: $_ and $-: */
4867 /* $_ Shell or shell script name; or last argument of last command
4868 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4869 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004870 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004871 ch = i_getch(input);
4872 nommu_addchr(as_string, ch);
4873 ch = i_peek_and_eat_bkslash_nl(input);
4874 if (isalnum(ch)) { /* it's $_name or $_123 */
4875 ch = '_';
4876 goto make_var1;
4877 }
4878 /* else: it's $_ */
4879#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004880 default:
4881 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004882 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004883 debug_printf_parse("parse_dollar return 1 (ok)\n");
4884 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004885#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004886}
4887
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004888#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004889#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004890 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004891#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004892#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004893static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004894 o_string *dest,
4895 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004896 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004897{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004898 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004899 int next;
4900
4901 again:
4902 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004903 if (ch != EOF)
4904 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004905 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004906 debug_printf_parse("encode_string return 1 (ok)\n");
4907 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004908 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004909 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004910 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004911 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004912 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004913 }
4914 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004915 if (ch != '\n') {
4916 next = i_peek(input);
4917 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004918 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004919 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02004920 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004921 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004922 /* Testcase: in interactive shell a file with
4923 * echo "unterminated string\<eof>
4924 * is sourced.
4925 */
4926 syntax_error_unterm_ch('"');
4927 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004928 }
4929 /* bash:
4930 * "The backslash retains its special meaning [in "..."]
4931 * only when followed by one of the following characters:
4932 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004933 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004934 * NB: in (unquoted) heredoc, above does not apply to ",
4935 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004936 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004937 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004938 ch = i_getch(input); /* eat next */
4939 if (ch == '\n')
4940 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004941 } /* else: ch remains == '\\', and we double it below: */
4942 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004943 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004944 goto again;
4945 }
4946 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004947 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4948 debug_printf_parse("encode_string return 0: "
4949 "parse_dollar returned 0 (error)\n");
4950 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004951 }
4952 goto again;
4953 }
4954#if ENABLE_HUSH_TICK
4955 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004956 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004957 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4958 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004959 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4960 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004961 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4962 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004963 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004964 }
4965#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004966 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004967 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004968#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004969}
4970
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004971/*
4972 * Scan input until EOF or end_trigger char.
4973 * Return a list of pipes to execute, or NULL on EOF
4974 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004975 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004976 * reset parsing machinery and start parsing anew,
4977 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004978 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004979static struct pipe *parse_stream(char **pstring,
4980 struct in_str *input,
4981 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004982{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004983 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004984 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004985
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004986 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004987 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004988 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004989 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004990 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004991 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004992
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004993 initialize_context(&ctx);
4994
4995 /* If very first arg is "" or '', ctx.word.data may end up NULL.
4996 * Preventing this:
4997 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02004998 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004999
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005000 /* We used to separate words on $IFS here. This was wrong.
5001 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005002 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005003 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005004
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005005 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005006 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005007 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005008 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005009 int ch;
5010 int next;
5011 int redir_fd;
5012 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005013
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005014 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005015 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005016 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005017 if (ch == EOF) {
5018 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005019
5020 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005021 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005022 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005023 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005024 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005025 syntax_error_unterm_ch('(');
5026 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005027 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005028 if (end_trigger == '}') {
5029 syntax_error_unterm_ch('{');
5030 goto parse_error;
5031 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005032
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005033 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005034 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005035 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005036 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005037 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005038 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005039 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005040 /* (this makes bare "&" cmd a no-op.
5041 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005042 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005043 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005044 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005045 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005046 pi = NULL;
5047 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005048#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005049 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005050 if (pstring)
5051 *pstring = ctx.as_string.data;
5052 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005053 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005054#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005055 debug_leave();
5056 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005057 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005058 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005059
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005060 /* Handle "'" and "\" first, as they won't play nice with
5061 * i_peek_and_eat_bkslash_nl() anyway:
5062 * echo z\\
5063 * and
5064 * echo '\
5065 * '
5066 * would break.
5067 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005068 if (ch == '\\') {
5069 ch = i_getch(input);
5070 if (ch == '\n')
5071 continue; /* drop \<newline>, get next char */
5072 nommu_addchr(&ctx.as_string, '\\');
5073 o_addchr(&ctx.word, '\\');
5074 if (ch == EOF) {
5075 /* Testcase: eval 'echo Ok\' */
5076 /* bash-4.3.43 was removing backslash,
5077 * but 4.4.19 retains it, most other shells too
5078 */
5079 continue; /* get next char */
5080 }
5081 /* Example: echo Hello \2>file
5082 * we need to know that word 2 is quoted
5083 */
5084 ctx.word.has_quoted_part = 1;
5085 nommu_addchr(&ctx.as_string, ch);
5086 o_addchr(&ctx.word, ch);
5087 continue; /* get next char */
5088 }
5089 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005090 if (ch == '\'') {
5091 ctx.word.has_quoted_part = 1;
5092 next = i_getch(input);
5093 if (next == '\'' && !ctx.pending_redirect)
5094 goto insert_empty_quoted_str_marker;
5095
5096 ch = next;
5097 while (1) {
5098 if (ch == EOF) {
5099 syntax_error_unterm_ch('\'');
5100 goto parse_error;
5101 }
5102 nommu_addchr(&ctx.as_string, ch);
5103 if (ch == '\'')
5104 break;
5105 if (ch == SPECIAL_VAR_SYMBOL) {
5106 /* Convert raw ^C to corresponding special variable reference */
5107 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5108 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5109 }
5110 o_addqchr(&ctx.word, ch);
5111 ch = i_getch(input);
5112 }
5113 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005114 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005115
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005116 next = '\0';
5117 if (ch != '\n')
5118 next = i_peek_and_eat_bkslash_nl(input);
5119
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005120 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005121 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005122 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005123 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005124 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005125 || ctx.word.length /* word{... - non-special */
5126 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005127 || (next != ';' /* }; - special */
5128 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005129 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005130 && next != '&' /* }& and }&& ... - special */
5131 && next != '|' /* }|| ... - special */
5132 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005133 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005134 ) {
5135 /* They are not special, skip "{}" */
5136 is_special += 2;
5137 }
5138 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005139 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005140
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005141 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005142 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005143 o_addQchr(&ctx.word, ch);
5144 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5145 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005146 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005147 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005148 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005149 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5150 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005151 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005152 continue;
5153 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005154
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005155 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005156#if ENABLE_HUSH_LINENO_VAR
5157/* Case:
5158 * "while ...; do<whitespace><newline>
5159 * cmd ..."
5160 * would think that "cmd" starts in <whitespace> -
5161 * i.e., at the previous line.
5162 * We need to skip all whitespace before newlines.
5163 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005164 while (ch != '\n') {
5165 next = i_peek(input);
5166 if (next != ' ' && next != '\t' && next != '\n')
5167 break; /* next char is not ws */
5168 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005169 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005170 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005171#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005172 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005173 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005174 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005175 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005176 /* Is this a case when newline is simply ignored?
5177 * Some examples:
5178 * "cmd | <newline> cmd ..."
5179 * "case ... in <newline> word) ..."
5180 */
5181 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005182 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005183 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005184 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005185 * Without check #1, interactive shell
5186 * ignores even bare <newline>,
5187 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005188 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005189 * ps2> _ <=== wrong, should be ps1
5190 * Without check #2, "cmd & <newline>"
5191 * is similarly mistreated.
5192 * (BTW, this makes "cmd & cmd"
5193 * and "cmd && cmd" non-orthogonal.
5194 * Really, ask yourself, why
5195 * "cmd && <newline>" doesn't start
5196 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005197 * The only reason is that it might be
5198 * a "cmd1 && <nl> cmd2 &" construct,
5199 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005200 */
5201 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005202 if (pi->num_cmds != 0 /* check #1 */
5203 && pi->followup != PIPE_BG /* check #2 */
5204 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005205 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005206 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005207 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005208 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005209 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005210 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5211 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005212 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005213 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005214 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005215 heredoc_cnt = 0;
5216 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005217 ctx.is_assignment = MAYBE_ASSIGNMENT;
5218 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005219 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005220 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005221 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005222 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005223 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005224
5225 /* "cmd}" or "cmd }..." without semicolon or &:
5226 * } is an ordinary char in this case, even inside { cmd; }
5227 * Pathological example: { ""}; } should exec "}" cmd
5228 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005229 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005230 if (ctx.word.length != 0 /* word} */
5231 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005232 ) {
5233 goto ordinary_char;
5234 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005235 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5236 /* Generally, there should be semicolon: "cmd; }"
5237 * However, bash allows to omit it if "cmd" is
5238 * a group. Examples:
5239 * { { echo 1; } }
5240 * {(echo 1)}
5241 * { echo 0 >&2 | { echo 1; } }
5242 * { while false; do :; done }
5243 * { case a in b) ;; esac }
5244 */
5245 if (ctx.command->group)
5246 goto term_group;
5247 goto ordinary_char;
5248 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005249 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005250 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005251 goto skip_end_trigger;
5252 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005253 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005254 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005255 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005256 && (ch != ';' || heredoc_cnt == 0)
5257#if ENABLE_HUSH_CASE
5258 && (ch != ')'
5259 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005260 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005261 )
5262#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005263 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005264 if (heredoc_cnt) {
5265 /* This is technically valid:
5266 * { cat <<HERE; }; echo Ok
5267 * heredoc
5268 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005269 * HERE
5270 * but we don't support this.
5271 * We require heredoc to be in enclosing {}/(),
5272 * if any.
5273 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005274 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005275 goto parse_error;
5276 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005277 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005278 goto parse_error;
5279 }
5280 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005281 ctx.is_assignment = MAYBE_ASSIGNMENT;
5282 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005283 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005284 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005285 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005286 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005287 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005288#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005289 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005290 if (pstring)
5291 *pstring = ctx.as_string.data;
5292 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005293 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005294#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005295 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5296 /* Example: bare "{ }", "()" */
5297 G.last_exitcode = 2; /* bash compat */
5298 syntax_error_unexpected_ch(ch);
5299 goto parse_error2;
5300 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005301 debug_printf_parse("parse_stream return %p: "
5302 "end_trigger char found\n",
5303 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005304 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005305 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005306 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005307 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005308
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005309 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005310 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005311
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005312 /* Catch <, > before deciding whether this word is
5313 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5314 switch (ch) {
5315 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005316 redir_fd = redirect_opt_num(&ctx.word);
5317 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005318 goto parse_error;
5319 }
5320 redir_style = REDIRECT_OVERWRITE;
5321 if (next == '>') {
5322 redir_style = REDIRECT_APPEND;
5323 ch = i_getch(input);
5324 nommu_addchr(&ctx.as_string, ch);
5325 }
5326#if 0
5327 else if (next == '(') {
5328 syntax_error(">(process) not supported");
5329 goto parse_error;
5330 }
5331#endif
5332 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5333 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005334 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005335 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005336 redir_fd = redirect_opt_num(&ctx.word);
5337 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005338 goto parse_error;
5339 }
5340 redir_style = REDIRECT_INPUT;
5341 if (next == '<') {
5342 redir_style = REDIRECT_HEREDOC;
5343 heredoc_cnt++;
5344 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5345 ch = i_getch(input);
5346 nommu_addchr(&ctx.as_string, ch);
5347 } else if (next == '>') {
5348 redir_style = REDIRECT_IO;
5349 ch = i_getch(input);
5350 nommu_addchr(&ctx.as_string, ch);
5351 }
5352#if 0
5353 else if (next == '(') {
5354 syntax_error("<(process) not supported");
5355 goto parse_error;
5356 }
5357#endif
5358 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5359 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005360 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005361 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005362 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005363 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005364 /* note: we do not add it to &ctx.as_string */
5365/* TODO: in bash:
5366 * comment inside $() goes to the next \n, even inside quoted string (!):
5367 * cmd "$(cmd2 #comment)" - syntax error
5368 * cmd "`cmd2 #comment`" - ok
5369 * We accept both (comment ends where command subst ends, in both cases).
5370 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005371 while (1) {
5372 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005373 if (ch == '\n') {
5374 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005375 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005376 }
5377 ch = i_getch(input);
5378 if (ch == EOF)
5379 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005380 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005381 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005382 }
5383 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005384 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005385 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005386
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005387 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005388 /* check that we are not in word in "a=1 2>word b=1": */
5389 && !ctx.pending_redirect
5390 ) {
5391 /* ch is a special char and thus this word
5392 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005393 ctx.is_assignment = NOT_ASSIGNMENT;
5394 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005395 }
5396
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005397 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5398
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005399 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005400 case SPECIAL_VAR_SYMBOL:
5401 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005402 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5403 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005404 /* fall through */
5405 case '#':
5406 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005407 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005408 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005409 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005410 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005411 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005412 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005413 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005414 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005415 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005416 case '"':
5417 ctx.word.has_quoted_part = 1;
5418 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005419 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005420 insert_empty_quoted_str_marker:
5421 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005422 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5423 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005424 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005425 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005426 if (ctx.is_assignment == NOT_ASSIGNMENT)
5427 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005428 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005429 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005430 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005431 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005432#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005433 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005434 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005435
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005436 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5437 o_addchr(&ctx.word, '`');
5438 USE_FOR_NOMMU(pos = ctx.word.length;)
5439 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005440 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005441# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005442 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005443 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005444# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005445 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5446 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005447 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005448 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005449#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005450 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005451#if ENABLE_HUSH_CASE
5452 case_semi:
5453#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005454 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005455 goto parse_error;
5456 }
5457 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005458#if ENABLE_HUSH_CASE
5459 /* Eat multiple semicolons, detect
5460 * whether it means something special */
5461 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005462 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005463 if (ch != ';')
5464 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005465 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005466 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005467 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005468 ctx.ctx_dsemicolon = 1;
5469 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005470 break;
5471 }
5472 }
5473#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005474 new_cmd:
5475 /* We just finished a cmd. New one may start
5476 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005477 ctx.is_assignment = MAYBE_ASSIGNMENT;
5478 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005479 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005480 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005481 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005482 goto parse_error;
5483 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005484 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005485 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005486 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005487 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005488 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005489 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005490 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005491 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005492 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005493 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005494 goto parse_error;
5495 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005496#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005497 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005498 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005499#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005500 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005501 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005502 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005503 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005504 } else {
5505 /* we could pick up a file descriptor choice here
5506 * with redirect_opt_num(), but bash doesn't do it.
5507 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005508 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005509 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005510 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005511 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005512#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005513 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005514 if (ctx.ctx_res_w == RES_MATCH
5515 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005516 && ctx.word.length == 0 /* not word(... */
5517 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005518 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005519 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005520 }
5521#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005522 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005523 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005524 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005525 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005526 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005527 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005528#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005529 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005530 goto case_semi;
5531#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005532 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005533 /* proper use of this character is caught by end_trigger:
5534 * if we see {, we call parse_group(..., end_trigger='}')
5535 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005536 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005537 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005538 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005539 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005540 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005541 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005542 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005543 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005544
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005545 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005546 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005547 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005548 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005549 struct parse_context *pctx;
5550 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005551
5552 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005553 * Sample for finding leaks on syntax error recovery path.
5554 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005555 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005556 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005557 * while if (true | { true;}); then echo ok; fi; do break; done
5558 * 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 +00005559 */
5560 pctx = &ctx;
5561 do {
5562 /* Update pipe/command counts,
5563 * otherwise freeing may miss some */
5564 done_pipe(pctx, PIPE_SEQ);
5565 debug_printf_clean("freeing list %p from ctx %p\n",
5566 pctx->list_head, pctx);
5567 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005568 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005569 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005570#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005571 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005572#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005573 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005574 if (pctx != &ctx) {
5575 free(pctx);
5576 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005577 IF_HAS_KEYWORDS(pctx = p2;)
5578 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005579
Denys Vlasenko18567402018-07-20 17:51:31 +02005580 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005581#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005582 if (pstring)
5583 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005584#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005585 debug_leave();
5586 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005587 }
Eric Andersen25f27032001-04-26 23:22:31 +00005588}
5589
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590
5591/*** Execution routines ***/
5592
5593/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005594#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005595#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005596 expand_string_to_string(str)
5597#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005598static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005599#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005601#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005602
5603/* expand_strvec_to_strvec() takes a list of strings, expands
5604 * all variable references within and returns a pointer to
5605 * a list of expanded strings, possibly with larger number
5606 * of strings. (Think VAR="a b"; echo $VAR).
5607 * This new list is allocated as a single malloc block.
5608 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005609 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005610 * Caller can deallocate entire list by single free(list). */
5611
Denys Vlasenko238081f2010-10-03 14:26:26 +02005612/* A horde of its helpers come first: */
5613
5614static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5615{
5616 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005617 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005618
Denys Vlasenko9e800222010-10-03 14:28:04 +02005619#if ENABLE_HUSH_BRACE_EXPANSION
5620 if (c == '{' || c == '}') {
5621 /* { -> \{, } -> \} */
5622 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005623 /* And now we want to add { or } and continue:
5624 * o_addchr(o, c);
5625 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005626 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005627 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005628 }
5629#endif
5630 o_addchr(o, c);
5631 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005632 /* \z -> \\\z; \<eol> -> \\<eol> */
5633 o_addchr(o, '\\');
5634 if (len) {
5635 len--;
5636 o_addchr(o, '\\');
5637 o_addchr(o, *str++);
5638 }
5639 }
5640 }
5641}
5642
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005643/* Store given string, finalizing the word and starting new one whenever
5644 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005645 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005646 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005647 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5648 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005649static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005650{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005651 int last_is_ifs = 0;
5652
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005653 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005654 int word_len;
5655
5656 if (!*str) /* EOL - do not finalize word */
5657 break;
5658 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005660 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005661 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005662 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005663 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005664 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005665 * Example: "v='\*'; echo b$v" prints "b\*"
5666 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005667 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005669 /*/ Why can't we do it easier? */
5670 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5671 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5672 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005673 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005674 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005675 if (!*str) /* EOL - do not finalize word */
5676 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005677 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005678
5679 /* We know str here points to at least one IFS char */
5680 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005681 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005682 if (!*str) /* EOL - do not finalize word */
5683 break;
5684
Denys Vlasenko96786362018-04-11 16:02:58 +02005685 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5686 && strchr(G.ifs, *str) /* the second check would fail */
5687 ) {
5688 /* This is a non-whitespace $IFS char */
5689 /* Skip it and IFS whitespace chars, start new word */
5690 str++;
5691 str += strspn(str, G.ifs_whitespace);
5692 goto new_word;
5693 }
5694
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005695 /* Start new word... but not always! */
5696 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005697 if (output->has_quoted_part
5698 /* Case "v=' a'; echo $v":
5699 * here nothing precedes the space in $v expansion,
5700 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005701 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005702 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005703 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005704 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005705 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005706 o_addchr(output, '\0');
5707 debug_print_list("expand_on_ifs", output, n);
5708 n = o_save_ptr(output, n);
5709 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005711
Denys Vlasenko168579a2018-07-19 13:45:54 +02005712 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713 debug_print_list("expand_on_ifs[1]", output, n);
5714 return n;
5715}
5716
5717/* Helper to expand $((...)) and heredoc body. These act as if
5718 * they are in double quotes, with the exception that they are not :).
5719 * Just the rules are similar: "expand only $var and `cmd`"
5720 *
5721 * Returns malloced string.
5722 * As an optimization, we return NULL if expansion is not needed.
5723 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005724static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005725{
5726 char *exp_str;
5727 struct in_str input;
5728 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005729 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005730
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005731 cp = str;
5732 for (;;) {
5733 if (!*cp) return NULL; /* string has no special chars */
5734 if (*cp == '$') break;
5735 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005736#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005737 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005738#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005739 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005740 }
5741
5742 /* We need to expand. Example:
5743 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5744 */
5745 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005746 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005747//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005748 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005749 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005750 EXP_FLAG_ESC_GLOB_CHARS,
5751 /*unbackslash:*/ 1
5752 );
5753 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005754 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005755 return exp_str;
5756}
5757
5758#if !BASH_PATTERN_SUBST
5759#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5760 encode_then_expand_vararg(str, handle_squotes)
5761#endif
5762static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5763{
5764#if !BASH_PATTERN_SUBST
5765 const int do_unbackslash = 0;
5766#endif
5767 char *exp_str;
5768 struct in_str input;
5769 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005770 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005771
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005772 cp = str;
5773 for (;;) {
5774 if (!*cp) return NULL; /* string has no special chars */
5775 if (*cp == '$') break;
5776 if (*cp == '\\') break;
5777 if (*cp == '\'') break;
5778 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005779#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005780 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005781#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005782 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005783 }
5784
5785 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5786 * These can contain single- and double-quoted strings,
5787 * and treated as if the ARG string is initially unquoted. IOW:
5788 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5789 * a dquoted string: "${var#"zz"}"), the difference only comes later
5790 * (word splitting and globbing of the ${var...} result).
5791 */
5792
5793 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005794 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005795 exp_str = NULL;
5796
5797 for (;;) {
5798 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005799
5800 ch = i_getch(&input);
5801 if (ch == EOF) {
5802 if (dest.o_expflags) { /* EXP_FLAG_ESC_GLOB_CHARS set? */
5803 syntax_error_unterm_ch('"');
5804 goto ret; /* error */
5805 }
5806 break;
5807 }
5808 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5809 __func__, ch, ch, !!dest.o_expflags);
5810 if (ch == '\'' && handle_squotes && !dest.o_expflags) {
5811//quoting version of add_till_single_quote() (try to merge?):
5812 for (;;) {
5813 ch = i_getch(&input);
5814 if (ch == EOF) {
5815 syntax_error_unterm_ch('\'');
5816 goto ret; /* error */
5817 }
5818 if (ch == '\'')
5819 break;
5820 o_addqchr(&dest, ch);
5821 }
5822 continue;
5823 }
5824 if (ch == '"') {
5825 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5826 continue;
5827 }
5828 if (ch == '\\') {
5829 ch = i_getch(&input);
5830 if (ch == EOF) {
5831//example? error message? syntax_error_unterm_ch('"');
5832 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5833 goto ret;
5834 }
5835 o_addqchr(&dest, ch);
5836 continue;
5837 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005838 if (ch == '$') {
5839 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5840 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5841 goto ret;
5842 }
5843 continue;
5844 }
5845#if ENABLE_HUSH_TICK
5846 if (ch == '`') {
5847 //unsigned pos = dest->length;
5848 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5849 o_addchr(&dest, 0x80 | '`');
5850 if (!add_till_backquote(&dest, &input,
5851 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5852 )
5853 ) {
5854 goto ret; /* error */
5855 }
5856 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5857 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5858 continue;
5859 }
5860#endif
5861 o_addQchr(&dest, ch);
5862 } /* for (;;) */
5863
5864 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5865 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005866 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5867 do_unbackslash
5868 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005869 ret:
5870 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005871 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005872 return exp_str;
5873}
5874
Denys Vlasenko294eb462018-07-20 16:18:59 +02005875static int expand_vars_to_list(o_string *output, int n, char *arg);
5876
5877static int encode_then_append_var_plusminus(o_string *output, int n,
5878 const char *str, int dquoted)
5879{
5880 struct in_str input;
5881 o_string dest = NULL_O_STRING;
5882
5883#if 0 //todo?
5884 const char *cp;
5885 cp = str;
5886 for (;;) {
5887 if (!*cp) return NULL; /* string has no special chars */
5888 if (*cp == '$') break;
5889 if (*cp == '\\') break;
5890 if (*cp == '\'') break;
5891 if (*cp == '"') break;
5892#if ENABLE_HUSH_TICK
5893 if (*cp == '`') break;
5894#endif
5895 cp++;
5896 }
5897#endif
5898
5899 /* Expanding ARG in ${var+ARG}, ${var-ARG} */
5900
5901 setup_string_in_str(&input, str);
5902
5903 for (;;) {
5904 int ch;
5905
5906 ch = i_getch(&input);
5907 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
5908 __func__, ch, ch, dest.o_expflags);
5909
5910 if (!dest.o_expflags) {
5911 if (ch == EOF)
5912 break;
5913 if (!dquoted && strchr(G.ifs, ch)) {
5914 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
5915 * do not assume we are at the start of the word (PREFIX above).
5916 */
5917 if (dest.data) {
5918 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02005919 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005920 o_addchr(output, '\0');
5921 n = o_save_ptr(output, n); /* create next word */
5922 } else
5923 if (output->length != o_get_last_ptr(output, n)
5924 || output->has_quoted_part
5925 ) {
5926 /* For these cases:
5927 * f() { for i; do echo "|$i|"; done; }; x=x
5928 * f a${x:+ }b # 1st condition
5929 * |a|
5930 * |b|
5931 * f ""${x:+ }b # 2nd condition
5932 * ||
5933 * |b|
5934 */
5935 o_addchr(output, '\0');
5936 n = o_save_ptr(output, n); /* create next word */
5937 }
5938 continue;
5939 }
5940 if (!dquoted && ch == '\'') {
5941//quoting version of add_till_single_quote() (try to merge?):
5942 for (;;) {
5943 ch = i_getch(&input);
5944 if (ch == EOF) {
5945 syntax_error_unterm_ch('\'');
5946 goto ret; /* error */
5947 }
5948 if (ch == '\'')
5949 break;
5950 o_addqchr(&dest, ch);
5951 }
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005952 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5953 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005954 continue;
5955 }
5956 }
5957 if (ch == EOF) {
5958 syntax_error_unterm_ch('"');
5959 goto ret; /* error */
5960 }
5961 if (ch == '"') {
5962 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005963 if (dest.o_expflags) {
5964 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5965 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5966 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02005967 continue;
5968 }
5969 if (ch == '\\') {
5970 ch = i_getch(&input);
5971 if (ch == EOF) {
5972//example? error message? syntax_error_unterm_ch('"');
5973 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5974 goto ret;
5975 }
5976 o_addqchr(&dest, ch);
5977 continue;
5978 }
5979 if (ch == '$') {
5980 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
5981 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5982 goto ret;
5983 }
5984 continue;
5985 }
5986#if ENABLE_HUSH_TICK
5987 if (ch == '`') {
5988 //unsigned pos = dest->length;
5989 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5990 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
5991 if (!add_till_backquote(&dest, &input,
5992 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5993 )
5994 ) {
5995 goto ret; /* error */
5996 }
5997 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5998 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5999 continue;
6000 }
6001#endif
6002 o_addQchr(&dest, ch);
6003 } /* for (;;) */
6004
6005 if (dest.data) {
6006 n = expand_vars_to_list(output, n, dest.data);
6007 }
6008 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006009 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006010 return n;
6011}
6012
Denys Vlasenko0b883582016-12-23 16:49:07 +01006013#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006014static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006015{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006016 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017 arith_t res;
6018 char *exp_str;
6019
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006020 math_state.lookupvar = get_local_var_value;
6021 math_state.setvar = set_local_var_from_halves;
6022 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006023 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006024 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006025 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006026 if (errmsg_p)
6027 *errmsg_p = math_state.errmsg;
6028 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006029 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006030 return res;
6031}
6032#endif
6033
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006034#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006035/* ${var/[/]pattern[/repl]} helpers */
6036static char *strstr_pattern(char *val, const char *pattern, int *size)
6037{
6038 while (1) {
6039 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6040 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6041 if (end) {
6042 *size = end - val;
6043 return val;
6044 }
6045 if (*val == '\0')
6046 return NULL;
6047 /* Optimization: if "*pat" did not match the start of "string",
6048 * we know that "tring", "ring" etc will not match too:
6049 */
6050 if (pattern[0] == '*')
6051 return NULL;
6052 val++;
6053 }
6054}
6055static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6056{
6057 char *result = NULL;
6058 unsigned res_len = 0;
6059 unsigned repl_len = strlen(repl);
6060
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006061 /* Null pattern never matches, including if "var" is empty */
6062 if (!pattern[0])
6063 return result; /* NULL, no replaces happened */
6064
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006065 while (1) {
6066 int size;
6067 char *s = strstr_pattern(val, pattern, &size);
6068 if (!s)
6069 break;
6070
6071 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006072 strcpy(mempcpy(result + res_len, val, s - val), repl);
6073 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006074 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6075
6076 val = s + size;
6077 if (exp_op == '/')
6078 break;
6079 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006080 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 result = xrealloc(result, res_len + strlen(val) + 1);
6082 strcpy(result + res_len, val);
6083 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6084 }
6085 debug_printf_varexp("result:'%s'\n", result);
6086 return result;
6087}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006088#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006089
Denys Vlasenko168579a2018-07-19 13:45:54 +02006090static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006091 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006092{
6093 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6094 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6095 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6096 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006097 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006098 } else { /* quoted "$VAR" */
6099 output->has_quoted_part = 1;
6100 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6101 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6102 if (val && val[0])
6103 o_addQstr(output, val);
6104 }
6105 return n;
6106}
6107
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006108/* Helper:
6109 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6110 */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006111static NOINLINE int expand_one_var(o_string *output,
Denys Vlasenko168579a2018-07-19 13:45:54 +02006112 int n, int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006113{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006114 const char *val;
6115 char *to_be_freed;
6116 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006117 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006118 char exp_op;
6119 char exp_save = exp_save; /* for compiler */
6120 char *exp_saveptr; /* points to expansion operator */
6121 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006122 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006124 val = NULL;
6125 to_be_freed = NULL;
6126 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006127 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006128 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006130 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006131 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006132 exp_op = 0;
6133
Denys Vlasenkob762c782018-07-17 14:21:38 +02006134 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006135 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6136 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6137 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006138 ) {
6139 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006140 var++;
6141 exp_op = 'L';
6142 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006143 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006144 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006145 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006146 ) {
6147 /* ${?:0}, ${#[:]%0} etc */
6148 exp_saveptr = var + 1;
6149 } else {
6150 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6151 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6152 }
6153 exp_op = exp_save = *exp_saveptr;
6154 if (exp_op) {
6155 exp_word = exp_saveptr + 1;
6156 if (exp_op == ':') {
6157 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006158//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006159 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006160 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006161 ) {
6162 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6163 exp_op = ':';
6164 exp_word--;
6165 }
6166 }
6167 *exp_saveptr = '\0';
6168 } /* else: it's not an expansion op, but bare ${var} */
6169 }
6170
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006171 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006173 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006174 int nn = xatoi_positive(var);
6175 if (nn < G.global_argc)
6176 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006177 /* else val remains NULL: $N with too big N */
6178 } else {
6179 switch (var[0]) {
6180 case '$': /* pid */
6181 val = utoa(G.root_pid);
6182 break;
6183 case '!': /* bg pid */
6184 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6185 break;
6186 case '?': /* exitcode */
6187 val = utoa(G.last_exitcode);
6188 break;
6189 case '#': /* argc */
6190 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6191 break;
6192 default:
6193 val = get_local_var_value(var);
6194 }
6195 }
6196
6197 /* Handle any expansions */
6198 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006199 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006200 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006201 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006202 debug_printf_expand("%s\n", val);
6203 } else if (exp_op) {
6204 if (exp_op == '%' || exp_op == '#') {
6205 /* Standard-mandated substring removal ops:
6206 * ${parameter%word} - remove smallest suffix pattern
6207 * ${parameter%%word} - remove largest suffix pattern
6208 * ${parameter#word} - remove smallest prefix pattern
6209 * ${parameter##word} - remove largest prefix pattern
6210 *
6211 * Word is expanded to produce a glob pattern.
6212 * Then var's value is matched to it and matching part removed.
6213 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006214//FIXME: ${x#...${...}...}
6215//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6216//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006217 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006218 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006219 char *exp_exp_word;
6220 char *loc;
6221 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006222 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006223 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006224 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006225 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006226 if (exp_exp_word)
6227 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006228 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6229 /*
6230 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006231 * G.global_argv and results of utoa and get_local_var_value
6232 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006233 * scan_and_match momentarily stores NULs there.
6234 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006235 t = (char*)val;
6236 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006237 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 +02006238 free(exp_exp_word);
6239 if (loc) { /* match was found */
6240 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006241 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006242 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006243 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006244 }
6245 }
6246 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006247#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006248 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006249 /* It's ${var/[/]pattern[/repl]} thing.
6250 * Note that in encoded form it has TWO parts:
6251 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006252 * and if // is used, it is encoded as \:
6253 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006254 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006255 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006256 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006257 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006258 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006259 * >az >bz
6260 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6261 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6262 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6263 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006264 * (note that a*z _pattern_ is never globbed!)
6265 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006266 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006267 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268 if (!pattern)
6269 pattern = xstrdup(exp_word);
6270 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6271 *p++ = SPECIAL_VAR_SYMBOL;
6272 exp_word = p;
6273 p = strchr(p, SPECIAL_VAR_SYMBOL);
6274 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006275 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006276 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6277 /* HACK ALERT. We depend here on the fact that
6278 * G.global_argv and results of utoa and get_local_var_value
6279 * are actually in writable memory:
6280 * replace_pattern momentarily stores NULs there. */
6281 t = (char*)val;
6282 to_be_freed = replace_pattern(t,
6283 pattern,
6284 (repl ? repl : exp_word),
6285 exp_op);
6286 if (to_be_freed) /* at least one replace happened */
6287 val = to_be_freed;
6288 free(pattern);
6289 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006290 } else {
6291 /* Empty variable always gives nothing */
6292 // "v=''; echo ${v/*/w}" prints "", not "w"
6293 /* Just skip "replace" part */
6294 *p++ = SPECIAL_VAR_SYMBOL;
6295 p = strchr(p, SPECIAL_VAR_SYMBOL);
6296 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006297 }
6298 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006299#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006300 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006301#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302 /* It's ${var:N[:M]} bashism.
6303 * Note that in encoded form it has TWO parts:
6304 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6305 */
6306 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006307 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006308
Denys Vlasenko063847d2010-09-15 13:33:02 +02006309 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6310 if (errmsg)
6311 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6313 *p++ = SPECIAL_VAR_SYMBOL;
6314 exp_word = p;
6315 p = strchr(p, SPECIAL_VAR_SYMBOL);
6316 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006317 len = expand_and_evaluate_arith(exp_word, &errmsg);
6318 if (errmsg)
6319 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006320 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006321 if (beg < 0) {
6322 /* negative beg counts from the end */
6323 beg = (arith_t)strlen(val) + beg;
6324 if (beg < 0) /* ${v: -999999} is "" */
6325 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006327 debug_printf_varexp("from val:'%s'\n", val);
6328 if (len < 0) {
6329 /* in bash, len=-n means strlen()-n */
6330 len = (arith_t)strlen(val) - beg + len;
6331 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006332 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006333 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006334 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006335 arith_err:
6336 val = NULL;
6337 } else {
6338 /* Paranoia. What if user entered 9999999999999
6339 * which fits in arith_t but not int? */
6340 if (len >= INT_MAX)
6341 len = INT_MAX;
6342 val = to_be_freed = xstrndup(val + beg, len);
6343 }
6344 debug_printf_varexp("val:'%s'\n", val);
6345#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006346 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006347 val = NULL;
6348#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349 } else { /* one of "-=+?" */
6350 /* Standard-mandated substitution ops:
6351 * ${var?word} - indicate error if unset
6352 * If var is unset, word (or a message indicating it is unset
6353 * if word is null) is written to standard error
6354 * and the shell exits with a non-zero exit status.
6355 * Otherwise, the value of var is substituted.
6356 * ${var-word} - use default value
6357 * If var is unset, word is substituted.
6358 * ${var=word} - assign and use default value
6359 * If var is unset, word is assigned to var.
6360 * In all cases, final value of var is substituted.
6361 * ${var+word} - use alternative value
6362 * If var is unset, null is substituted.
6363 * Otherwise, word is substituted.
6364 *
6365 * Word is subjected to tilde expansion, parameter expansion,
6366 * command substitution, and arithmetic expansion.
6367 * If word is not needed, it is not expanded.
6368 *
6369 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6370 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006371 *
6372 * Word-splitting and single quote behavior:
6373 *
6374 * $ f() { for i; do echo "|$i|"; done; };
6375 *
6376 * $ x=; f ${x:?'x y' z}
6377 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6378 * $ x=; f "${x:?'x y' z}"
6379 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6380 *
6381 * $ x=; f ${x:='x y' z}
6382 * |x|
6383 * |y|
6384 * |z|
6385 * $ x=; f "${x:='x y' z}"
6386 * |'x y' z|
6387 *
6388 * $ x=x; f ${x:+'x y' z}|
6389 * |x y|
6390 * |z|
6391 * $ x=x; f "${x:+'x y' z}"
6392 * |'x y' z|
6393 *
6394 * $ x=; f ${x:-'x y' z}
6395 * |x y|
6396 * |z|
6397 * $ x=; f "${x:-'x y' z}"
6398 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006399 */
6400 int use_word = (!val || ((exp_save == ':') && !val[0]));
6401 if (exp_op == '+')
6402 use_word = !use_word;
6403 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6404 (exp_save == ':') ? "true" : "false", use_word);
6405 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006406 if (exp_op == '+' || exp_op == '-') {
6407 /* ${var+word} - use alternative value */
6408 /* ${var-word} - use default value */
6409 n = encode_then_append_var_plusminus(output, n, exp_word,
6410 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006411 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006412 val = NULL;
6413 } else {
6414 /* ${var?word} - indicate error if unset */
6415 /* ${var=word} - assign and use default value */
6416 to_be_freed = encode_then_expand_vararg(exp_word,
6417 /*handle_squotes:*/ !(arg0 & 0x80),
6418 /*unbackslash:*/ 0
6419 );
6420 if (to_be_freed)
6421 exp_word = to_be_freed;
6422 if (exp_op == '?') {
6423 /* mimic bash message */
6424 msg_and_die_if_script("%s: %s",
6425 var,
6426 exp_word[0]
6427 ? exp_word
6428 : "parameter null or not set"
6429 /* ash has more specific messages, a-la: */
6430 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6431 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006432//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006433//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006434// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6435// bash: x: x y z
6436// $
6437// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006438 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006439 val = exp_word;
6440 }
6441 if (exp_op == '=') {
6442 /* ${var=[word]} or ${var:=[word]} */
6443 if (isdigit(var[0]) || var[0] == '#') {
6444 /* mimic bash message */
6445 msg_and_die_if_script("$%s: cannot assign in this way", var);
6446 val = NULL;
6447 } else {
6448 char *new_var = xasprintf("%s=%s", var, val);
6449 set_local_var(new_var, /*flag:*/ 0);
6450 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006451 }
6452 }
6453 }
6454 } /* one of "-=+?" */
6455
6456 *exp_saveptr = exp_save;
6457 } /* if (exp_op) */
6458
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006459 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006460 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006461
Denys Vlasenko168579a2018-07-19 13:45:54 +02006462 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006463
6464 free(to_be_freed);
6465 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006466}
6467
6468/* Expand all variable references in given string, adding words to list[]
6469 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6470 * to be filled). This routine is extremely tricky: has to deal with
6471 * variables/parameters with whitespace, $* and $@, and constructs like
6472 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006473static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006474{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006475 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006476 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006477 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006478 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006479 char *p;
6480
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006481 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6482 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006483 debug_print_list("expand_vars_to_list[0]", output, n);
6484
6485 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6486 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006487#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488 char arith_buf[sizeof(arith_t)*3 + 2];
6489#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006490
Denys Vlasenko168579a2018-07-19 13:45:54 +02006491 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006492 o_addchr(output, '\0');
6493 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006494 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006495 }
6496
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 o_addblock(output, arg, p - arg);
6498 debug_print_list("expand_vars_to_list[1]", output, n);
6499 arg = ++p;
6500 p = strchr(p, SPECIAL_VAR_SYMBOL);
6501
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006502 /* Fetch special var name (if it is indeed one of them)
6503 * and quote bit, force the bit on if singleword expansion -
6504 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006505 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006506
6507 /* Is this variable quoted and thus expansion can't be null?
6508 * "$@" is special. Even if quoted, it can still
6509 * expand to nothing (not even an empty string),
6510 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006511 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006512 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006513
6514 switch (first_ch & 0x7f) {
6515 /* Highest bit in first_ch indicates that var is double-quoted */
6516 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006517 case '@': {
6518 int i;
6519 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006520 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006521 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006522 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006523 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006524 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006525 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6527 if (G.global_argv[i++][0] && G.global_argv[i]) {
6528 /* this argv[] is not empty and not last:
6529 * put terminating NUL, start new word */
6530 o_addchr(output, '\0');
6531 debug_print_list("expand_vars_to_list[2]", output, n);
6532 n = o_save_ptr(output, n);
6533 debug_print_list("expand_vars_to_list[3]", output, n);
6534 }
6535 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006536 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006537 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006538 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006539 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006540 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006541 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006542 while (1) {
6543 o_addQstr(output, G.global_argv[i]);
6544 if (++i >= G.global_argc)
6545 break;
6546 o_addchr(output, '\0');
6547 debug_print_list("expand_vars_to_list[4]", output, n);
6548 n = o_save_ptr(output, n);
6549 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006550 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 while (1) {
6552 o_addQstr(output, G.global_argv[i]);
6553 if (!G.global_argv[++i])
6554 break;
6555 if (G.ifs[0])
6556 o_addchr(output, G.ifs[0]);
6557 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006558 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006559 }
6560 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006561 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006562 case SPECIAL_VAR_SYMBOL: {
6563 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006564 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006565 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006566 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006567 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006568 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006569 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006570 case SPECIAL_VAR_QUOTED_SVS:
6571 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006572 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006573 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006574 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006575 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006576#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006577 case '`': {
6578 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006579 o_string subst_result = NULL_O_STRING;
6580
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006581 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006582 arg++;
6583 /* Can't just stuff it into output o_string,
6584 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006585 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6587 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006588 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006589 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006590 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006591 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006592 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006593 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006594#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006595#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006596 case '+': {
6597 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006598 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006599
6600 arg++; /* skip '+' */
6601 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6602 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006603 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006604 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6605 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006606 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006607 break;
6608 }
6609#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006610 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006611 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006612 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006613 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006614 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6615
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006616 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6617 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 if (*p != SPECIAL_VAR_SYMBOL)
6619 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620 arg = ++p;
6621 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6622
6623 if (arg[0]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006624 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006625 o_addchr(output, '\0');
6626 n = o_save_ptr(output, n);
6627 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006628 debug_print_list("expand_vars_to_list[a]", output, n);
6629 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006630 * if needed (much earlier), do not use o_addQstr here!
6631 */
6632 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006633 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006634 } else
6635 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006636 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6637 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006638 ) {
6639 n--;
6640 /* allow to reuse list[n] later without re-growth */
6641 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006642 }
6643
6644 return n;
6645}
6646
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006647static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006648{
6649 int n;
6650 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006651 o_string output = NULL_O_STRING;
6652
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006653 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006654
6655 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006656 for (;;) {
6657 /* go to next list[n] */
6658 output.ended_in_ifs = 0;
6659 n = o_save_ptr(&output, n);
6660
6661 if (!*argv)
6662 break;
6663
6664 /* expand argv[i] */
6665 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006666 /* if (!output->has_empty_slot) -- need this?? */
6667 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006668 }
6669 debug_print_list("expand_variables", &output, n);
6670
6671 /* output.data (malloced in one block) gets returned in "list" */
6672 list = o_finalize_list(&output, n);
6673 debug_print_strings("expand_variables[1]", list);
6674 return list;
6675}
6676
6677static char **expand_strvec_to_strvec(char **argv)
6678{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006679 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006680}
6681
Denys Vlasenko11752d42018-04-03 08:20:58 +02006682#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006683static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6684{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006685 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006686}
6687#endif
6688
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006689/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006690 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006691 *
6692 * NB: should NOT do globbing!
6693 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6694 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006695static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006696{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006697#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006698 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006699 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006700#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006701 char *argv[2], **list;
6702
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006703 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006704 /* This is generally an optimization, but it also
6705 * handles "", which otherwise trips over !list[0] check below.
6706 * (is this ever happens that we actually get str="" here?)
6707 */
6708 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6709 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006710 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006711 return xstrdup(str);
6712 }
6713
6714 argv[0] = (char*)str;
6715 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006716 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006717 if (!list[0]) {
6718 /* Example where it happens:
6719 * x=; echo ${x:-"$@"}
6720 */
6721 ((char*)list)[0] = '\0';
6722 } else {
6723 if (HUSH_DEBUG)
6724 if (list[1])
6725 bb_error_msg_and_die("BUG in varexp2");
6726 /* actually, just move string 2*sizeof(char*) bytes back */
6727 overlapping_strcpy((char*)list, list[0]);
6728 if (do_unbackslash)
6729 unbackslash((char*)list);
6730 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006731 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006732 return (char*)list;
6733}
6734
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006735#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006736static char* expand_strvec_to_string(char **argv)
6737{
6738 char **list;
6739
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006740 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006741 /* Convert all NULs to spaces */
6742 if (list[0]) {
6743 int n = 1;
6744 while (list[n]) {
6745 if (HUSH_DEBUG)
6746 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6747 bb_error_msg_and_die("BUG in varexp3");
6748 /* bash uses ' ' regardless of $IFS contents */
6749 list[n][-1] = ' ';
6750 n++;
6751 }
6752 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006753 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6755 return (char*)list;
6756}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006757#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006758
6759static char **expand_assignments(char **argv, int count)
6760{
6761 int i;
6762 char **p;
6763
6764 G.expanded_assignments = p = NULL;
6765 /* Expand assignments into one string each */
6766 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006767 p = add_string_to_strings(p,
6768 expand_string_to_string(argv[i],
6769 EXP_FLAG_ESC_GLOB_CHARS,
6770 /*unbackslash:*/ 1
6771 )
6772 );
6773 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 }
6775 G.expanded_assignments = NULL;
6776 return p;
6777}
6778
6779
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006780static void switch_off_special_sigs(unsigned mask)
6781{
6782 unsigned sig = 0;
6783 while ((mask >>= 1) != 0) {
6784 sig++;
6785 if (!(mask & 1))
6786 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006787#if ENABLE_HUSH_TRAP
6788 if (G_traps) {
6789 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006790 /* trap is '', has to remain SIG_IGN */
6791 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006792 free(G_traps[sig]);
6793 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006794 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006795#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006796 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006797 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006798 }
6799}
6800
Denys Vlasenkob347df92011-08-09 22:49:15 +02006801#if BB_MMU
6802/* never called */
6803void re_execute_shell(char ***to_free, const char *s,
6804 char *g_argv0, char **g_argv,
6805 char **builtin_argv) NORETURN;
6806
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006807static void reset_traps_to_defaults(void)
6808{
6809 /* This function is always called in a child shell
6810 * after fork (not vfork, NOMMU doesn't use this function).
6811 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006812 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006813 unsigned mask;
6814
6815 /* Child shells are not interactive.
6816 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6817 * Testcase: (while :; do :; done) + ^Z should background.
6818 * Same goes for SIGTERM, SIGHUP, SIGINT.
6819 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006820 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006821 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006822 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006823
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006824 /* Switch off special sigs */
6825 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006826# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006827 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006828# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006829 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006830 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6831 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006832
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006833# if ENABLE_HUSH_TRAP
6834 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006835 return;
6836
6837 /* Reset all sigs to default except ones with empty traps */
6838 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006839 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006840 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006841 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006842 continue; /* empty trap: has to remain SIG_IGN */
6843 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006844 free(G_traps[sig]);
6845 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006846 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847 if (sig == 0)
6848 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006849 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006850 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006851# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006852}
6853
6854#else /* !BB_MMU */
6855
6856static void re_execute_shell(char ***to_free, const char *s,
6857 char *g_argv0, char **g_argv,
6858 char **builtin_argv) NORETURN;
6859static void re_execute_shell(char ***to_free, const char *s,
6860 char *g_argv0, char **g_argv,
6861 char **builtin_argv)
6862{
6863# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6864 /* delims + 2 * (number of bytes in printed hex numbers) */
6865 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6866 char *heredoc_argv[4];
6867 struct variable *cur;
6868# if ENABLE_HUSH_FUNCTIONS
6869 struct function *funcp;
6870# endif
6871 char **argv, **pp;
6872 unsigned cnt;
6873 unsigned long long empty_trap_mask;
6874
6875 if (!g_argv0) { /* heredoc */
6876 argv = heredoc_argv;
6877 argv[0] = (char *) G.argv0_for_re_execing;
6878 argv[1] = (char *) "-<";
6879 argv[2] = (char *) s;
6880 argv[3] = NULL;
6881 pp = &argv[3]; /* used as pointer to empty environment */
6882 goto do_exec;
6883 }
6884
6885 cnt = 0;
6886 pp = builtin_argv;
6887 if (pp) while (*pp++)
6888 cnt++;
6889
6890 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006891 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006892 int sig;
6893 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006894 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006895 empty_trap_mask |= 1LL << sig;
6896 }
6897 }
6898
6899 sprintf(param_buf, NOMMU_HACK_FMT
6900 , (unsigned) G.root_pid
6901 , (unsigned) G.root_ppid
6902 , (unsigned) G.last_bg_pid
6903 , (unsigned) G.last_exitcode
6904 , cnt
6905 , empty_trap_mask
6906 IF_HUSH_LOOPS(, G.depth_of_loop)
6907 );
6908# undef NOMMU_HACK_FMT
6909 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6910 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6911 */
6912 cnt += 6;
6913 for (cur = G.top_var; cur; cur = cur->next) {
6914 if (!cur->flg_export || cur->flg_read_only)
6915 cnt += 2;
6916 }
6917# if ENABLE_HUSH_FUNCTIONS
6918 for (funcp = G.top_func; funcp; funcp = funcp->next)
6919 cnt += 3;
6920# endif
6921 pp = g_argv;
6922 while (*pp++)
6923 cnt++;
6924 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6925 *pp++ = (char *) G.argv0_for_re_execing;
6926 *pp++ = param_buf;
6927 for (cur = G.top_var; cur; cur = cur->next) {
6928 if (strcmp(cur->varstr, hush_version_str) == 0)
6929 continue;
6930 if (cur->flg_read_only) {
6931 *pp++ = (char *) "-R";
6932 *pp++ = cur->varstr;
6933 } else if (!cur->flg_export) {
6934 *pp++ = (char *) "-V";
6935 *pp++ = cur->varstr;
6936 }
6937 }
6938# if ENABLE_HUSH_FUNCTIONS
6939 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6940 *pp++ = (char *) "-F";
6941 *pp++ = funcp->name;
6942 *pp++ = funcp->body_as_string;
6943 }
6944# endif
6945 /* We can pass activated traps here. Say, -Tnn:trap_string
6946 *
6947 * However, POSIX says that subshells reset signals with traps
6948 * to SIG_DFL.
6949 * I tested bash-3.2 and it not only does that with true subshells
6950 * of the form ( list ), but with any forked children shells.
6951 * I set trap "echo W" WINCH; and then tried:
6952 *
6953 * { echo 1; sleep 20; echo 2; } &
6954 * while true; do echo 1; sleep 20; echo 2; break; done &
6955 * true | { echo 1; sleep 20; echo 2; } | cat
6956 *
6957 * In all these cases sending SIGWINCH to the child shell
6958 * did not run the trap. If I add trap "echo V" WINCH;
6959 * _inside_ group (just before echo 1), it works.
6960 *
6961 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006962 */
6963 *pp++ = (char *) "-c";
6964 *pp++ = (char *) s;
6965 if (builtin_argv) {
6966 while (*++builtin_argv)
6967 *pp++ = *builtin_argv;
6968 *pp++ = (char *) "";
6969 }
6970 *pp++ = g_argv0;
6971 while (*g_argv)
6972 *pp++ = *g_argv++;
6973 /* *pp = NULL; - is already there */
6974 pp = environ;
6975
6976 do_exec:
6977 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006978 /* Don't propagate SIG_IGN to the child */
6979 if (SPECIAL_JOBSTOP_SIGS != 0)
6980 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006981 execve(bb_busybox_exec_path, argv, pp);
6982 /* Fallback. Useful for init=/bin/hush usage etc */
6983 if (argv[0][0] == '/')
6984 execve(argv[0], argv, pp);
6985 xfunc_error_retval = 127;
6986 bb_error_msg_and_die("can't re-execute the shell");
6987}
6988#endif /* !BB_MMU */
6989
6990
6991static int run_and_free_list(struct pipe *pi);
6992
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006993/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006994 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6995 * end_trigger controls how often we stop parsing
6996 * NUL: parse all, execute, return
6997 * ';': parse till ';' or newline, execute, repeat till EOF
6998 */
6999static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007000{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007001 /* Why we need empty flag?
7002 * An obscure corner case "false; ``; echo $?":
7003 * empty command in `` should still set $? to 0.
7004 * But we can't just set $? to 0 at the start,
7005 * this breaks "false; echo `echo $?`" case.
7006 */
7007 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007008 while (1) {
7009 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007010
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007011#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007012 if (end_trigger == ';') {
7013 G.promptmode = 0; /* PS1 */
7014 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7015 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007016#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007017 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007018 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7019 /* If we are in "big" script
7020 * (not in `cmd` or something similar)...
7021 */
7022 if (pipe_list == ERR_PTR && end_trigger == ';') {
7023 /* Discard cached input (rest of line) */
7024 int ch = inp->last_char;
7025 while (ch != EOF && ch != '\n') {
7026 //bb_error_msg("Discarded:'%c'", ch);
7027 ch = i_getch(inp);
7028 }
7029 /* Force prompt */
7030 inp->p = NULL;
7031 /* This stream isn't empty */
7032 empty = 0;
7033 continue;
7034 }
7035 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007036 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007037 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007038 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007039 debug_print_tree(pipe_list, 0);
7040 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7041 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007042 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007043 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007044 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007045 }
Eric Andersen25f27032001-04-26 23:22:31 +00007046}
7047
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007048static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007049{
7050 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007051 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7052
Eric Andersen25f27032001-04-26 23:22:31 +00007053 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007054 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007055 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007056}
7057
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007058static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007059{
Eric Andersen25f27032001-04-26 23:22:31 +00007060 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007061 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007062
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007063 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01007064 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007065 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007066 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007067}
7068
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007069#if ENABLE_HUSH_TICK
7070static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
7071{
7072 pid_t pid;
7073 int channel[2];
7074# if !BB_MMU
7075 char **to_free = NULL;
7076# endif
7077
7078 xpipe(channel);
7079 pid = BB_MMU ? xfork() : xvfork();
7080 if (pid == 0) { /* child */
7081 disable_restore_tty_pgrp_on_exit();
7082 /* Process substitution is not considered to be usual
7083 * 'command execution'.
7084 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7085 */
7086 bb_signals(0
7087 + (1 << SIGTSTP)
7088 + (1 << SIGTTIN)
7089 + (1 << SIGTTOU)
7090 , SIG_IGN);
7091 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7092 close(channel[0]); /* NB: close _first_, then move fd! */
7093 xmove_fd(channel[1], 1);
7094 /* Prevent it from trying to handle ctrl-z etc */
7095 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007096# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007097 /* Awful hack for `trap` or $(trap).
7098 *
7099 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7100 * contains an example where "trap" is executed in a subshell:
7101 *
7102 * save_traps=$(trap)
7103 * ...
7104 * eval "$save_traps"
7105 *
7106 * Standard does not say that "trap" in subshell shall print
7107 * parent shell's traps. It only says that its output
7108 * must have suitable form, but then, in the above example
7109 * (which is not supposed to be normative), it implies that.
7110 *
7111 * bash (and probably other shell) does implement it
7112 * (traps are reset to defaults, but "trap" still shows them),
7113 * but as a result, "trap" logic is hopelessly messed up:
7114 *
7115 * # trap
7116 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7117 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7118 * # true | trap <--- trap is in subshell - no output (ditto)
7119 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7120 * trap -- 'echo Ho' SIGWINCH
7121 * # echo `(trap)` <--- in subshell in subshell - output
7122 * trap -- 'echo Ho' SIGWINCH
7123 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7124 * trap -- 'echo Ho' SIGWINCH
7125 *
7126 * The rules when to forget and when to not forget traps
7127 * get really complex and nonsensical.
7128 *
7129 * Our solution: ONLY bare $(trap) or `trap` is special.
7130 */
7131 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007132 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007133 && skip_whitespace(s + 4)[0] == '\0'
7134 ) {
7135 static const char *const argv[] = { NULL, NULL };
7136 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007137 fflush_all(); /* important */
7138 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007139 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007140# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007141# if BB_MMU
7142 reset_traps_to_defaults();
7143 parse_and_run_string(s);
7144 _exit(G.last_exitcode);
7145# else
7146 /* We re-execute after vfork on NOMMU. This makes this script safe:
7147 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7148 * huge=`cat BIG` # was blocking here forever
7149 * echo OK
7150 */
7151 re_execute_shell(&to_free,
7152 s,
7153 G.global_argv[0],
7154 G.global_argv + 1,
7155 NULL);
7156# endif
7157 }
7158
7159 /* parent */
7160 *pid_p = pid;
7161# if ENABLE_HUSH_FAST
7162 G.count_SIGCHLD++;
7163//bb_error_msg("[%d] fork in generate_stream_from_string:"
7164// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7165// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7166# endif
7167 enable_restore_tty_pgrp_on_exit();
7168# if !BB_MMU
7169 free(to_free);
7170# endif
7171 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007172 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007173}
7174
7175/* Return code is exit status of the process that is run. */
7176static int process_command_subs(o_string *dest, const char *s)
7177{
7178 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007179 pid_t pid;
7180 int status, ch, eol_cnt;
7181
7182 fp = generate_stream_from_string(s, &pid);
7183
7184 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007185 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007186 while ((ch = getc(fp)) != EOF) {
7187 if (ch == '\0')
7188 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007189 if (ch == '\n') {
7190 eol_cnt++;
7191 continue;
7192 }
7193 while (eol_cnt) {
7194 o_addchr(dest, '\n');
7195 eol_cnt--;
7196 }
7197 o_addQchr(dest, ch);
7198 }
7199
7200 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007201 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007202 /* We need to extract exitcode. Test case
7203 * "true; echo `sleep 1; false` $?"
7204 * should print 1 */
7205 safe_waitpid(pid, &status, 0);
7206 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7207 return WEXITSTATUS(status);
7208}
7209#endif /* ENABLE_HUSH_TICK */
7210
7211
7212static void setup_heredoc(struct redir_struct *redir)
7213{
7214 struct fd_pair pair;
7215 pid_t pid;
7216 int len, written;
7217 /* the _body_ of heredoc (misleading field name) */
7218 const char *heredoc = redir->rd_filename;
7219 char *expanded;
7220#if !BB_MMU
7221 char **to_free;
7222#endif
7223
7224 expanded = NULL;
7225 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007226 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007227 if (expanded)
7228 heredoc = expanded;
7229 }
7230 len = strlen(heredoc);
7231
7232 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7233 xpiped_pair(pair);
7234 xmove_fd(pair.rd, redir->rd_fd);
7235
7236 /* Try writing without forking. Newer kernels have
7237 * dynamically growing pipes. Must use non-blocking write! */
7238 ndelay_on(pair.wr);
7239 while (1) {
7240 written = write(pair.wr, heredoc, len);
7241 if (written <= 0)
7242 break;
7243 len -= written;
7244 if (len == 0) {
7245 close(pair.wr);
7246 free(expanded);
7247 return;
7248 }
7249 heredoc += written;
7250 }
7251 ndelay_off(pair.wr);
7252
7253 /* Okay, pipe buffer was not big enough */
7254 /* Note: we must not create a stray child (bastard? :)
7255 * for the unsuspecting parent process. Child creates a grandchild
7256 * and exits before parent execs the process which consumes heredoc
7257 * (that exec happens after we return from this function) */
7258#if !BB_MMU
7259 to_free = NULL;
7260#endif
7261 pid = xvfork();
7262 if (pid == 0) {
7263 /* child */
7264 disable_restore_tty_pgrp_on_exit();
7265 pid = BB_MMU ? xfork() : xvfork();
7266 if (pid != 0)
7267 _exit(0);
7268 /* grandchild */
7269 close(redir->rd_fd); /* read side of the pipe */
7270#if BB_MMU
7271 full_write(pair.wr, heredoc, len); /* may loop or block */
7272 _exit(0);
7273#else
7274 /* Delegate blocking writes to another process */
7275 xmove_fd(pair.wr, STDOUT_FILENO);
7276 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7277#endif
7278 }
7279 /* parent */
7280#if ENABLE_HUSH_FAST
7281 G.count_SIGCHLD++;
7282//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7283#endif
7284 enable_restore_tty_pgrp_on_exit();
7285#if !BB_MMU
7286 free(to_free);
7287#endif
7288 close(pair.wr);
7289 free(expanded);
7290 wait(NULL); /* wait till child has died */
7291}
7292
Denys Vlasenko2db74612017-07-07 22:07:28 +02007293struct squirrel {
7294 int orig_fd;
7295 int moved_to;
7296 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7297 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7298};
7299
Denys Vlasenko621fc502017-07-24 12:42:17 +02007300static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7301{
7302 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7303 sq[i].orig_fd = orig;
7304 sq[i].moved_to = moved;
7305 sq[i+1].orig_fd = -1; /* end marker */
7306 return sq;
7307}
7308
Denys Vlasenko2db74612017-07-07 22:07:28 +02007309static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7310{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007311 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007312 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007313
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007314 i = 0;
7315 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007316 /* If we collide with an already moved fd... */
7317 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007318 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007319 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7320 if (sq[i].moved_to < 0) /* what? */
7321 xfunc_die();
7322 return sq;
7323 }
7324 if (fd == sq[i].orig_fd) {
7325 /* Example: echo Hello >/dev/null 1>&2 */
7326 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7327 return sq;
7328 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007329 }
7330
Denys Vlasenko2db74612017-07-07 22:07:28 +02007331 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007332 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007333 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7334 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007335 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007336 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007337}
7338
Denys Vlasenko657e9002017-07-30 23:34:04 +02007339static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7340{
7341 int i;
7342
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007343 i = 0;
7344 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007345 /* If we collide with an already moved fd... */
7346 if (fd == sq[i].orig_fd) {
7347 /* Examples:
7348 * "echo 3>FILE 3>&- 3>FILE"
7349 * "echo 3>&- 3>FILE"
7350 * No need for last redirect to insert
7351 * another "need to close 3" indicator.
7352 */
7353 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7354 return sq;
7355 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007356 }
7357
7358 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7359 return append_squirrel(sq, i, fd, -1);
7360}
7361
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007362/* fd: redirect wants this fd to be used (e.g. 3>file).
7363 * Move all conflicting internally used fds,
7364 * and remember them so that we can restore them later.
7365 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007366static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007367{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007368 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7369 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007370
7371#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007372 if (fd == G.interactive_fd) {
7373 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007374 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007375 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7376 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007377 }
7378#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007379 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7380 * (1) Redirect in a forked child. No need to save FILEs' fds,
7381 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007382 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7383 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007384 * "fileno(fd) = new_fd" can't be done.
7385 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007386 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007387 return 0;
7388
Denys Vlasenko2db74612017-07-07 22:07:28 +02007389 /* If this one of script's fds? */
7390 if (save_FILEs_on_redirect(fd, avoid_fd))
7391 return 1; /* yes. "we closed fd" */
7392
7393 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7394 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7395 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007396}
7397
Denys Vlasenko2db74612017-07-07 22:07:28 +02007398static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007399{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007400 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007401 int i;
7402 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007403 if (sq[i].moved_to >= 0) {
7404 /* We simply die on error */
7405 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7406 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7407 } else {
7408 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7409 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7410 close(sq[i].orig_fd);
7411 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007412 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007413 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007414 }
7415
Denys Vlasenko2db74612017-07-07 22:07:28 +02007416 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007417
7418 restore_redirected_FILEs();
7419}
7420
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007421#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007422static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007423{
7424 if (G_interactive_fd)
7425 close(G_interactive_fd);
7426 close_all_FILE_list();
7427}
7428#endif
7429
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007430static int internally_opened_fd(int fd, struct squirrel *sq)
7431{
7432 int i;
7433
7434#if ENABLE_HUSH_INTERACTIVE
7435 if (fd == G.interactive_fd)
7436 return 1;
7437#endif
7438 /* If this one of script's fds? */
7439 if (fd_in_FILEs(fd))
7440 return 1;
7441
7442 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7443 if (fd == sq[i].moved_to)
7444 return 1;
7445 }
7446 return 0;
7447}
7448
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007449/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7450 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007451static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007452{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007453 struct redir_struct *redir;
7454
7455 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007456 int newfd;
7457 int closed;
7458
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007459 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007460 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007461 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007462 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7463 * of the heredoc */
7464 debug_printf_parse("set heredoc '%s'\n",
7465 redir->rd_filename);
7466 setup_heredoc(redir);
7467 continue;
7468 }
7469
7470 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007471 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007472 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007473 int mode;
7474
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007475 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007476 /*
7477 * Examples:
7478 * "cmd >" (no filename)
7479 * "cmd > <file" (2nd redirect starts too early)
7480 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007481 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007482 continue;
7483 }
7484 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007485 p = expand_string_to_string(redir->rd_filename,
7486 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007487 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007488 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007489 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007490 /* Error message from open_or_warn can be lost
7491 * if stderr has been redirected, but bash
7492 * and ash both lose it as well
7493 * (though zsh doesn't!)
7494 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007495 return 1;
7496 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007497 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007498 /* open() gave us precisely the fd we wanted.
7499 * This means that this fd was not busy
7500 * (not opened to anywhere).
7501 * Remember to close it on restore:
7502 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007503 *sqp = add_squirrel_closed(*sqp, newfd);
7504 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007505 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007506 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007507 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7508 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007509 }
7510
Denys Vlasenko657e9002017-07-30 23:34:04 +02007511 if (newfd == redir->rd_fd)
7512 continue;
7513
7514 /* if "N>FILE": move newfd to redir->rd_fd */
7515 /* if "N>&M": dup newfd to redir->rd_fd */
7516 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7517
7518 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7519 if (newfd == REDIRFD_CLOSE) {
7520 /* "N>&-" means "close me" */
7521 if (!closed) {
7522 /* ^^^ optimization: saving may already
7523 * have closed it. If not... */
7524 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007525 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007526 /* Sometimes we do another close on restore, getting EBADF.
7527 * Consider "echo 3>FILE 3>&-"
7528 * first redirect remembers "need to close 3",
7529 * and second redirect closes 3! Restore code then closes 3 again.
7530 */
7531 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007532 /* if newfd is a script fd or saved fd, simulate EBADF */
7533 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7534 //errno = EBADF;
7535 //bb_perror_msg_and_die("can't duplicate file descriptor");
7536 newfd = -1; /* same effect as code above */
7537 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007538 xdup2(newfd, redir->rd_fd);
7539 if (redir->rd_dup == REDIRFD_TO_FILE)
7540 /* "rd_fd > FILE" */
7541 close(newfd);
7542 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007543 }
7544 }
7545 return 0;
7546}
7547
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007548static char *find_in_path(const char *arg)
7549{
7550 char *ret = NULL;
7551 const char *PATH = get_local_var_value("PATH");
7552
7553 if (!PATH)
7554 return NULL;
7555
7556 while (1) {
7557 const char *end = strchrnul(PATH, ':');
7558 int sz = end - PATH; /* must be int! */
7559
7560 free(ret);
7561 if (sz != 0) {
7562 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7563 } else {
7564 /* We have xxx::yyyy in $PATH,
7565 * it means "use current dir" */
7566 ret = xstrdup(arg);
7567 }
7568 if (access(ret, F_OK) == 0)
7569 break;
7570
7571 if (*end == '\0') {
7572 free(ret);
7573 return NULL;
7574 }
7575 PATH = end + 1;
7576 }
7577
7578 return ret;
7579}
7580
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007581static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007582 const struct built_in_command *x,
7583 const struct built_in_command *end)
7584{
7585 while (x != end) {
7586 if (strcmp(name, x->b_cmd) != 0) {
7587 x++;
7588 continue;
7589 }
7590 debug_printf_exec("found builtin '%s'\n", name);
7591 return x;
7592 }
7593 return NULL;
7594}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007595static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007596{
7597 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7598}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007599static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007600{
7601 const struct built_in_command *x = find_builtin1(name);
7602 if (x)
7603 return x;
7604 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7605}
7606
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007607static void remove_nested_vars(void)
7608{
7609 struct variable *cur;
7610 struct variable **cur_pp;
7611
7612 cur_pp = &G.top_var;
7613 while ((cur = *cur_pp) != NULL) {
7614 if (cur->var_nest_level <= G.var_nest_level) {
7615 cur_pp = &cur->next;
7616 continue;
7617 }
7618 /* Unexport */
7619 if (cur->flg_export) {
7620 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7621 bb_unsetenv(cur->varstr);
7622 }
7623 /* Remove from global list */
7624 *cur_pp = cur->next;
7625 /* Free */
7626 if (!cur->max_len) {
7627 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7628 free(cur->varstr);
7629 }
7630 free(cur);
7631 }
7632}
7633
7634static void enter_var_nest_level(void)
7635{
7636 G.var_nest_level++;
7637 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7638
7639 /* Try: f() { echo -n .; f; }; f
7640 * struct variable::var_nest_level is uint16_t,
7641 * thus limiting recursion to < 2^16.
7642 * In any case, with 8 Mbyte stack SEGV happens
7643 * not too long after 2^16 recursions anyway.
7644 */
7645 if (G.var_nest_level > 0xff00)
7646 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7647}
7648
7649static void leave_var_nest_level(void)
7650{
7651 G.var_nest_level--;
7652 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7653 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7654 bb_error_msg_and_die("BUG: nesting underflow");
7655
7656 remove_nested_vars();
7657}
7658
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007659#if ENABLE_HUSH_FUNCTIONS
7660static struct function **find_function_slot(const char *name)
7661{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007662 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007663 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007664
7665 while ((funcp = *funcpp) != NULL) {
7666 if (strcmp(name, funcp->name) == 0) {
7667 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007668 break;
7669 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007670 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007671 }
7672 return funcpp;
7673}
7674
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007675static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007676{
7677 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007678 return funcp;
7679}
7680
7681/* Note: takes ownership on name ptr */
7682static struct function *new_function(char *name)
7683{
7684 struct function **funcpp = find_function_slot(name);
7685 struct function *funcp = *funcpp;
7686
7687 if (funcp != NULL) {
7688 struct command *cmd = funcp->parent_cmd;
7689 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7690 if (!cmd) {
7691 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7692 free(funcp->name);
7693 /* Note: if !funcp->body, do not free body_as_string!
7694 * This is a special case of "-F name body" function:
7695 * body_as_string was not malloced! */
7696 if (funcp->body) {
7697 free_pipe_list(funcp->body);
7698# if !BB_MMU
7699 free(funcp->body_as_string);
7700# endif
7701 }
7702 } else {
7703 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7704 cmd->argv[0] = funcp->name;
7705 cmd->group = funcp->body;
7706# if !BB_MMU
7707 cmd->group_as_string = funcp->body_as_string;
7708# endif
7709 }
7710 } else {
7711 debug_printf_exec("remembering new function '%s'\n", name);
7712 funcp = *funcpp = xzalloc(sizeof(*funcp));
7713 /*funcp->next = NULL;*/
7714 }
7715
7716 funcp->name = name;
7717 return funcp;
7718}
7719
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007720# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007721static void unset_func(const char *name)
7722{
7723 struct function **funcpp = find_function_slot(name);
7724 struct function *funcp = *funcpp;
7725
7726 if (funcp != NULL) {
7727 debug_printf_exec("freeing function '%s'\n", funcp->name);
7728 *funcpp = funcp->next;
7729 /* funcp is unlinked now, deleting it.
7730 * Note: if !funcp->body, the function was created by
7731 * "-F name body", do not free ->body_as_string
7732 * and ->name as they were not malloced. */
7733 if (funcp->body) {
7734 free_pipe_list(funcp->body);
7735 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007736# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007737 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007738# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007739 }
7740 free(funcp);
7741 }
7742}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007743# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007744
7745# if BB_MMU
7746#define exec_function(to_free, funcp, argv) \
7747 exec_function(funcp, argv)
7748# endif
7749static void exec_function(char ***to_free,
7750 const struct function *funcp,
7751 char **argv) NORETURN;
7752static void exec_function(char ***to_free,
7753 const struct function *funcp,
7754 char **argv)
7755{
7756# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007757 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007758
7759 argv[0] = G.global_argv[0];
7760 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007761 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007762
7763// Example when we are here: "cmd | func"
7764// func will run with saved-redirect fds open.
7765// $ f() { echo /proc/self/fd/*; }
7766// $ true | f
7767// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7768// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7769// Same in script:
7770// $ . ./SCRIPT
7771// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7772// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7773// They are CLOEXEC so external programs won't see them, but
7774// for "more correctness" we might want to close those extra fds here:
7775//? close_saved_fds_and_FILE_fds();
7776
Denys Vlasenko332e4112018-04-04 22:32:59 +02007777 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007778 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007779 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007780 IF_HUSH_LOCAL(G.func_nest_level++;)
7781
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007782 /* On MMU, funcp->body is always non-NULL */
7783 n = run_list(funcp->body);
7784 fflush_all();
7785 _exit(n);
7786# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007787//? close_saved_fds_and_FILE_fds();
7788
7789//TODO: check whether "true | func_with_return" works
7790
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007791 re_execute_shell(to_free,
7792 funcp->body_as_string,
7793 G.global_argv[0],
7794 argv + 1,
7795 NULL);
7796# endif
7797}
7798
7799static int run_function(const struct function *funcp, char **argv)
7800{
7801 int rc;
7802 save_arg_t sv;
7803 smallint sv_flg;
7804
7805 save_and_replace_G_args(&sv, argv);
7806
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007807 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007808 sv_flg = G_flag_return_in_progress;
7809 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007810
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007811 /* Make "local" variables properly shadow previous ones */
7812 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007813 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007814
7815 /* On MMU, funcp->body is always non-NULL */
7816# if !BB_MMU
7817 if (!funcp->body) {
7818 /* Function defined by -F */
7819 parse_and_run_string(funcp->body_as_string);
7820 rc = G.last_exitcode;
7821 } else
7822# endif
7823 {
7824 rc = run_list(funcp->body);
7825 }
7826
Denys Vlasenko332e4112018-04-04 22:32:59 +02007827 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007828 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007829
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007830 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007831
7832 restore_G_args(&sv, argv);
7833
7834 return rc;
7835}
7836#endif /* ENABLE_HUSH_FUNCTIONS */
7837
7838
7839#if BB_MMU
7840#define exec_builtin(to_free, x, argv) \
7841 exec_builtin(x, argv)
7842#else
7843#define exec_builtin(to_free, x, argv) \
7844 exec_builtin(to_free, argv)
7845#endif
7846static void exec_builtin(char ***to_free,
7847 const struct built_in_command *x,
7848 char **argv) NORETURN;
7849static void exec_builtin(char ***to_free,
7850 const struct built_in_command *x,
7851 char **argv)
7852{
7853#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007854 int rcode;
7855 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007856//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007857 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007858 fflush_all();
7859 _exit(rcode);
7860#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007861 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007862 /* On NOMMU, we must never block!
7863 * Example: { sleep 99 | read line; } & echo Ok
7864 */
7865 re_execute_shell(to_free,
7866 argv[0],
7867 G.global_argv[0],
7868 G.global_argv + 1,
7869 argv);
7870#endif
7871}
7872
7873
7874static void execvp_or_die(char **argv) NORETURN;
7875static void execvp_or_die(char **argv)
7876{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007877 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007878 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007879 /* Don't propagate SIG_IGN to the child */
7880 if (SPECIAL_JOBSTOP_SIGS != 0)
7881 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007882 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007883 e = 2;
7884 if (errno == EACCES) e = 126;
7885 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007886 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007887 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007888}
7889
7890#if ENABLE_HUSH_MODE_X
7891static void dump_cmd_in_x_mode(char **argv)
7892{
7893 if (G_x_mode && argv) {
7894 /* We want to output the line in one write op */
7895 char *buf, *p;
7896 int len;
7897 int n;
7898
7899 len = 3;
7900 n = 0;
7901 while (argv[n])
7902 len += strlen(argv[n++]) + 1;
7903 buf = xmalloc(len);
7904 buf[0] = '+';
7905 p = buf + 1;
7906 n = 0;
7907 while (argv[n])
7908 p += sprintf(p, " %s", argv[n++]);
7909 *p++ = '\n';
7910 *p = '\0';
7911 fputs(buf, stderr);
7912 free(buf);
7913 }
7914}
7915#else
7916# define dump_cmd_in_x_mode(argv) ((void)0)
7917#endif
7918
Denys Vlasenko57000292018-01-12 14:41:45 +01007919#if ENABLE_HUSH_COMMAND
7920static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7921{
7922 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007923
Denys Vlasenko57000292018-01-12 14:41:45 +01007924 if (!opt_vV)
7925 return;
7926
7927 to_free = NULL;
7928 if (!explanation) {
7929 char *path = getenv("PATH");
7930 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007931 if (!explanation)
7932 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007933 if (opt_vV != 'V')
7934 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7935 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007936 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007937 free(to_free);
7938 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007939 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007940}
7941#else
7942# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7943#endif
7944
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007945#if BB_MMU
7946#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7947 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7948#define pseudo_exec(nommu_save, command, argv_expanded) \
7949 pseudo_exec(command, argv_expanded)
7950#endif
7951
7952/* Called after [v]fork() in run_pipe, or from builtin_exec.
7953 * Never returns.
7954 * Don't exit() here. If you don't exec, use _exit instead.
7955 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007956 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007957 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007958static void pseudo_exec_argv(nommu_save_t *nommu_save,
7959 char **argv, int assignment_cnt,
7960 char **argv_expanded) NORETURN;
7961static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7962 char **argv, int assignment_cnt,
7963 char **argv_expanded)
7964{
Denys Vlasenko57000292018-01-12 14:41:45 +01007965 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007966 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007967 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007968 IF_HUSH_COMMAND(char opt_vV = 0;)
7969 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007970
7971 new_env = expand_assignments(argv, assignment_cnt);
7972 dump_cmd_in_x_mode(new_env);
7973
7974 if (!argv[assignment_cnt]) {
7975 /* Case when we are here: ... | var=val | ...
7976 * (note that we do not exit early, i.e., do not optimize out
7977 * expand_assignments(): think about ... | var=`sleep 1` | ...
7978 */
7979 free_strings(new_env);
7980 _exit(EXIT_SUCCESS);
7981 }
7982
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007983 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007984#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007985 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007986#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007987 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007988 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007989#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007990 set_vars_and_save_old(new_env);
7991 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007992
7993 if (argv_expanded) {
7994 argv = argv_expanded;
7995 } else {
7996 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7997#if !BB_MMU
7998 nommu_save->argv = argv;
7999#endif
8000 }
8001 dump_cmd_in_x_mode(argv);
8002
8003#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8004 if (strchr(argv[0], '/') != NULL)
8005 goto skip;
8006#endif
8007
Denys Vlasenko75481d32017-07-31 05:27:09 +02008008#if ENABLE_HUSH_FUNCTIONS
8009 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008010 funcp = find_function(argv[0]);
8011 if (funcp)
8012 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008013#endif
8014
Denys Vlasenko57000292018-01-12 14:41:45 +01008015#if ENABLE_HUSH_COMMAND
8016 /* "command BAR": run BAR without looking it up among functions
8017 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8018 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8019 */
8020 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8021 char *p;
8022
8023 argv++;
8024 p = *argv;
8025 if (p[0] != '-' || !p[1])
8026 continue; /* bash allows "command command command [-OPT] BAR" */
8027
8028 for (;;) {
8029 p++;
8030 switch (*p) {
8031 case '\0':
8032 argv++;
8033 p = *argv;
8034 if (p[0] != '-' || !p[1])
8035 goto after_opts;
8036 continue; /* next arg is also -opts, process it too */
8037 case 'v':
8038 case 'V':
8039 opt_vV = *p;
8040 continue;
8041 default:
8042 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8043 }
8044 }
8045 }
8046 after_opts:
8047# if ENABLE_HUSH_FUNCTIONS
8048 if (opt_vV && find_function(argv[0]))
8049 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8050# endif
8051#endif
8052
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008053 /* Check if the command matches any of the builtins.
8054 * Depending on context, this might be redundant. But it's
8055 * easier to waste a few CPU cycles than it is to figure out
8056 * if this is one of those cases.
8057 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008058 /* Why "BB_MMU ? :" difference in logic? -
8059 * On NOMMU, it is more expensive to re-execute shell
8060 * just in order to run echo or test builtin.
8061 * It's better to skip it here and run corresponding
8062 * non-builtin later. */
8063 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8064 if (x) {
8065 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8066 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008067 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008068
8069#if ENABLE_FEATURE_SH_STANDALONE
8070 /* Check if the command matches any busybox applets */
8071 {
8072 int a = find_applet_by_name(argv[0]);
8073 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008074 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008075# if BB_MMU /* see above why on NOMMU it is not allowed */
8076 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008077 /* Do not leak open fds from opened script files etc.
8078 * Testcase: interactive "ls -l /proc/self/fd"
8079 * should not show tty fd open.
8080 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008081 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008082//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008083//This casuses test failures in
8084//redir_children_should_not_see_saved_fd_2.tests
8085//redir_children_should_not_see_saved_fd_3.tests
8086//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008087 /* Without this, "rm -i FILE" can't be ^C'ed: */
8088 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008089 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008090 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008091 }
8092# endif
8093 /* Re-exec ourselves */
8094 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008095 /* Don't propagate SIG_IGN to the child */
8096 if (SPECIAL_JOBSTOP_SIGS != 0)
8097 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008098 execv(bb_busybox_exec_path, argv);
8099 /* If they called chroot or otherwise made the binary no longer
8100 * executable, fall through */
8101 }
8102 }
8103#endif
8104
8105#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8106 skip:
8107#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008108 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008109 execvp_or_die(argv);
8110}
8111
8112/* Called after [v]fork() in run_pipe
8113 */
8114static void pseudo_exec(nommu_save_t *nommu_save,
8115 struct command *command,
8116 char **argv_expanded) NORETURN;
8117static void pseudo_exec(nommu_save_t *nommu_save,
8118 struct command *command,
8119 char **argv_expanded)
8120{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008121#if ENABLE_HUSH_FUNCTIONS
8122 if (command->cmd_type == CMD_FUNCDEF) {
8123 /* Ignore funcdefs in pipes:
8124 * true | f() { cmd }
8125 */
8126 _exit(0);
8127 }
8128#endif
8129
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008130 if (command->argv) {
8131 pseudo_exec_argv(nommu_save, command->argv,
8132 command->assignment_cnt, argv_expanded);
8133 }
8134
8135 if (command->group) {
8136 /* Cases when we are here:
8137 * ( list )
8138 * { list } &
8139 * ... | ( list ) | ...
8140 * ... | { list } | ...
8141 */
8142#if BB_MMU
8143 int rcode;
8144 debug_printf_exec("pseudo_exec: run_list\n");
8145 reset_traps_to_defaults();
8146 rcode = run_list(command->group);
8147 /* OK to leak memory by not calling free_pipe_list,
8148 * since this process is about to exit */
8149 _exit(rcode);
8150#else
8151 re_execute_shell(&nommu_save->argv_from_re_execing,
8152 command->group_as_string,
8153 G.global_argv[0],
8154 G.global_argv + 1,
8155 NULL);
8156#endif
8157 }
8158
8159 /* Case when we are here: ... | >file */
8160 debug_printf_exec("pseudo_exec'ed null command\n");
8161 _exit(EXIT_SUCCESS);
8162}
8163
8164#if ENABLE_HUSH_JOB
8165static const char *get_cmdtext(struct pipe *pi)
8166{
8167 char **argv;
8168 char *p;
8169 int len;
8170
8171 /* This is subtle. ->cmdtext is created only on first backgrounding.
8172 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8173 * On subsequent bg argv is trashed, but we won't use it */
8174 if (pi->cmdtext)
8175 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008176
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008177 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008178 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008179 pi->cmdtext = xzalloc(1);
8180 return pi->cmdtext;
8181 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008182 len = 0;
8183 do {
8184 len += strlen(*argv) + 1;
8185 } while (*++argv);
8186 p = xmalloc(len);
8187 pi->cmdtext = p;
8188 argv = pi->cmds[0].argv;
8189 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008190 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008191 *p++ = ' ';
8192 } while (*++argv);
8193 p[-1] = '\0';
8194 return pi->cmdtext;
8195}
8196
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008197static void remove_job_from_table(struct pipe *pi)
8198{
8199 struct pipe *prev_pipe;
8200
8201 if (pi == G.job_list) {
8202 G.job_list = pi->next;
8203 } else {
8204 prev_pipe = G.job_list;
8205 while (prev_pipe->next != pi)
8206 prev_pipe = prev_pipe->next;
8207 prev_pipe->next = pi->next;
8208 }
8209 G.last_jobid = 0;
8210 if (G.job_list)
8211 G.last_jobid = G.job_list->jobid;
8212}
8213
8214static void delete_finished_job(struct pipe *pi)
8215{
8216 remove_job_from_table(pi);
8217 free_pipe(pi);
8218}
8219
8220static void clean_up_last_dead_job(void)
8221{
8222 if (G.job_list && !G.job_list->alive_cmds)
8223 delete_finished_job(G.job_list);
8224}
8225
Denys Vlasenko16096292017-07-10 10:00:28 +02008226static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008227{
8228 struct pipe *job, **jobp;
8229 int i;
8230
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008231 clean_up_last_dead_job();
8232
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008233 /* Find the end of the list, and find next job ID to use */
8234 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008235 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008236 while ((job = *jobp) != NULL) {
8237 if (job->jobid > i)
8238 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008239 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008240 }
8241 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008242
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008243 /* Create a new job struct at the end */
8244 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008245 job->next = NULL;
8246 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8247 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8248 for (i = 0; i < pi->num_cmds; i++) {
8249 job->cmds[i].pid = pi->cmds[i].pid;
8250 /* all other fields are not used and stay zero */
8251 }
8252 job->cmdtext = xstrdup(get_cmdtext(pi));
8253
8254 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008255 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008256 G.last_jobid = job->jobid;
8257}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008258#endif /* JOB */
8259
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008260static int job_exited_or_stopped(struct pipe *pi)
8261{
8262 int rcode, i;
8263
8264 if (pi->alive_cmds != pi->stopped_cmds)
8265 return -1;
8266
8267 /* All processes in fg pipe have exited or stopped */
8268 rcode = 0;
8269 i = pi->num_cmds;
8270 while (--i >= 0) {
8271 rcode = pi->cmds[i].cmd_exitcode;
8272 /* usually last process gives overall exitstatus,
8273 * but with "set -o pipefail", last *failed* process does */
8274 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8275 break;
8276 }
8277 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8278 return rcode;
8279}
8280
Denys Vlasenko7e675362016-10-28 21:57:31 +02008281static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008282{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008283#if ENABLE_HUSH_JOB
8284 struct pipe *pi;
8285#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008286 int i, dead;
8287
8288 dead = WIFEXITED(status) || WIFSIGNALED(status);
8289
8290#if DEBUG_JOBS
8291 if (WIFSTOPPED(status))
8292 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8293 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8294 if (WIFSIGNALED(status))
8295 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8296 childpid, WTERMSIG(status), WEXITSTATUS(status));
8297 if (WIFEXITED(status))
8298 debug_printf_jobs("pid %d exited, exitcode %d\n",
8299 childpid, WEXITSTATUS(status));
8300#endif
8301 /* Were we asked to wait for a fg pipe? */
8302 if (fg_pipe) {
8303 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008304
Denys Vlasenko7e675362016-10-28 21:57:31 +02008305 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008306 int rcode;
8307
Denys Vlasenko7e675362016-10-28 21:57:31 +02008308 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8309 if (fg_pipe->cmds[i].pid != childpid)
8310 continue;
8311 if (dead) {
8312 int ex;
8313 fg_pipe->cmds[i].pid = 0;
8314 fg_pipe->alive_cmds--;
8315 ex = WEXITSTATUS(status);
8316 /* bash prints killer signal's name for *last*
8317 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8318 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8319 */
8320 if (WIFSIGNALED(status)) {
8321 int sig = WTERMSIG(status);
8322 if (i == fg_pipe->num_cmds-1)
8323 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8324 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8325 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8326 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8327 * Maybe we need to use sig | 128? */
8328 ex = sig + 128;
8329 }
8330 fg_pipe->cmds[i].cmd_exitcode = ex;
8331 } else {
8332 fg_pipe->stopped_cmds++;
8333 }
8334 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8335 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008336 rcode = job_exited_or_stopped(fg_pipe);
8337 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008338/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8339 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8340 * and "killall -STOP cat" */
8341 if (G_interactive_fd) {
8342#if ENABLE_HUSH_JOB
8343 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008344 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008345#endif
8346 return rcode;
8347 }
8348 if (fg_pipe->alive_cmds == 0)
8349 return rcode;
8350 }
8351 /* There are still running processes in the fg_pipe */
8352 return -1;
8353 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008354 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008355 }
8356
8357#if ENABLE_HUSH_JOB
8358 /* We were asked to wait for bg or orphaned children */
8359 /* No need to remember exitcode in this case */
8360 for (pi = G.job_list; pi; pi = pi->next) {
8361 for (i = 0; i < pi->num_cmds; i++) {
8362 if (pi->cmds[i].pid == childpid)
8363 goto found_pi_and_prognum;
8364 }
8365 }
8366 /* Happens when shell is used as init process (init=/bin/sh) */
8367 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8368 return -1; /* this wasn't a process from fg_pipe */
8369
8370 found_pi_and_prognum:
8371 if (dead) {
8372 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008373 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008374 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008375 rcode = 128 + WTERMSIG(status);
8376 pi->cmds[i].cmd_exitcode = rcode;
8377 if (G.last_bg_pid == pi->cmds[i].pid)
8378 G.last_bg_pid_exitcode = rcode;
8379 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008380 pi->alive_cmds--;
8381 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008382 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008383 printf(JOB_STATUS_FORMAT, pi->jobid,
8384 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008385 delete_finished_job(pi);
8386 } else {
8387/*
8388 * bash deletes finished jobs from job table only in interactive mode,
8389 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8390 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8391 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8392 * We only retain one "dead" job, if it's the single job on the list.
8393 * This covers most of real-world scenarios where this is useful.
8394 */
8395 if (pi != G.job_list)
8396 delete_finished_job(pi);
8397 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008398 }
8399 } else {
8400 /* child stopped */
8401 pi->stopped_cmds++;
8402 }
8403#endif
8404 return -1; /* this wasn't a process from fg_pipe */
8405}
8406
8407/* Check to see if any processes have exited -- if they have,
8408 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008409 *
8410 * If non-NULL fg_pipe: wait for its completion or stop.
8411 * Return its exitcode or zero if stopped.
8412 *
8413 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8414 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8415 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8416 * or 0 if no children changed status.
8417 *
8418 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8419 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8420 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008421 */
8422static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8423{
8424 int attributes;
8425 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008426 int rcode = 0;
8427
8428 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8429
8430 attributes = WUNTRACED;
8431 if (fg_pipe == NULL)
8432 attributes |= WNOHANG;
8433
8434 errno = 0;
8435#if ENABLE_HUSH_FAST
8436 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8437//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8438//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8439 /* There was neither fork nor SIGCHLD since last waitpid */
8440 /* Avoid doing waitpid syscall if possible */
8441 if (!G.we_have_children) {
8442 errno = ECHILD;
8443 return -1;
8444 }
8445 if (fg_pipe == NULL) { /* is WNOHANG set? */
8446 /* We have children, but they did not exit
8447 * or stop yet (we saw no SIGCHLD) */
8448 return 0;
8449 }
8450 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8451 }
8452#endif
8453
8454/* Do we do this right?
8455 * bash-3.00# sleep 20 | false
8456 * <ctrl-Z pressed>
8457 * [3]+ Stopped sleep 20 | false
8458 * bash-3.00# echo $?
8459 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8460 * [hush 1.14.0: yes we do it right]
8461 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008462 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008463 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008464#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008465 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008466 i = G.count_SIGCHLD;
8467#endif
8468 childpid = waitpid(-1, &status, attributes);
8469 if (childpid <= 0) {
8470 if (childpid && errno != ECHILD)
8471 bb_perror_msg("waitpid");
8472#if ENABLE_HUSH_FAST
8473 else { /* Until next SIGCHLD, waitpid's are useless */
8474 G.we_have_children = (childpid == 0);
8475 G.handled_SIGCHLD = i;
8476//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8477 }
8478#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008479 /* ECHILD (no children), or 0 (no change in children status) */
8480 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008481 break;
8482 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008483 rcode = process_wait_result(fg_pipe, childpid, status);
8484 if (rcode >= 0) {
8485 /* fg_pipe exited or stopped */
8486 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008487 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008488 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008489 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008490 rcode = WEXITSTATUS(status);
8491 if (WIFSIGNALED(status))
8492 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008493 if (WIFSTOPPED(status))
8494 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8495 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008496 rcode++;
8497 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008498 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008499 /* This wasn't one of our processes, or */
8500 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008501 } /* while (waitpid succeeds)... */
8502
8503 return rcode;
8504}
8505
8506#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008507static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008508{
8509 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008510 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008511 if (G_saved_tty_pgrp) {
8512 /* Job finished, move the shell to the foreground */
8513 p = getpgrp(); /* our process group id */
8514 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8515 tcsetpgrp(G_interactive_fd, p);
8516 }
8517 return rcode;
8518}
8519#endif
8520
8521/* Start all the jobs, but don't wait for anything to finish.
8522 * See checkjobs().
8523 *
8524 * Return code is normally -1, when the caller has to wait for children
8525 * to finish to determine the exit status of the pipe. If the pipe
8526 * is a simple builtin command, however, the action is done by the
8527 * time run_pipe returns, and the exit code is provided as the
8528 * return value.
8529 *
8530 * Returns -1 only if started some children. IOW: we have to
8531 * mask out retvals of builtins etc with 0xff!
8532 *
8533 * The only case when we do not need to [v]fork is when the pipe
8534 * is single, non-backgrounded, non-subshell command. Examples:
8535 * cmd ; ... { list } ; ...
8536 * cmd && ... { list } && ...
8537 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008538 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008539 * or (if SH_STANDALONE) an applet, and we can run the { list }
8540 * with run_list. If it isn't one of these, we fork and exec cmd.
8541 *
8542 * Cases when we must fork:
8543 * non-single: cmd | cmd
8544 * backgrounded: cmd & { list } &
8545 * subshell: ( list ) [&]
8546 */
8547#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008548#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8549 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008550#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008551static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008552 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008553 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008554 char **argv_expanded)
8555{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008556 /* Assignments occur before redirects. Try:
8557 * a=`sleep 1` sleep 2 3>/qwe/rty
8558 */
8559
8560 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8561 dump_cmd_in_x_mode(new_env);
8562 dump_cmd_in_x_mode(argv_expanded);
8563 /* this takes ownership of new_env[i] elements, and frees new_env: */
8564 set_vars_and_save_old(new_env);
8565
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008566 /* setup_redirects acts on file descriptors, not FILEs.
8567 * This is perfect for work that comes after exec().
8568 * Is it really safe for inline use? Experimentally,
8569 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008570 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008571}
8572static NOINLINE int run_pipe(struct pipe *pi)
8573{
8574 static const char *const null_ptr = NULL;
8575
8576 int cmd_no;
8577 int next_infd;
8578 struct command *command;
8579 char **argv_expanded;
8580 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008581 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008582 int rcode;
8583
8584 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8585 debug_enter();
8586
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008587 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8588 * Result should be 3 lines: q w e, qwe, q w e
8589 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008590 if (G.ifs_whitespace != G.ifs)
8591 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008592 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008593 if (G.ifs) {
8594 char *p;
8595 G.ifs_whitespace = (char*)G.ifs;
8596 p = skip_whitespace(G.ifs);
8597 if (*p) {
8598 /* Not all $IFS is whitespace */
8599 char *d;
8600 int len = p - G.ifs;
8601 p = skip_non_whitespace(p);
8602 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8603 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8604 while (*p) {
8605 if (isspace(*p))
8606 *d++ = *p;
8607 p++;
8608 }
8609 *d = '\0';
8610 }
8611 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008612 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008613 G.ifs_whitespace = (char*)G.ifs;
8614 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008615
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008616 IF_HUSH_JOB(pi->pgrp = -1;)
8617 pi->stopped_cmds = 0;
8618 command = &pi->cmds[0];
8619 argv_expanded = NULL;
8620
8621 if (pi->num_cmds != 1
8622 || pi->followup == PIPE_BG
8623 || command->cmd_type == CMD_SUBSHELL
8624 ) {
8625 goto must_fork;
8626 }
8627
8628 pi->alive_cmds = 1;
8629
8630 debug_printf_exec(": group:%p argv:'%s'\n",
8631 command->group, command->argv ? command->argv[0] : "NONE");
8632
8633 if (command->group) {
8634#if ENABLE_HUSH_FUNCTIONS
8635 if (command->cmd_type == CMD_FUNCDEF) {
8636 /* "executing" func () { list } */
8637 struct function *funcp;
8638
8639 funcp = new_function(command->argv[0]);
8640 /* funcp->name is already set to argv[0] */
8641 funcp->body = command->group;
8642# if !BB_MMU
8643 funcp->body_as_string = command->group_as_string;
8644 command->group_as_string = NULL;
8645# endif
8646 command->group = NULL;
8647 command->argv[0] = NULL;
8648 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8649 funcp->parent_cmd = command;
8650 command->child_func = funcp;
8651
8652 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8653 debug_leave();
8654 return EXIT_SUCCESS;
8655 }
8656#endif
8657 /* { list } */
8658 debug_printf("non-subshell group\n");
8659 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008660 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008661 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008662//FIXME: we need to pass squirrel down into run_list()
8663//for SH_STANDALONE case, or else this construct:
8664// { find /proc/self/fd; true; } >FILE; cmd2
8665//has no way of closing saved fd#1 for "find",
8666//and in SH_STANDALONE mode, "find" is not execed,
8667//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008668 rcode = run_list(command->group) & 0xff;
8669 }
8670 restore_redirects(squirrel);
8671 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8672 debug_leave();
8673 debug_printf_exec("run_pipe: return %d\n", rcode);
8674 return rcode;
8675 }
8676
8677 argv = command->argv ? command->argv : (char **) &null_ptr;
8678 {
8679 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008680 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8681 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008682 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008683 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008684
Denys Vlasenko5807e182018-02-08 19:19:04 +01008685#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008686 if (G.lineno_var)
8687 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8688#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008689
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008690 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008691 /* Assignments, but no command.
8692 * Ensure redirects take effect (that is, create files).
8693 * Try "a=t >file"
8694 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008695 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008696 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008697 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008698 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008699 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008700
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008701 /* Set shell variables */
8702 if (G_x_mode)
8703 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008704 i = 0;
8705 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008706 char *p = expand_string_to_string(argv[i],
8707 EXP_FLAG_ESC_GLOB_CHARS,
8708 /*unbackslash:*/ 1
8709 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008710 if (G_x_mode)
8711 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008712 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008713 if (set_local_var(p, /*flag:*/ 0)) {
8714 /* assignment to readonly var / putenv error? */
8715 rcode = 1;
8716 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008717 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008718 }
8719 if (G_x_mode)
8720 bb_putchar_stderr('\n');
8721 /* Redirect error sets $? to 1. Otherwise,
8722 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008723 * Else, clear $?:
8724 * false; q=`exit 2`; echo $? - should print 2
8725 * false; x=1; echo $? - should print 0
8726 * Because of the 2nd case, we can't just use G.last_exitcode.
8727 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008728 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008729 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008730 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8731 debug_leave();
8732 debug_printf_exec("run_pipe: return %d\n", rcode);
8733 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008734 }
8735
8736 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008737#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008738 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008739 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008740 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008741#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008742 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008743
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008744 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008745 if (!argv_expanded[0]) {
8746 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008747 /* `false` still has to set exitcode 1 */
8748 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008749 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008750 }
8751
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008752 old_vars = NULL;
8753 sv_shadowed = G.shadowed_vars_pp;
8754
Denys Vlasenko75481d32017-07-31 05:27:09 +02008755 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008756 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8757 IF_HUSH_FUNCTIONS(x = NULL;)
8758 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008759 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008760 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008761 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8762 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008763 /*
8764 * Variable assignments are executed, but then "forgotten":
8765 * a=`sleep 1;echo A` exec 3>&-; echo $a
8766 * sleeps, but prints nothing.
8767 */
8768 enter_var_nest_level();
8769 G.shadowed_vars_pp = &old_vars;
8770 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8771 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008772 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008773
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008774 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008775 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008776
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008777 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008778 * a=b true; env | grep ^a=
8779 */
8780 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008781 /* Collect all variables "shadowed" by helper
8782 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8783 * into old_vars list:
8784 */
8785 G.shadowed_vars_pp = &old_vars;
8786 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008787 if (rcode == 0) {
8788 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008789 /* Do not collect *to old_vars list* vars shadowed
8790 * by e.g. "local VAR" builtin (collect them
8791 * in the previously nested list instead):
8792 * don't want them to be restored immediately
8793 * after "local" completes.
8794 */
8795 G.shadowed_vars_pp = sv_shadowed;
8796
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008797 debug_printf_exec(": builtin '%s' '%s'...\n",
8798 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008799 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008800 rcode = x->b_function(argv_expanded) & 0xff;
8801 fflush_all();
8802 }
8803#if ENABLE_HUSH_FUNCTIONS
8804 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008805 debug_printf_exec(": function '%s' '%s'...\n",
8806 funcp->name, argv_expanded[1]);
8807 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008808 /*
8809 * But do collect *to old_vars list* vars shadowed
8810 * within function execution. To that end, restore
8811 * this pointer _after_ function run:
8812 */
8813 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008814 }
8815#endif
8816 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008817 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008818 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008819 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008820 if (n < 0 || !APPLET_IS_NOFORK(n))
8821 goto must_fork;
8822
8823 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008824 /* Collect all variables "shadowed" by helper into old_vars list */
8825 G.shadowed_vars_pp = &old_vars;
8826 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8827 G.shadowed_vars_pp = sv_shadowed;
8828
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008829 if (rcode == 0) {
8830 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8831 argv_expanded[0], argv_expanded[1]);
8832 /*
8833 * Note: signals (^C) can't interrupt here.
8834 * We remember them and they will be acted upon
8835 * after applet returns.
8836 * This makes applets which can run for a long time
8837 * and/or wait for user input ineligible for NOFORK:
8838 * for example, "yes" or "rm" (rm -i waits for input).
8839 */
8840 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008841 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008842 } else
8843 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008844
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008845 restore_redirects(squirrel);
8846 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008847 leave_var_nest_level();
8848 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008849
8850 /*
8851 * Try "usleep 99999999" + ^C + "echo $?"
8852 * with FEATURE_SH_NOFORK=y.
8853 */
8854 if (!funcp) {
8855 /* It was builtin or nofork.
8856 * if this would be a real fork/execed program,
8857 * it should have died if a fatal sig was received.
8858 * But OTOH, there was no separate process,
8859 * the sig was sent to _shell_, not to non-existing
8860 * child.
8861 * Let's just handle ^C only, this one is obvious:
8862 * we aren't ok with exitcode 0 when ^C was pressed
8863 * during builtin/nofork.
8864 */
8865 if (sigismember(&G.pending_set, SIGINT))
8866 rcode = 128 + SIGINT;
8867 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008868 free(argv_expanded);
8869 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8870 debug_leave();
8871 debug_printf_exec("run_pipe return %d\n", rcode);
8872 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008873 }
8874
8875 must_fork:
8876 /* NB: argv_expanded may already be created, and that
8877 * might include `cmd` runs! Do not rerun it! We *must*
8878 * use argv_expanded if it's non-NULL */
8879
8880 /* Going to fork a child per each pipe member */
8881 pi->alive_cmds = 0;
8882 next_infd = 0;
8883
8884 cmd_no = 0;
8885 while (cmd_no < pi->num_cmds) {
8886 struct fd_pair pipefds;
8887#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008888 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008889 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008890 nommu_save.old_vars = NULL;
8891 nommu_save.argv = NULL;
8892 nommu_save.argv_from_re_execing = NULL;
8893#endif
8894 command = &pi->cmds[cmd_no];
8895 cmd_no++;
8896 if (command->argv) {
8897 debug_printf_exec(": pipe member '%s' '%s'...\n",
8898 command->argv[0], command->argv[1]);
8899 } else {
8900 debug_printf_exec(": pipe member with no argv\n");
8901 }
8902
8903 /* pipes are inserted between pairs of commands */
8904 pipefds.rd = 0;
8905 pipefds.wr = 1;
8906 if (cmd_no < pi->num_cmds)
8907 xpiped_pair(pipefds);
8908
Denys Vlasenko5807e182018-02-08 19:19:04 +01008909#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008910 if (G.lineno_var)
8911 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8912#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008913
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008914 command->pid = BB_MMU ? fork() : vfork();
8915 if (!command->pid) { /* child */
8916#if ENABLE_HUSH_JOB
8917 disable_restore_tty_pgrp_on_exit();
8918 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8919
8920 /* Every child adds itself to new process group
8921 * with pgid == pid_of_first_child_in_pipe */
8922 if (G.run_list_level == 1 && G_interactive_fd) {
8923 pid_t pgrp;
8924 pgrp = pi->pgrp;
8925 if (pgrp < 0) /* true for 1st process only */
8926 pgrp = getpid();
8927 if (setpgid(0, pgrp) == 0
8928 && pi->followup != PIPE_BG
8929 && G_saved_tty_pgrp /* we have ctty */
8930 ) {
8931 /* We do it in *every* child, not just first,
8932 * to avoid races */
8933 tcsetpgrp(G_interactive_fd, pgrp);
8934 }
8935 }
8936#endif
8937 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8938 /* 1st cmd in backgrounded pipe
8939 * should have its stdin /dev/null'ed */
8940 close(0);
8941 if (open(bb_dev_null, O_RDONLY))
8942 xopen("/", O_RDONLY);
8943 } else {
8944 xmove_fd(next_infd, 0);
8945 }
8946 xmove_fd(pipefds.wr, 1);
8947 if (pipefds.rd > 1)
8948 close(pipefds.rd);
8949 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008950 * and the pipe fd (fd#1) is available for dup'ing:
8951 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8952 * of cmd1 goes into pipe.
8953 */
8954 if (setup_redirects(command, NULL)) {
8955 /* Happens when redir file can't be opened:
8956 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8957 * FOO
8958 * hush: can't open '/qwe/rty': No such file or directory
8959 * BAZ
8960 * (echo BAR is not executed, it hits _exit(1) below)
8961 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008962 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008963 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008964
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008965 /* Stores to nommu_save list of env vars putenv'ed
8966 * (NOMMU, on MMU we don't need that) */
8967 /* cast away volatility... */
8968 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8969 /* pseudo_exec() does not return */
8970 }
8971
8972 /* parent or error */
8973#if ENABLE_HUSH_FAST
8974 G.count_SIGCHLD++;
8975//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8976#endif
8977 enable_restore_tty_pgrp_on_exit();
8978#if !BB_MMU
8979 /* Clean up after vforked child */
8980 free(nommu_save.argv);
8981 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008982 G.var_nest_level = sv_var_nest_level;
8983 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008984 add_vars(nommu_save.old_vars);
8985#endif
8986 free(argv_expanded);
8987 argv_expanded = NULL;
8988 if (command->pid < 0) { /* [v]fork failed */
8989 /* Clearly indicate, was it fork or vfork */
8990 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8991 } else {
8992 pi->alive_cmds++;
8993#if ENABLE_HUSH_JOB
8994 /* Second and next children need to know pid of first one */
8995 if (pi->pgrp < 0)
8996 pi->pgrp = command->pid;
8997#endif
8998 }
8999
9000 if (cmd_no > 1)
9001 close(next_infd);
9002 if (cmd_no < pi->num_cmds)
9003 close(pipefds.wr);
9004 /* Pass read (output) pipe end to next iteration */
9005 next_infd = pipefds.rd;
9006 }
9007
9008 if (!pi->alive_cmds) {
9009 debug_leave();
9010 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9011 return 1;
9012 }
9013
9014 debug_leave();
9015 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9016 return -1;
9017}
9018
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009019/* NB: called by pseudo_exec, and therefore must not modify any
9020 * global data until exec/_exit (we can be a child after vfork!) */
9021static int run_list(struct pipe *pi)
9022{
9023#if ENABLE_HUSH_CASE
9024 char *case_word = NULL;
9025#endif
9026#if ENABLE_HUSH_LOOPS
9027 struct pipe *loop_top = NULL;
9028 char **for_lcur = NULL;
9029 char **for_list = NULL;
9030#endif
9031 smallint last_followup;
9032 smalluint rcode;
9033#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9034 smalluint cond_code = 0;
9035#else
9036 enum { cond_code = 0 };
9037#endif
9038#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009039 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009040 smallint last_rword; /* ditto */
9041#endif
9042
9043 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9044 debug_enter();
9045
9046#if ENABLE_HUSH_LOOPS
9047 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009048 {
9049 struct pipe *cpipe;
9050 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9051 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9052 continue;
9053 /* current word is FOR or IN (BOLD in comments below) */
9054 if (cpipe->next == NULL) {
9055 syntax_error("malformed for");
9056 debug_leave();
9057 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9058 return 1;
9059 }
9060 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9061 if (cpipe->next->res_word == RES_DO)
9062 continue;
9063 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9064 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9065 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9066 ) {
9067 syntax_error("malformed for");
9068 debug_leave();
9069 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9070 return 1;
9071 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009072 }
9073 }
9074#endif
9075
9076 /* Past this point, all code paths should jump to ret: label
9077 * in order to return, no direct "return" statements please.
9078 * This helps to ensure that no memory is leaked. */
9079
9080#if ENABLE_HUSH_JOB
9081 G.run_list_level++;
9082#endif
9083
9084#if HAS_KEYWORDS
9085 rword = RES_NONE;
9086 last_rword = RES_XXXX;
9087#endif
9088 last_followup = PIPE_SEQ;
9089 rcode = G.last_exitcode;
9090
9091 /* Go through list of pipes, (maybe) executing them. */
9092 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009093 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009094 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009095
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009096 if (G.flag_SIGINT)
9097 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009098 if (G_flag_return_in_progress == 1)
9099 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009100
9101 IF_HAS_KEYWORDS(rword = pi->res_word;)
9102 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9103 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009104
9105 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009106 if (
9107#if ENABLE_HUSH_IF
9108 rword == RES_IF || rword == RES_ELIF ||
9109#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009110 pi->followup != PIPE_SEQ
9111 ) {
9112 G.errexit_depth++;
9113 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009114#if ENABLE_HUSH_LOOPS
9115 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9116 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9117 ) {
9118 /* start of a loop: remember where loop starts */
9119 loop_top = pi;
9120 G.depth_of_loop++;
9121 }
9122#endif
9123 /* Still in the same "if...", "then..." or "do..." branch? */
9124 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9125 if ((rcode == 0 && last_followup == PIPE_OR)
9126 || (rcode != 0 && last_followup == PIPE_AND)
9127 ) {
9128 /* It is "<true> || CMD" or "<false> && CMD"
9129 * and we should not execute CMD */
9130 debug_printf_exec("skipped cmd because of || or &&\n");
9131 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009132 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009133 }
9134 }
9135 last_followup = pi->followup;
9136 IF_HAS_KEYWORDS(last_rword = rword;)
9137#if ENABLE_HUSH_IF
9138 if (cond_code) {
9139 if (rword == RES_THEN) {
9140 /* if false; then ... fi has exitcode 0! */
9141 G.last_exitcode = rcode = EXIT_SUCCESS;
9142 /* "if <false> THEN cmd": skip cmd */
9143 continue;
9144 }
9145 } else {
9146 if (rword == RES_ELSE || rword == RES_ELIF) {
9147 /* "if <true> then ... ELSE/ELIF cmd":
9148 * skip cmd and all following ones */
9149 break;
9150 }
9151 }
9152#endif
9153#if ENABLE_HUSH_LOOPS
9154 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9155 if (!for_lcur) {
9156 /* first loop through for */
9157
9158 static const char encoded_dollar_at[] ALIGN1 = {
9159 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9160 }; /* encoded representation of "$@" */
9161 static const char *const encoded_dollar_at_argv[] = {
9162 encoded_dollar_at, NULL
9163 }; /* argv list with one element: "$@" */
9164 char **vals;
9165
9166 vals = (char**)encoded_dollar_at_argv;
9167 if (pi->next->res_word == RES_IN) {
9168 /* if no variable values after "in" we skip "for" */
9169 if (!pi->next->cmds[0].argv) {
9170 G.last_exitcode = rcode = EXIT_SUCCESS;
9171 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9172 break;
9173 }
9174 vals = pi->next->cmds[0].argv;
9175 } /* else: "for var; do..." -> assume "$@" list */
9176 /* create list of variable values */
9177 debug_print_strings("for_list made from", vals);
9178 for_list = expand_strvec_to_strvec(vals);
9179 for_lcur = for_list;
9180 debug_print_strings("for_list", for_list);
9181 }
9182 if (!*for_lcur) {
9183 /* "for" loop is over, clean up */
9184 free(for_list);
9185 for_list = NULL;
9186 for_lcur = NULL;
9187 break;
9188 }
9189 /* Insert next value from for_lcur */
9190 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009191 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009192 continue;
9193 }
9194 if (rword == RES_IN) {
9195 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9196 }
9197 if (rword == RES_DONE) {
9198 continue; /* "done" has no cmds too */
9199 }
9200#endif
9201#if ENABLE_HUSH_CASE
9202 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009203 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009204 case_word = expand_string_to_string(pi->cmds->argv[0],
9205 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009206 debug_printf_exec("CASE word1:'%s'\n", case_word);
9207 //unbackslash(case_word);
9208 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009209 continue;
9210 }
9211 if (rword == RES_MATCH) {
9212 char **argv;
9213
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009214 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009215 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9216 break;
9217 /* all prev words didn't match, does this one match? */
9218 argv = pi->cmds->argv;
9219 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009220 char *pattern;
9221 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9222 pattern = expand_string_to_string(*argv,
9223 EXP_FLAG_ESC_GLOB_CHARS,
9224 /*unbackslash:*/ 0
9225 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009226 /* TODO: which FNM_xxx flags to use? */
9227 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009228 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9229 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009230 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009231 if (cond_code == 0) {
9232 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009233 free(case_word);
9234 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009235 break;
9236 }
9237 argv++;
9238 }
9239 continue;
9240 }
9241 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009242 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009243 if (cond_code != 0)
9244 continue; /* not matched yet, skip this pipe */
9245 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009246 if (rword == RES_ESAC) {
9247 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9248 if (case_word) {
9249 /* "case" did not match anything: still set $? (to 0) */
9250 G.last_exitcode = rcode = EXIT_SUCCESS;
9251 }
9252 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009253#endif
9254 /* Just pressing <enter> in shell should check for jobs.
9255 * OTOH, in non-interactive shell this is useless
9256 * and only leads to extra job checks */
9257 if (pi->num_cmds == 0) {
9258 if (G_interactive_fd)
9259 goto check_jobs_and_continue;
9260 continue;
9261 }
9262
9263 /* After analyzing all keywords and conditions, we decided
9264 * to execute this pipe. NB: have to do checkjobs(NULL)
9265 * after run_pipe to collect any background children,
9266 * even if list execution is to be stopped. */
9267 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009268#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009269 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009270#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009271 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9272 if (r != -1) {
9273 /* We ran a builtin, function, or group.
9274 * rcode is already known
9275 * and we don't need to wait for anything. */
9276 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9277 G.last_exitcode = rcode;
9278 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009279#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009280 /* Was it "break" or "continue"? */
9281 if (G.flag_break_continue) {
9282 smallint fbc = G.flag_break_continue;
9283 /* We might fall into outer *loop*,
9284 * don't want to break it too */
9285 if (loop_top) {
9286 G.depth_break_continue--;
9287 if (G.depth_break_continue == 0)
9288 G.flag_break_continue = 0;
9289 /* else: e.g. "continue 2" should *break* once, *then* continue */
9290 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9291 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009292 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009293 break;
9294 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009295 /* "continue": simulate end of loop */
9296 rword = RES_DONE;
9297 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009298 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009299#endif
9300 if (G_flag_return_in_progress == 1) {
9301 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9302 break;
9303 }
9304 } else if (pi->followup == PIPE_BG) {
9305 /* What does bash do with attempts to background builtins? */
9306 /* even bash 3.2 doesn't do that well with nested bg:
9307 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9308 * I'm NOT treating inner &'s as jobs */
9309#if ENABLE_HUSH_JOB
9310 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009311 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009312#endif
9313 /* Last command's pid goes to $! */
9314 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009315 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009316 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009317/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009318 rcode = EXIT_SUCCESS;
9319 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009320 } else {
9321#if ENABLE_HUSH_JOB
9322 if (G.run_list_level == 1 && G_interactive_fd) {
9323 /* Waits for completion, then fg's main shell */
9324 rcode = checkjobs_and_fg_shell(pi);
9325 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009326 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009327 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009328#endif
9329 /* This one just waits for completion */
9330 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9331 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9332 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009333 G.last_exitcode = rcode;
9334 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009335 }
9336
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009337 /* Handle "set -e" */
9338 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9339 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9340 if (G.errexit_depth == 0)
9341 hush_exit(rcode);
9342 }
9343 G.errexit_depth = sv_errexit_depth;
9344
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009345 /* Analyze how result affects subsequent commands */
9346#if ENABLE_HUSH_IF
9347 if (rword == RES_IF || rword == RES_ELIF)
9348 cond_code = rcode;
9349#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009350 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009351 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009352 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009353#if ENABLE_HUSH_LOOPS
9354 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009355 if (pi->next
9356 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009357 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009358 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009359 if (rword == RES_WHILE) {
9360 if (rcode) {
9361 /* "while false; do...done" - exitcode 0 */
9362 G.last_exitcode = rcode = EXIT_SUCCESS;
9363 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009364 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009365 }
9366 }
9367 if (rword == RES_UNTIL) {
9368 if (!rcode) {
9369 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009370 break;
9371 }
9372 }
9373 }
9374#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009375 } /* for (pi) */
9376
9377#if ENABLE_HUSH_JOB
9378 G.run_list_level--;
9379#endif
9380#if ENABLE_HUSH_LOOPS
9381 if (loop_top)
9382 G.depth_of_loop--;
9383 free(for_list);
9384#endif
9385#if ENABLE_HUSH_CASE
9386 free(case_word);
9387#endif
9388 debug_leave();
9389 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9390 return rcode;
9391}
9392
9393/* Select which version we will use */
9394static int run_and_free_list(struct pipe *pi)
9395{
9396 int rcode = 0;
9397 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009398 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009399 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9400 rcode = run_list(pi);
9401 }
9402 /* free_pipe_list has the side effect of clearing memory.
9403 * In the long run that function can be merged with run_list,
9404 * but doing that now would hobble the debugging effort. */
9405 free_pipe_list(pi);
9406 debug_printf_exec("run_and_free_list return %d\n", rcode);
9407 return rcode;
9408}
9409
9410
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009411static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009412{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009413 sighandler_t old_handler;
9414 unsigned sig = 0;
9415 while ((mask >>= 1) != 0) {
9416 sig++;
9417 if (!(mask & 1))
9418 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009419 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009420 /* POSIX allows shell to re-enable SIGCHLD
9421 * even if it was SIG_IGN on entry.
9422 * Therefore we skip IGN check for it:
9423 */
9424 if (sig == SIGCHLD)
9425 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009426 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9427 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9428 */
9429 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009430 if (old_handler == SIG_IGN) {
9431 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009432 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009433#if ENABLE_HUSH_TRAP
9434 if (!G_traps)
9435 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9436 free(G_traps[sig]);
9437 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9438#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009439 }
9440 }
9441}
9442
9443/* Called a few times only (or even once if "sh -c") */
9444static void install_special_sighandlers(void)
9445{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009446 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009447
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009448 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009449 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009450 if (G_interactive_fd) {
9451 mask |= SPECIAL_INTERACTIVE_SIGS;
9452 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009453 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009454 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009455 /* Careful, do not re-install handlers we already installed */
9456 if (G.special_sig_mask != mask) {
9457 unsigned diff = mask & ~G.special_sig_mask;
9458 G.special_sig_mask = mask;
9459 install_sighandlers(diff);
9460 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009461}
9462
9463#if ENABLE_HUSH_JOB
9464/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009465/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009466static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009467{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009468 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009469
9470 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009471 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009472 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9473 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009474 + (1 << SIGBUS ) * HUSH_DEBUG
9475 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009476 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009477 + (1 << SIGABRT)
9478 /* bash 3.2 seems to handle these just like 'fatal' ones */
9479 + (1 << SIGPIPE)
9480 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009481 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009482 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009483 * we never want to restore pgrp on exit, and this fn is not called
9484 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009485 /*+ (1 << SIGHUP )*/
9486 /*+ (1 << SIGTERM)*/
9487 /*+ (1 << SIGINT )*/
9488 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009489 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009490
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009491 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009492}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009493#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009494
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009495static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009496{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009497 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009498 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009499 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009500 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009501 break;
9502 case 'x':
9503 IF_HUSH_MODE_X(G_x_mode = state;)
9504 break;
9505 case 'o':
9506 if (!o_opt) {
9507 /* "set -+o" without parameter.
9508 * in bash, set -o produces this output:
9509 * pipefail off
9510 * and set +o:
9511 * set +o pipefail
9512 * We always use the second form.
9513 */
9514 const char *p = o_opt_strings;
9515 idx = 0;
9516 while (*p) {
9517 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9518 idx++;
9519 p += strlen(p) + 1;
9520 }
9521 break;
9522 }
9523 idx = index_in_strings(o_opt_strings, o_opt);
9524 if (idx >= 0) {
9525 G.o_opt[idx] = state;
9526 break;
9527 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009528 case 'e':
9529 G.o_opt[OPT_O_ERREXIT] = state;
9530 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009531 default:
9532 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009533 }
9534 return EXIT_SUCCESS;
9535}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009536
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009537int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009538int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009539{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009540 enum {
9541 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009542 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009543 };
9544 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009545 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009546 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009547 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009548 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009549
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009550 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009551 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009552 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009553
Denys Vlasenko10c01312011-05-11 11:49:21 +02009554#if ENABLE_HUSH_FAST
9555 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9556#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009557#if !BB_MMU
9558 G.argv0_for_re_execing = argv[0];
9559#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009560
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009561 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009562 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9563 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009564 shell_ver = xzalloc(sizeof(*shell_ver));
9565 shell_ver->flg_export = 1;
9566 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009567 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009568 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009569 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009570
Denys Vlasenko605067b2010-09-06 12:10:51 +02009571 /* Create shell local variables from the values
9572 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009573 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009574 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009575 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009576 if (e) while (*e) {
9577 char *value = strchr(*e, '=');
9578 if (value) { /* paranoia */
9579 cur_var->next = xzalloc(sizeof(*cur_var));
9580 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009581 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009582 cur_var->max_len = strlen(*e);
9583 cur_var->flg_export = 1;
9584 }
9585 e++;
9586 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009587 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009588 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9589 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009590
9591 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009592 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009593
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009594#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9595 /* Set (but not export) PS1/2 unless already set */
9596 if (!get_local_var_value("PS1"))
9597 set_local_var_from_halves("PS1", "\\w \\$ ");
9598 if (!get_local_var_value("PS2"))
9599 set_local_var_from_halves("PS2", "> ");
9600#endif
9601
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009602#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009603 /* Set (but not export) HOSTNAME unless already set */
9604 if (!get_local_var_value("HOSTNAME")) {
9605 struct utsname uts;
9606 uname(&uts);
9607 set_local_var_from_halves("HOSTNAME", uts.nodename);
9608 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009609 /* bash also exports SHLVL and _,
9610 * and sets (but doesn't export) the following variables:
9611 * BASH=/bin/bash
9612 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9613 * BASH_VERSION='3.2.0(1)-release'
9614 * HOSTTYPE=i386
9615 * MACHTYPE=i386-pc-linux-gnu
9616 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009617 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009618 * EUID=<NNNNN>
9619 * UID=<NNNNN>
9620 * GROUPS=()
9621 * LINES=<NNN>
9622 * COLUMNS=<NNN>
9623 * BASH_ARGC=()
9624 * BASH_ARGV=()
9625 * BASH_LINENO=()
9626 * BASH_SOURCE=()
9627 * DIRSTACK=()
9628 * PIPESTATUS=([0]="0")
9629 * HISTFILE=/<xxx>/.bash_history
9630 * HISTFILESIZE=500
9631 * HISTSIZE=500
9632 * MAILCHECK=60
9633 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9634 * SHELL=/bin/bash
9635 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9636 * TERM=dumb
9637 * OPTERR=1
9638 * OPTIND=1
9639 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009640 * PS4='+ '
9641 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009642#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009643
Denys Vlasenko5807e182018-02-08 19:19:04 +01009644#if ENABLE_HUSH_LINENO_VAR
9645 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009646 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9647 set_local_var(p, /*flags*/ 0);
9648 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9649 }
9650#endif
9651
Denis Vlasenko38f63192007-01-22 09:03:07 +00009652#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009653 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009654#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009655
Eric Andersen94ac2442001-05-22 19:05:18 +00009656 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009657 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009658
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009659 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009660
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009661 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009662 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009663 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009664 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009665 * in order to intercept (more) signals.
9666 */
9667
9668 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009669 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009670 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009671 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009672 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009673 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009674#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009675 "<:$:R:V:"
9676# if ENABLE_HUSH_FUNCTIONS
9677 "F:"
9678# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009679#endif
9680 );
9681 if (opt <= 0)
9682 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009683 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009684 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009685 /* Possibilities:
9686 * sh ... -c 'script'
9687 * sh ... -c 'script' ARG0 [ARG1...]
9688 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009689 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009690 * "" needs to be replaced with NULL
9691 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009692 * Note: the form without ARG0 never happens:
9693 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009694 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009695 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009696 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009697 G.root_ppid = getppid();
9698 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009699 G.global_argv = argv + optind;
9700 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009701 if (builtin_argc) {
9702 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9703 const struct built_in_command *x;
9704
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009705 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009706 x = find_builtin(optarg);
9707 if (x) { /* paranoia */
9708 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9709 G.global_argv += builtin_argc;
9710 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009711 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009712 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009713 }
9714 goto final_return;
9715 }
9716 if (!G.global_argv[0]) {
9717 /* -c 'script' (no params): prevent empty $0 */
9718 G.global_argv--; /* points to argv[i] of 'script' */
9719 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009720 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009721 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009722 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009723 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009724 goto final_return;
9725 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009726 /* Well, we cannot just declare interactiveness,
9727 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009728 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009729 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009730 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009731 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009732 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009733 case 'l':
9734 flags |= OPT_login;
9735 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009736#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009737 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009738 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009739 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009740 case '$': {
9741 unsigned long long empty_trap_mask;
9742
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009743 G.root_pid = bb_strtou(optarg, &optarg, 16);
9744 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009745 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9746 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009747 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9748 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009749 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009750 optarg++;
9751 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009752 optarg++;
9753 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9754 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009755 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009756 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009757# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009758 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009759 for (sig = 1; sig < NSIG; sig++) {
9760 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009761 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009762 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009763 }
9764 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009765# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009766 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009767# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009768 optarg++;
9769 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009770# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009771# if ENABLE_HUSH_FUNCTIONS
9772 /* nommu uses re-exec trick for "... | func | ...",
9773 * should allow "return".
9774 * This accidentally allows returns in subshells.
9775 */
9776 G_flag_return_in_progress = -1;
9777# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009778 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009779 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009780 case 'R':
9781 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009782 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009783 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009784# if ENABLE_HUSH_FUNCTIONS
9785 case 'F': {
9786 struct function *funcp = new_function(optarg);
9787 /* funcp->name is already set to optarg */
9788 /* funcp->body is set to NULL. It's a special case. */
9789 funcp->body_as_string = argv[optind];
9790 optind++;
9791 break;
9792 }
9793# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009794#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009795 case 'n':
9796 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009797 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009798 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009799 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009800 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009801#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009802 fprintf(stderr, "Usage: sh [FILE]...\n"
9803 " or: sh -c command [args]...\n\n");
9804 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009805#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009806 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009807#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009808 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009809 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009810
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009811 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9812 G.global_argc = argc - (optind - 1);
9813 G.global_argv = argv + (optind - 1);
9814 G.global_argv[0] = argv[0];
9815
Denys Vlasenkodea47882009-10-09 15:40:49 +02009816 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009817 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009818 G.root_ppid = getppid();
9819 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009820
9821 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009822 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009823 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009824 debug_printf("sourcing /etc/profile\n");
9825 input = fopen_for_read("/etc/profile");
9826 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009827 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009828 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009829 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009830 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009831 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009832 /* bash: after sourcing /etc/profile,
9833 * tries to source (in the given order):
9834 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009835 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009836 * bash also sources ~/.bash_logout on exit.
9837 * If called as sh, skips .bash_XXX files.
9838 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009839 }
9840
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009841 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9842 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009843 FILE *input;
9844 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009845 * "bash <script>" (which is never interactive (unless -i?))
9846 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009847 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009848 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009849 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009850 G.global_argc--;
9851 G.global_argv++;
9852 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009853 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009854 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009855 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009856 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009857 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009858 parse_and_run_file(input);
9859#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009860 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009861#endif
9862 goto final_return;
9863 }
9864
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009865 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009866 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009867 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009868
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009869 /* A shell is interactive if the '-i' flag was given,
9870 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009871 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009872 * no arguments remaining or the -s flag given
9873 * standard input is a terminal
9874 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009875 * Refer to Posix.2, the description of the 'sh' utility.
9876 */
9877#if ENABLE_HUSH_JOB
9878 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009879 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9880 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9881 if (G_saved_tty_pgrp < 0)
9882 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009883
9884 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009885 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009886 if (G_interactive_fd < 0) {
9887 /* try to dup to any fd */
9888 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009889 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009890 /* give up */
9891 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009892 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009893 }
9894 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009895// TODO: track & disallow any attempts of user
9896// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009897 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009898 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009899 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009900 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009901
Mike Frysinger38478a62009-05-20 04:48:06 -04009902 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009903 /* If we were run as 'hush &', sleep until we are
9904 * in the foreground (tty pgrp == our pgrp).
9905 * If we get started under a job aware app (like bash),
9906 * make sure we are now in charge so we don't fight over
9907 * who gets the foreground */
9908 while (1) {
9909 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009910 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9911 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009912 break;
9913 /* send TTIN to ourself (should stop us) */
9914 kill(- shell_pgrp, SIGTTIN);
9915 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009916 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009917
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009918 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009919 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009920
Mike Frysinger38478a62009-05-20 04:48:06 -04009921 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009922 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009923 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009924 /* Put ourselves in our own process group
9925 * (bash, too, does this only if ctty is available) */
9926 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9927 /* Grab control of the terminal */
9928 tcsetpgrp(G_interactive_fd, getpid());
9929 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009930 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009931
9932# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9933 {
9934 const char *hp = get_local_var_value("HISTFILE");
9935 if (!hp) {
9936 hp = get_local_var_value("HOME");
9937 if (hp)
9938 hp = concat_path_file(hp, ".hush_history");
9939 } else {
9940 hp = xstrdup(hp);
9941 }
9942 if (hp) {
9943 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009944 //set_local_var(xasprintf("HISTFILE=%s", ...));
9945 }
9946# if ENABLE_FEATURE_SH_HISTFILESIZE
9947 hp = get_local_var_value("HISTFILESIZE");
9948 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9949# endif
9950 }
9951# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009952 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009953 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009954 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009955#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009956 /* No job control compiled in, only prompt/line editing */
9957 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009958 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009959 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009960 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +02009961 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009962 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009963 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009964 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009965 }
9966 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009967 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009968 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009969 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009970 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009971#else
9972 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009973 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009974#endif
9975 /* bash:
9976 * if interactive but not a login shell, sources ~/.bashrc
9977 * (--norc turns this off, --rcfile <file> overrides)
9978 */
9979
9980 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009981 /* note: ash and hush share this string */
9982 printf("\n\n%s %s\n"
9983 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9984 "\n",
9985 bb_banner,
9986 "hush - the humble shell"
9987 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009988 }
9989
Denis Vlasenkof9375282009-04-05 19:13:39 +00009990 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009991
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009992 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009993 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009994}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009995
9996
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009997/*
9998 * Built-ins
9999 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010000static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010001{
10002 return 0;
10003}
10004
Denys Vlasenko265062d2017-01-10 15:13:30 +010010005#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010006static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010007{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010008 int argc = string_array_len(argv);
10009 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010010}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010011#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010012#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010013static int FAST_FUNC builtin_test(char **argv)
10014{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010015 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010016}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010017#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010018#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010019static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010020{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010021 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010022}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010023#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010024#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010025static int FAST_FUNC builtin_printf(char **argv)
10026{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010027 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010028}
10029#endif
10030
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010031#if ENABLE_HUSH_HELP
10032static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10033{
10034 const struct built_in_command *x;
10035
10036 printf(
10037 "Built-in commands:\n"
10038 "------------------\n");
10039 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10040 if (x->b_descr)
10041 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10042 }
10043 return EXIT_SUCCESS;
10044}
10045#endif
10046
10047#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10048static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10049{
10050 show_history(G.line_input_state);
10051 return EXIT_SUCCESS;
10052}
10053#endif
10054
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010055static char **skip_dash_dash(char **argv)
10056{
10057 argv++;
10058 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10059 argv++;
10060 return argv;
10061}
10062
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010063static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010064{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010065 const char *newdir;
10066
10067 argv = skip_dash_dash(argv);
10068 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010069 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010070 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010071 * bash says "bash: cd: HOME not set" and does nothing
10072 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010073 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010074 const char *home = get_local_var_value("HOME");
10075 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010076 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010077 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010078 /* Mimic bash message exactly */
10079 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010080 return EXIT_FAILURE;
10081 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010082 /* Read current dir (get_cwd(1) is inside) and set PWD.
10083 * Note: do not enforce exporting. If PWD was unset or unexported,
10084 * set it again, but do not export. bash does the same.
10085 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010086 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010087 return EXIT_SUCCESS;
10088}
10089
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010090static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10091{
10092 puts(get_cwd(0));
10093 return EXIT_SUCCESS;
10094}
10095
10096static int FAST_FUNC builtin_eval(char **argv)
10097{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010098 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010099
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010100 if (!argv[0])
10101 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010102
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010103 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010104 /* bash:
10105 * eval "echo Hi; done" ("done" is syntax error):
10106 * "echo Hi" will not execute too.
10107 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010108 parse_and_run_string(argv[0]);
10109 } else {
10110 /* "The eval utility shall construct a command by
10111 * concatenating arguments together, separating
10112 * each with a <space> character."
10113 */
10114 char *str, *p;
10115 unsigned len = 0;
10116 char **pp = argv;
10117 do
10118 len += strlen(*pp) + 1;
10119 while (*++pp);
10120 str = p = xmalloc(len);
10121 pp = argv;
10122 for (;;) {
10123 p = stpcpy(p, *pp);
10124 pp++;
10125 if (!*pp)
10126 break;
10127 *p++ = ' ';
10128 }
10129 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010130 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010131 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010132 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010133}
10134
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010135static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010136{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010137 argv = skip_dash_dash(argv);
10138 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010139 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010140
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010141 /* Careful: we can end up here after [v]fork. Do not restore
10142 * tty pgrp then, only top-level shell process does that */
10143 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10144 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10145
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010146 /* Saved-redirect fds, script fds and G_interactive_fd are still
10147 * open here. However, they are all CLOEXEC, and execv below
10148 * closes them. Try interactive "exec ls -l /proc/self/fd",
10149 * it should show no extra open fds in the "ls" process.
10150 * If we'd try to run builtins/NOEXECs, this would need improving.
10151 */
10152 //close_saved_fds_and_FILE_fds();
10153
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010154 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010155 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010156 * and tcsetpgrp, and this is inherently racy.
10157 */
10158 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010159}
10160
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010161static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010162{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010163 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010164
10165 /* interactive bash:
10166 * # trap "echo EEE" EXIT
10167 * # exit
10168 * exit
10169 * There are stopped jobs.
10170 * (if there are _stopped_ jobs, running ones don't count)
10171 * # exit
10172 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010173 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010174 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010175 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010176 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010177
10178 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010179 argv = skip_dash_dash(argv);
10180 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010181 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010182 /* mimic bash: exit 123abc == exit 255 + error msg */
10183 xfunc_error_retval = 255;
10184 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010185 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010186}
10187
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010188#if ENABLE_HUSH_TYPE
10189/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10190static int FAST_FUNC builtin_type(char **argv)
10191{
10192 int ret = EXIT_SUCCESS;
10193
10194 while (*++argv) {
10195 const char *type;
10196 char *path = NULL;
10197
10198 if (0) {} /* make conditional compile easier below */
10199 /*else if (find_alias(*argv))
10200 type = "an alias";*/
10201#if ENABLE_HUSH_FUNCTIONS
10202 else if (find_function(*argv))
10203 type = "a function";
10204#endif
10205 else if (find_builtin(*argv))
10206 type = "a shell builtin";
10207 else if ((path = find_in_path(*argv)) != NULL)
10208 type = path;
10209 else {
10210 bb_error_msg("type: %s: not found", *argv);
10211 ret = EXIT_FAILURE;
10212 continue;
10213 }
10214
10215 printf("%s is %s\n", *argv, type);
10216 free(path);
10217 }
10218
10219 return ret;
10220}
10221#endif
10222
10223#if ENABLE_HUSH_READ
10224/* Interruptibility of read builtin in bash
10225 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10226 *
10227 * Empty trap makes read ignore corresponding signal, for any signal.
10228 *
10229 * SIGINT:
10230 * - terminates non-interactive shell;
10231 * - interrupts read in interactive shell;
10232 * if it has non-empty trap:
10233 * - executes trap and returns to command prompt in interactive shell;
10234 * - executes trap and returns to read in non-interactive shell;
10235 * SIGTERM:
10236 * - is ignored (does not interrupt) read in interactive shell;
10237 * - terminates non-interactive shell;
10238 * if it has non-empty trap:
10239 * - executes trap and returns to read;
10240 * SIGHUP:
10241 * - terminates shell (regardless of interactivity);
10242 * if it has non-empty trap:
10243 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010244 * SIGCHLD from children:
10245 * - does not interrupt read regardless of interactivity:
10246 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010247 */
10248static int FAST_FUNC builtin_read(char **argv)
10249{
10250 const char *r;
10251 char *opt_n = NULL;
10252 char *opt_p = NULL;
10253 char *opt_t = NULL;
10254 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010255 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010256 const char *ifs;
10257 int read_flags;
10258
10259 /* "!": do not abort on errors.
10260 * Option string must start with "sr" to match BUILTIN_READ_xxx
10261 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010262 read_flags = getopt32(argv,
10263#if BASH_READ_D
10264 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10265#else
10266 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10267#endif
10268 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010269 if (read_flags == (uint32_t)-1)
10270 return EXIT_FAILURE;
10271 argv += optind;
10272 ifs = get_local_var_value("IFS"); /* can be NULL */
10273
10274 again:
10275 r = shell_builtin_read(set_local_var_from_halves,
10276 argv,
10277 ifs,
10278 read_flags,
10279 opt_n,
10280 opt_p,
10281 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010282 opt_u,
10283 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010284 );
10285
10286 if ((uintptr_t)r == 1 && errno == EINTR) {
10287 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010288 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010289 goto again;
10290 }
10291
10292 if ((uintptr_t)r > 1) {
10293 bb_error_msg("%s", r);
10294 r = (char*)(uintptr_t)1;
10295 }
10296
10297 return (uintptr_t)r;
10298}
10299#endif
10300
10301#if ENABLE_HUSH_UMASK
10302static int FAST_FUNC builtin_umask(char **argv)
10303{
10304 int rc;
10305 mode_t mask;
10306
10307 rc = 1;
10308 mask = umask(0);
10309 argv = skip_dash_dash(argv);
10310 if (argv[0]) {
10311 mode_t old_mask = mask;
10312
10313 /* numeric umasks are taken as-is */
10314 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10315 if (!isdigit(argv[0][0]))
10316 mask ^= 0777;
10317 mask = bb_parse_mode(argv[0], mask);
10318 if (!isdigit(argv[0][0]))
10319 mask ^= 0777;
10320 if ((unsigned)mask > 0777) {
10321 mask = old_mask;
10322 /* bash messages:
10323 * bash: umask: 'q': invalid symbolic mode operator
10324 * bash: umask: 999: octal number out of range
10325 */
10326 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10327 rc = 0;
10328 }
10329 } else {
10330 /* Mimic bash */
10331 printf("%04o\n", (unsigned) mask);
10332 /* fall through and restore mask which we set to 0 */
10333 }
10334 umask(mask);
10335
10336 return !rc; /* rc != 0 - success */
10337}
10338#endif
10339
Denys Vlasenko41ade052017-01-08 18:56:24 +010010340#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010341static void print_escaped(const char *s)
10342{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010343 if (*s == '\'')
10344 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010345 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010346 const char *p = strchrnul(s, '\'');
10347 /* print 'xxxx', possibly just '' */
10348 printf("'%.*s'", (int)(p - s), s);
10349 if (*p == '\0')
10350 break;
10351 s = p;
10352 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010353 /* s points to '; print "'''...'''" */
10354 putchar('"');
10355 do putchar('\''); while (*++s == '\'');
10356 putchar('"');
10357 } while (*s);
10358}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010359#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010360
Denys Vlasenko1e660422017-07-17 21:10:50 +020010361#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010362static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010363{
10364 do {
10365 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010366 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010367
10368 /* So far we do not check that name is valid (TODO?) */
10369
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010370 if (*name_end == '\0') {
10371 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010372
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010373 vpp = get_ptr_to_local_var(name, name_end - name);
10374 var = vpp ? *vpp : NULL;
10375
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010376 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010377 /* export -n NAME (without =VALUE) */
10378 if (var) {
10379 var->flg_export = 0;
10380 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10381 unsetenv(name);
10382 } /* else: export -n NOT_EXISTING_VAR: no-op */
10383 continue;
10384 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010385 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010386 /* export NAME (without =VALUE) */
10387 if (var) {
10388 var->flg_export = 1;
10389 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10390 putenv(var->varstr);
10391 continue;
10392 }
10393 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010394 if (flags & SETFLAG_MAKE_RO) {
10395 /* readonly NAME (without =VALUE) */
10396 if (var) {
10397 var->flg_read_only = 1;
10398 continue;
10399 }
10400 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010401# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010402 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010403 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010404 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10405 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010406 /* "local x=abc; ...; local x" - ignore second local decl */
10407 continue;
10408 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010409 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010410# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010411 /* Exporting non-existing variable.
10412 * bash does not put it in environment,
10413 * but remembers that it is exported,
10414 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010415 * We just set it to "" and export.
10416 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010417 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010418 * bash sets the value to "".
10419 */
10420 /* Or, it's "readonly NAME" (without =VALUE).
10421 * bash remembers NAME and disallows its creation
10422 * in the future.
10423 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010424 name = xasprintf("%s=", name);
10425 } else {
10426 /* (Un)exporting/making local NAME=VALUE */
10427 name = xstrdup(name);
10428 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010429 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010430 if (set_local_var(name, flags))
10431 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010432 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010433 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010434}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010435#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010436
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010437#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010438static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010439{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010440 unsigned opt_unexport;
10441
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010442#if ENABLE_HUSH_EXPORT_N
10443 /* "!": do not abort on errors */
10444 opt_unexport = getopt32(argv, "!n");
10445 if (opt_unexport == (uint32_t)-1)
10446 return EXIT_FAILURE;
10447 argv += optind;
10448#else
10449 opt_unexport = 0;
10450 argv++;
10451#endif
10452
10453 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010454 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010455 if (e) {
10456 while (*e) {
10457#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010458 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010459#else
10460 /* ash emits: export VAR='VAL'
10461 * bash: declare -x VAR="VAL"
10462 * we follow ash example */
10463 const char *s = *e++;
10464 const char *p = strchr(s, '=');
10465
10466 if (!p) /* wtf? take next variable */
10467 continue;
10468 /* export var= */
10469 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010470 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010471 putchar('\n');
10472#endif
10473 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010474 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010475 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010476 return EXIT_SUCCESS;
10477 }
10478
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010479 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010480}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010481#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010482
Denys Vlasenko295fef82009-06-03 12:47:26 +020010483#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010484static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010485{
10486 if (G.func_nest_level == 0) {
10487 bb_error_msg("%s: not in a function", argv[0]);
10488 return EXIT_FAILURE; /* bash compat */
10489 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010490 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010491 /* Since all builtins run in a nested variable level,
10492 * need to use level - 1 here. Or else the variable will be removed at once
10493 * after builtin returns.
10494 */
10495 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010496}
10497#endif
10498
Denys Vlasenko1e660422017-07-17 21:10:50 +020010499#if ENABLE_HUSH_READONLY
10500static int FAST_FUNC builtin_readonly(char **argv)
10501{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010502 argv++;
10503 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010504 /* bash: readonly [-p]: list all readonly VARs
10505 * (-p has no effect in bash)
10506 */
10507 struct variable *e;
10508 for (e = G.top_var; e; e = e->next) {
10509 if (e->flg_read_only) {
10510//TODO: quote value: readonly VAR='VAL'
10511 printf("readonly %s\n", e->varstr);
10512 }
10513 }
10514 return EXIT_SUCCESS;
10515 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010516 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010517}
10518#endif
10519
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010520#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010521/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10522static int FAST_FUNC builtin_unset(char **argv)
10523{
10524 int ret;
10525 unsigned opts;
10526
10527 /* "!": do not abort on errors */
10528 /* "+": stop at 1st non-option */
10529 opts = getopt32(argv, "!+vf");
10530 if (opts == (unsigned)-1)
10531 return EXIT_FAILURE;
10532 if (opts == 3) {
10533 bb_error_msg("unset: -v and -f are exclusive");
10534 return EXIT_FAILURE;
10535 }
10536 argv += optind;
10537
10538 ret = EXIT_SUCCESS;
10539 while (*argv) {
10540 if (!(opts & 2)) { /* not -f */
10541 if (unset_local_var(*argv)) {
10542 /* unset <nonexistent_var> doesn't fail.
10543 * Error is when one tries to unset RO var.
10544 * Message was printed by unset_local_var. */
10545 ret = EXIT_FAILURE;
10546 }
10547 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010548# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010549 else {
10550 unset_func(*argv);
10551 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010552# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010553 argv++;
10554 }
10555 return ret;
10556}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010557#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010558
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010559#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010560/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10561 * built-in 'set' handler
10562 * SUSv3 says:
10563 * set [-abCefhmnuvx] [-o option] [argument...]
10564 * set [+abCefhmnuvx] [+o option] [argument...]
10565 * set -- [argument...]
10566 * set -o
10567 * set +o
10568 * Implementations shall support the options in both their hyphen and
10569 * plus-sign forms. These options can also be specified as options to sh.
10570 * Examples:
10571 * Write out all variables and their values: set
10572 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10573 * Turn on the -x and -v options: set -xv
10574 * Unset all positional parameters: set --
10575 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10576 * Set the positional parameters to the expansion of x, even if x expands
10577 * with a leading '-' or '+': set -- $x
10578 *
10579 * So far, we only support "set -- [argument...]" and some of the short names.
10580 */
10581static int FAST_FUNC builtin_set(char **argv)
10582{
10583 int n;
10584 char **pp, **g_argv;
10585 char *arg = *++argv;
10586
10587 if (arg == NULL) {
10588 struct variable *e;
10589 for (e = G.top_var; e; e = e->next)
10590 puts(e->varstr);
10591 return EXIT_SUCCESS;
10592 }
10593
10594 do {
10595 if (strcmp(arg, "--") == 0) {
10596 ++argv;
10597 goto set_argv;
10598 }
10599 if (arg[0] != '+' && arg[0] != '-')
10600 break;
10601 for (n = 1; arg[n]; ++n) {
10602 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10603 goto error;
10604 if (arg[n] == 'o' && argv[1])
10605 argv++;
10606 }
10607 } while ((arg = *++argv) != NULL);
10608 /* Now argv[0] is 1st argument */
10609
10610 if (arg == NULL)
10611 return EXIT_SUCCESS;
10612 set_argv:
10613
10614 /* NB: G.global_argv[0] ($0) is never freed/changed */
10615 g_argv = G.global_argv;
10616 if (G.global_args_malloced) {
10617 pp = g_argv;
10618 while (*++pp)
10619 free(*pp);
10620 g_argv[1] = NULL;
10621 } else {
10622 G.global_args_malloced = 1;
10623 pp = xzalloc(sizeof(pp[0]) * 2);
10624 pp[0] = g_argv[0]; /* retain $0 */
10625 g_argv = pp;
10626 }
10627 /* This realloc's G.global_argv */
10628 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10629
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010630 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010631
10632 return EXIT_SUCCESS;
10633
10634 /* Nothing known, so abort */
10635 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010636 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010637 return EXIT_FAILURE;
10638}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010639#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010640
10641static int FAST_FUNC builtin_shift(char **argv)
10642{
10643 int n = 1;
10644 argv = skip_dash_dash(argv);
10645 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010646 n = bb_strtou(argv[0], NULL, 10);
10647 if (errno || n < 0) {
10648 /* shared string with ash.c */
10649 bb_error_msg("Illegal number: %s", argv[0]);
10650 /*
10651 * ash aborts in this case.
10652 * bash prints error message and set $? to 1.
10653 * Interestingly, for "shift 99999" bash does not
10654 * print error message, but does set $? to 1
10655 * (and does no shifting at all).
10656 */
10657 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010658 }
10659 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010660 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010661 int m = 1;
10662 while (m <= n)
10663 free(G.global_argv[m++]);
10664 }
10665 G.global_argc -= n;
10666 memmove(&G.global_argv[1], &G.global_argv[n+1],
10667 G.global_argc * sizeof(G.global_argv[0]));
10668 return EXIT_SUCCESS;
10669 }
10670 return EXIT_FAILURE;
10671}
10672
Denys Vlasenko74d40582017-08-11 01:32:46 +020010673#if ENABLE_HUSH_GETOPTS
10674static int FAST_FUNC builtin_getopts(char **argv)
10675{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010676/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10677
Denys Vlasenko74d40582017-08-11 01:32:46 +020010678TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010679If a required argument is not found, and getopts is not silent,
10680a question mark (?) is placed in VAR, OPTARG is unset, and a
10681diagnostic message is printed. If getopts is silent, then a
10682colon (:) is placed in VAR and OPTARG is set to the option
10683character found.
10684
10685Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010686
10687"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010688*/
10689 char cbuf[2];
10690 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010691 int c, n, exitcode, my_opterr;
10692 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010693
10694 optstring = *++argv;
10695 if (!optstring || !(var = *++argv)) {
10696 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10697 return EXIT_FAILURE;
10698 }
10699
Denys Vlasenko238ff982017-08-29 13:38:30 +020010700 if (argv[1])
10701 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10702 else
10703 argv = G.global_argv;
10704 cbuf[1] = '\0';
10705
10706 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010707 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010708 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010709 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010710 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010711 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010712
10713 /* getopts stops on first non-option. Add "+" to force that */
10714 /*if (optstring[0] != '+')*/ {
10715 char *s = alloca(strlen(optstring) + 2);
10716 sprintf(s, "+%s", optstring);
10717 optstring = s;
10718 }
10719
Denys Vlasenko238ff982017-08-29 13:38:30 +020010720 /* Naively, now we should just
10721 * cp = get_local_var_value("OPTIND");
10722 * optind = cp ? atoi(cp) : 0;
10723 * optarg = NULL;
10724 * opterr = my_opterr;
10725 * c = getopt(string_array_len(argv), argv, optstring);
10726 * and be done? Not so fast...
10727 * Unlike normal getopt() usage in C programs, here
10728 * each successive call will (usually) have the same argv[] CONTENTS,
10729 * but not the ADDRESSES. Worse yet, it's possible that between
10730 * invocations of "getopts", there will be calls to shell builtins
10731 * which use getopt() internally. Example:
10732 * while getopts "abc" RES -a -bc -abc de; do
10733 * unset -ff func
10734 * done
10735 * This would not work correctly: getopt() call inside "unset"
10736 * modifies internal libc state which is tracking position in
10737 * multi-option strings ("-abc"). At best, it can skip options
10738 * or return the same option infinitely. With glibc implementation
10739 * of getopt(), it would use outright invalid pointers and return
10740 * garbage even _without_ "unset" mangling internal state.
10741 *
10742 * We resort to resetting getopt() state and calling it N times,
10743 * until we get Nth result (or failure).
10744 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10745 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010746 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010747 count = 0;
10748 n = string_array_len(argv);
10749 do {
10750 optarg = NULL;
10751 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10752 c = getopt(n, argv, optstring);
10753 if (c < 0)
10754 break;
10755 count++;
10756 } while (count <= G.getopt_count);
10757
10758 /* Set OPTIND. Prevent resetting of the magic counter! */
10759 set_local_var_from_halves("OPTIND", utoa(optind));
10760 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010761 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010762
10763 /* Set OPTARG */
10764 /* Always set or unset, never left as-is, even on exit/error:
10765 * "If no option was found, or if the option that was found
10766 * does not have an option-argument, OPTARG shall be unset."
10767 */
10768 cp = optarg;
10769 if (c == '?') {
10770 /* If ":optstring" and unknown option is seen,
10771 * it is stored to OPTARG.
10772 */
10773 if (optstring[1] == ':') {
10774 cbuf[0] = optopt;
10775 cp = cbuf;
10776 }
10777 }
10778 if (cp)
10779 set_local_var_from_halves("OPTARG", cp);
10780 else
10781 unset_local_var("OPTARG");
10782
10783 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010784 exitcode = EXIT_SUCCESS;
10785 if (c < 0) { /* -1: end of options */
10786 exitcode = EXIT_FAILURE;
10787 c = '?';
10788 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010789
Denys Vlasenko238ff982017-08-29 13:38:30 +020010790 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010791 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010792 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010793
Denys Vlasenko74d40582017-08-11 01:32:46 +020010794 return exitcode;
10795}
10796#endif
10797
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010798static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010799{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010800 char *arg_path, *filename;
10801 FILE *input;
10802 save_arg_t sv;
10803 char *args_need_save;
10804#if ENABLE_HUSH_FUNCTIONS
10805 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010806#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010807
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010808 argv = skip_dash_dash(argv);
10809 filename = argv[0];
10810 if (!filename) {
10811 /* bash says: "bash: .: filename argument required" */
10812 return 2; /* bash compat */
10813 }
10814 arg_path = NULL;
10815 if (!strchr(filename, '/')) {
10816 arg_path = find_in_path(filename);
10817 if (arg_path)
10818 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010819 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010820 errno = ENOENT;
10821 bb_simple_perror_msg(filename);
10822 return EXIT_FAILURE;
10823 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010824 }
10825 input = remember_FILE(fopen_or_warn(filename, "r"));
10826 free(arg_path);
10827 if (!input) {
10828 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10829 /* POSIX: non-interactive shell should abort here,
10830 * not merely fail. So far no one complained :)
10831 */
10832 return EXIT_FAILURE;
10833 }
10834
10835#if ENABLE_HUSH_FUNCTIONS
10836 sv_flg = G_flag_return_in_progress;
10837 /* "we are inside sourced file, ok to use return" */
10838 G_flag_return_in_progress = -1;
10839#endif
10840 args_need_save = argv[1]; /* used as a boolean variable */
10841 if (args_need_save)
10842 save_and_replace_G_args(&sv, argv);
10843
10844 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10845 G.last_exitcode = 0;
10846 parse_and_run_file(input);
10847 fclose_and_forget(input);
10848
10849 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10850 restore_G_args(&sv, argv);
10851#if ENABLE_HUSH_FUNCTIONS
10852 G_flag_return_in_progress = sv_flg;
10853#endif
10854
10855 return G.last_exitcode;
10856}
10857
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010858#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010859static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010860{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010861 int sig;
10862 char *new_cmd;
10863
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010864 if (!G_traps)
10865 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010866
10867 argv++;
10868 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010869 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010870 /* No args: print all trapped */
10871 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010872 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010873 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010874 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010875 /* note: bash adds "SIG", but only if invoked
10876 * as "bash". If called as "sh", or if set -o posix,
10877 * then it prints short signal names.
10878 * We are printing short names: */
10879 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010880 }
10881 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010882 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010883 return EXIT_SUCCESS;
10884 }
10885
10886 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010887 /* If first arg is a number: reset all specified signals */
10888 sig = bb_strtou(*argv, NULL, 10);
10889 if (errno == 0) {
10890 int ret;
10891 process_sig_list:
10892 ret = EXIT_SUCCESS;
10893 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010894 sighandler_t handler;
10895
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010896 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010897 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010898 ret = EXIT_FAILURE;
10899 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010900 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010901 continue;
10902 }
10903
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010904 free(G_traps[sig]);
10905 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010906
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010907 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010908 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010909
10910 /* There is no signal for 0 (EXIT) */
10911 if (sig == 0)
10912 continue;
10913
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010914 if (new_cmd)
10915 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10916 else
10917 /* We are removing trap handler */
10918 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010919 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010920 }
10921 return ret;
10922 }
10923
10924 if (!argv[1]) { /* no second arg */
10925 bb_error_msg("trap: invalid arguments");
10926 return EXIT_FAILURE;
10927 }
10928
10929 /* First arg is "-": reset all specified to default */
10930 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10931 /* Everything else: set arg as signal handler
10932 * (includes "" case, which ignores signal) */
10933 if (argv[0][0] == '-') {
10934 if (argv[0][1] == '\0') { /* "-" */
10935 /* new_cmd remains NULL: "reset these sigs" */
10936 goto reset_traps;
10937 }
10938 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10939 argv++;
10940 }
10941 /* else: "-something", no special meaning */
10942 }
10943 new_cmd = *argv;
10944 reset_traps:
10945 argv++;
10946 goto process_sig_list;
10947}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010948#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010949
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010950#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010951static struct pipe *parse_jobspec(const char *str)
10952{
10953 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010954 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010955
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010956 if (sscanf(str, "%%%u", &jobnum) != 1) {
10957 if (str[0] != '%'
10958 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10959 ) {
10960 bb_error_msg("bad argument '%s'", str);
10961 return NULL;
10962 }
10963 /* It is "%%", "%+" or "%" - current job */
10964 jobnum = G.last_jobid;
10965 if (jobnum == 0) {
10966 bb_error_msg("no current job");
10967 return NULL;
10968 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010969 }
10970 for (pi = G.job_list; pi; pi = pi->next) {
10971 if (pi->jobid == jobnum) {
10972 return pi;
10973 }
10974 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010975 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010976 return NULL;
10977}
10978
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010979static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10980{
10981 struct pipe *job;
10982 const char *status_string;
10983
10984 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10985 for (job = G.job_list; job; job = job->next) {
10986 if (job->alive_cmds == job->stopped_cmds)
10987 status_string = "Stopped";
10988 else
10989 status_string = "Running";
10990
10991 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10992 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010993
10994 clean_up_last_dead_job();
10995
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010996 return EXIT_SUCCESS;
10997}
10998
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010999/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011000static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011001{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011002 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011003 struct pipe *pi;
11004
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011005 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011006 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011007
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011008 /* If they gave us no args, assume they want the last backgrounded task */
11009 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011010 for (pi = G.job_list; pi; pi = pi->next) {
11011 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011012 goto found;
11013 }
11014 }
11015 bb_error_msg("%s: no current job", argv[0]);
11016 return EXIT_FAILURE;
11017 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011018
11019 pi = parse_jobspec(argv[1]);
11020 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011021 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011022 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011023 /* TODO: bash prints a string representation
11024 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011025 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011026 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011027 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011028 }
11029
11030 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011031 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11032 for (i = 0; i < pi->num_cmds; i++) {
11033 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011034 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011035 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011036
11037 i = kill(- pi->pgrp, SIGCONT);
11038 if (i < 0) {
11039 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011040 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011041 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011042 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011043 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011044 }
11045
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011046 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011047 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011048 return checkjobs_and_fg_shell(pi);
11049 }
11050 return EXIT_SUCCESS;
11051}
11052#endif
11053
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011054#if ENABLE_HUSH_KILL
11055static int FAST_FUNC builtin_kill(char **argv)
11056{
11057 int ret = 0;
11058
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011059# if ENABLE_HUSH_JOB
11060 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11061 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011062
11063 do {
11064 struct pipe *pi;
11065 char *dst;
11066 int j, n;
11067
11068 if (argv[i][0] != '%')
11069 continue;
11070 /*
11071 * "kill %N" - job kill
11072 * Converting to pgrp / pid kill
11073 */
11074 pi = parse_jobspec(argv[i]);
11075 if (!pi) {
11076 /* Eat bad jobspec */
11077 j = i;
11078 do {
11079 j++;
11080 argv[j - 1] = argv[j];
11081 } while (argv[j]);
11082 ret = 1;
11083 i--;
11084 continue;
11085 }
11086 /*
11087 * In jobs started under job control, we signal
11088 * entire process group by kill -PGRP_ID.
11089 * This happens, f.e., in interactive shell.
11090 *
11091 * Otherwise, we signal each child via
11092 * kill PID1 PID2 PID3.
11093 * Testcases:
11094 * sh -c 'sleep 1|sleep 1 & kill %1'
11095 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11096 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11097 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011098 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011099 dst = alloca(n * sizeof(int)*4);
11100 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011101 if (G_interactive_fd)
11102 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011103 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011104 struct command *cmd = &pi->cmds[j];
11105 /* Skip exited members of the job */
11106 if (cmd->pid == 0)
11107 continue;
11108 /*
11109 * kill_main has matching code to expect
11110 * leading space. Needed to not confuse
11111 * negative pids with "kill -SIGNAL_NO" syntax
11112 */
11113 dst += sprintf(dst, " %u", (int)cmd->pid);
11114 }
11115 *dst = '\0';
11116 } while (argv[++i]);
11117 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011118# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011119
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011120 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011121 ret = run_applet_main(argv, kill_main);
11122 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011123 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011124 return ret;
11125}
11126#endif
11127
11128#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011129/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011130#if !ENABLE_HUSH_JOB
11131# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11132#endif
11133static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011134{
11135 int ret = 0;
11136 for (;;) {
11137 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011138 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011139
Denys Vlasenko830ea352016-11-08 04:59:11 +010011140 if (!sigisemptyset(&G.pending_set))
11141 goto check_sig;
11142
Denys Vlasenko7e675362016-10-28 21:57:31 +020011143 /* waitpid is not interruptible by SA_RESTARTed
11144 * signals which we use. Thus, this ugly dance:
11145 */
11146
11147 /* Make sure possible SIGCHLD is stored in kernel's
11148 * pending signal mask before we call waitpid.
11149 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011150 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011151 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011152 sigfillset(&oldset); /* block all signals, remember old set */
11153 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011154
11155 if (!sigisemptyset(&G.pending_set)) {
11156 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011157 goto restore;
11158 }
11159
11160 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011161/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011162 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011163 debug_printf_exec("checkjobs:%d\n", ret);
11164#if ENABLE_HUSH_JOB
11165 if (waitfor_pipe) {
11166 int rcode = job_exited_or_stopped(waitfor_pipe);
11167 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11168 if (rcode >= 0) {
11169 ret = rcode;
11170 sigprocmask(SIG_SETMASK, &oldset, NULL);
11171 break;
11172 }
11173 }
11174#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011175 /* if ECHILD, there are no children (ret is -1 or 0) */
11176 /* if ret == 0, no children changed state */
11177 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011178 if (errno == ECHILD || ret) {
11179 ret--;
11180 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011181 ret = 0;
11182 sigprocmask(SIG_SETMASK, &oldset, NULL);
11183 break;
11184 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011185 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011186 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11187 /* Note: sigsuspend invokes signal handler */
11188 sigsuspend(&oldset);
11189 restore:
11190 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011191 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011192 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011193 sig = check_and_run_traps();
11194 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011195 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011196 ret = 128 + sig;
11197 break;
11198 }
11199 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11200 }
11201 return ret;
11202}
11203
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011204static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011205{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011206 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011207 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011208
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011209 argv = skip_dash_dash(argv);
11210 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011211 /* Don't care about wait results */
11212 /* Note 1: must wait until there are no more children */
11213 /* Note 2: must be interruptible */
11214 /* Examples:
11215 * $ sleep 3 & sleep 6 & wait
11216 * [1] 30934 sleep 3
11217 * [2] 30935 sleep 6
11218 * [1] Done sleep 3
11219 * [2] Done sleep 6
11220 * $ sleep 3 & sleep 6 & wait
11221 * [1] 30936 sleep 3
11222 * [2] 30937 sleep 6
11223 * [1] Done sleep 3
11224 * ^C <-- after ~4 sec from keyboard
11225 * $
11226 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011227 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011228 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011229
Denys Vlasenko7e675362016-10-28 21:57:31 +020011230 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011231 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011232 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011233#if ENABLE_HUSH_JOB
11234 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011235 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011236 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011237 wait_pipe = parse_jobspec(*argv);
11238 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011239 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011240 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011241 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011242 } else {
11243 /* waiting on "last dead job" removes it */
11244 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011245 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011246 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011247 /* else: parse_jobspec() already emitted error msg */
11248 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011249 }
11250#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011251 /* mimic bash message */
11252 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011253 ret = EXIT_FAILURE;
11254 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011255 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011256
Denys Vlasenko7e675362016-10-28 21:57:31 +020011257 /* Do we have such child? */
11258 ret = waitpid(pid, &status, WNOHANG);
11259 if (ret < 0) {
11260 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011261 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011262 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011263 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011264 /* "wait $!" but last bg task has already exited. Try:
11265 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11266 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011267 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011268 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011269 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011270 } else {
11271 /* Example: "wait 1". mimic bash message */
11272 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011273 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011274 } else {
11275 /* ??? */
11276 bb_perror_msg("wait %s", *argv);
11277 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011278 continue; /* bash checks all argv[] */
11279 }
11280 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011281 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011282 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011283 } else {
11284 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011285 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011286 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011287 if (WIFSIGNALED(status))
11288 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011289 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011290 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011291
11292 return ret;
11293}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011294#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011295
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011296#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11297static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11298{
11299 if (argv[1]) {
11300 def = bb_strtou(argv[1], NULL, 10);
11301 if (errno || def < def_min || argv[2]) {
11302 bb_error_msg("%s: bad arguments", argv[0]);
11303 def = UINT_MAX;
11304 }
11305 }
11306 return def;
11307}
11308#endif
11309
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011310#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011311static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011312{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011313 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011314 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011315 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011316 /* if we came from builtin_continue(), need to undo "= 1" */
11317 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011318 return EXIT_SUCCESS; /* bash compat */
11319 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011320 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011321
11322 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11323 if (depth == UINT_MAX)
11324 G.flag_break_continue = BC_BREAK;
11325 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011326 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011327
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011328 return EXIT_SUCCESS;
11329}
11330
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011331static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011332{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011333 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11334 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011335}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011336#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011337
11338#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011339static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011340{
11341 int rc;
11342
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011343 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011344 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11345 return EXIT_FAILURE; /* bash compat */
11346 }
11347
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011348 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011349
11350 /* bash:
11351 * out of range: wraps around at 256, does not error out
11352 * non-numeric param:
11353 * f() { false; return qwe; }; f; echo $?
11354 * bash: return: qwe: numeric argument required <== we do this
11355 * 255 <== we also do this
11356 */
11357 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11358 return rc;
11359}
11360#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011361
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011362#if ENABLE_HUSH_TIMES
11363static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11364{
11365 static const uint8_t times_tbl[] ALIGN1 = {
11366 ' ', offsetof(struct tms, tms_utime),
11367 '\n', offsetof(struct tms, tms_stime),
11368 ' ', offsetof(struct tms, tms_cutime),
11369 '\n', offsetof(struct tms, tms_cstime),
11370 0
11371 };
11372 const uint8_t *p;
11373 unsigned clk_tck;
11374 struct tms buf;
11375
11376 clk_tck = bb_clk_tck();
11377
11378 times(&buf);
11379 p = times_tbl;
11380 do {
11381 unsigned sec, frac;
11382 unsigned long t;
11383 t = *(clock_t *)(((char *) &buf) + p[1]);
11384 sec = t / clk_tck;
11385 frac = t % clk_tck;
11386 printf("%um%u.%03us%c",
11387 sec / 60, sec % 60,
11388 (frac * 1000) / clk_tck,
11389 p[0]);
11390 p += 2;
11391 } while (*p);
11392
11393 return EXIT_SUCCESS;
11394}
11395#endif
11396
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011397#if ENABLE_HUSH_MEMLEAK
11398static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11399{
11400 void *p;
11401 unsigned long l;
11402
11403# ifdef M_TRIM_THRESHOLD
11404 /* Optional. Reduces probability of false positives */
11405 malloc_trim(0);
11406# endif
11407 /* Crude attempt to find where "free memory" starts,
11408 * sans fragmentation. */
11409 p = malloc(240);
11410 l = (unsigned long)p;
11411 free(p);
11412 p = malloc(3400);
11413 if (l < (unsigned long)p) l = (unsigned long)p;
11414 free(p);
11415
11416
11417# if 0 /* debug */
11418 {
11419 struct mallinfo mi = mallinfo();
11420 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11421 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11422 }
11423# endif
11424
11425 if (!G.memleak_value)
11426 G.memleak_value = l;
11427
11428 l -= G.memleak_value;
11429 if ((long)l < 0)
11430 l = 0;
11431 l /= 1024;
11432 if (l > 127)
11433 l = 127;
11434
11435 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11436 return l;
11437}
11438#endif